1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2011, AdaCore o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
30 @c GNAT_UGN Style Guide
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
100 @set PLATFORM OpenVMS
105 @c The ARG is an optional argument. To be used for macro arguments in
106 @c their documentation (@defmac).
108 @r{[}@var{\varname\}@r{]}@c
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
124 @include gcc-common.texi
126 @setchapternewpage odd
131 @title @value{EDITION} User's Guide
135 @titlefont{@i{@value{PLATFORM}}}
141 @subtitle GNAT, The GNU Ada Compiler
146 @vskip 0pt plus 1filll
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
157 @value{EDITION} User's Guide @value{PLATFORM}
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * The GNAT Metric Tool gnatmetric::
183 * File Name Krunching Using gnatkr::
184 * Preprocessing Using gnatprep::
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties Using gnatcheck::
194 * Creating Sample Bodies Using gnatstub::
195 * Generating Ada Bindings for C and C++ headers::
196 * Other Utility Programs::
197 * Running and Debugging Ada Programs::
199 * Code Coverage and Profiling::
202 * Compatibility with HP Ada::
204 * Platform-Specific Information for the Run-Time Libraries::
205 * Example of Binder Output File::
206 * Elaboration Order Handling in GNAT::
207 * Conditional Compilation::
209 * Compatibility and Porting Guide::
211 * Microsoft Windows Topics::
213 * GNU Free Documentation License::
216 --- The Detailed Node Listing ---
220 * What This Guide Contains::
221 * What You Should Know before Reading This Guide::
222 * Related Information::
225 Getting Started with GNAT
228 * Running a Simple Ada Program::
229 * Running a Program with Multiple Units::
230 * Using the gnatmake Utility::
232 * Editing with Emacs::
235 * Introduction to GPS::
238 The GNAT Compilation Model
240 * Source Representation::
241 * Foreign Language Representation::
242 * File Naming Rules::
243 * Using Other File Names::
244 * Alternative File Naming Schemes::
245 * Generating Object Files::
246 * Source Dependencies::
247 * The Ada Library Information Files::
248 * Binding an Ada Program::
249 * Mixed Language Programming::
251 * Building Mixed Ada & C++ Programs::
252 * Comparison between GNAT and C/C++ Compilation Models::
254 * Comparison between GNAT and Conventional Ada Library Models::
256 * Placement of temporary files::
259 Foreign Language Representation
262 * Other 8-Bit Codes::
263 * Wide Character Encodings::
265 Compiling Ada Programs With gcc
267 * Compiling Programs::
269 * Search Paths and the Run-Time Library (RTL)::
270 * Order of Compilation Issues::
275 * Output and Error Message Control::
276 * Warning Message Control::
277 * Debugging and Assertion Control::
278 * Validity Checking::
281 * Using gcc for Syntax Checking::
282 * Using gcc for Semantic Checking::
283 * Compiling Different Versions of Ada::
284 * Character Set Control::
285 * File Naming Control::
286 * Subprogram Inlining Control::
287 * Auxiliary Output Control::
288 * Debugging Control::
289 * Exception Handling Control::
290 * Units to Sources Mapping Files::
291 * Integrated Preprocessing::
296 Binding Ada Programs With gnatbind
299 * Switches for gnatbind::
300 * Command-Line Access::
301 * Search Paths for gnatbind::
302 * Examples of gnatbind Usage::
304 Switches for gnatbind
306 * Consistency-Checking Modes::
307 * Binder Error Message Control::
308 * Elaboration Control::
310 * Binding with Non-Ada Main Programs::
311 * Binding Programs with No Main Subprogram::
313 Linking Using gnatlink
316 * Switches for gnatlink::
318 The GNAT Make Program gnatmake
321 * Switches for gnatmake::
322 * Mode Switches for gnatmake::
323 * Notes on the Command Line::
324 * How gnatmake Works::
325 * Examples of gnatmake Usage::
327 Improving Performance
328 * Performance Considerations::
329 * Text_IO Suggestions::
330 * Reducing Size of Ada Executables with gnatelim::
331 * Reducing Size of Executables with unused subprogram/data elimination::
333 Performance Considerations
334 * Controlling Run-Time Checks::
335 * Use of Restrictions::
336 * Optimization Levels::
337 * Debugging Optimized Code::
338 * Inlining of Subprograms::
339 * Other Optimization Switches::
340 * Optimization and Strict Aliasing::
342 * Coverage Analysis::
345 Reducing Size of Ada Executables with gnatelim
348 * Processing Precompiled Libraries::
349 * Correcting the List of Eliminate Pragmas::
350 * Making Your Executables Smaller::
351 * Summary of the gnatelim Usage Cycle::
353 Reducing Size of Executables with unused subprogram/data elimination
354 * About unused subprogram/data elimination::
355 * Compilation options::
357 Renaming Files Using gnatchop
359 * Handling Files with Multiple Units::
360 * Operating gnatchop in Compilation Mode::
361 * Command Line for gnatchop::
362 * Switches for gnatchop::
363 * Examples of gnatchop Usage::
365 Configuration Pragmas
367 * Handling of Configuration Pragmas::
368 * The Configuration Pragmas Files::
370 Handling Arbitrary File Naming Conventions Using gnatname
372 * Arbitrary File Naming Conventions::
374 * Switches for gnatname::
375 * Examples of gnatname Usage::
377 The Cross-Referencing Tools gnatxref and gnatfind
379 * Switches for gnatxref::
380 * Switches for gnatfind::
381 * Project Files for gnatxref and gnatfind::
382 * Regular Expressions in gnatfind and gnatxref::
383 * Examples of gnatxref Usage::
384 * Examples of gnatfind Usage::
386 The GNAT Pretty-Printer gnatpp
388 * Switches for gnatpp::
391 The GNAT Metrics Tool gnatmetric
393 * Switches for gnatmetric::
395 File Name Krunching Using gnatkr
400 * Examples of gnatkr Usage::
402 Preprocessing Using gnatprep
403 * Preprocessing Symbols::
405 * Switches for gnatprep::
406 * Form of Definitions File::
407 * Form of Input Text for gnatprep::
409 The GNAT Library Browser gnatls
412 * Switches for gnatls::
413 * Examples of gnatls Usage::
415 Cleaning Up Using gnatclean
417 * Running gnatclean::
418 * Switches for gnatclean::
419 @c * Examples of gnatclean Usage::
425 * Introduction to Libraries in GNAT::
426 * General Ada Libraries::
427 * Stand-alone Ada Libraries::
428 * Rebuilding the GNAT Run-Time Library::
430 Using the GNU make Utility
432 * Using gnatmake in a Makefile::
433 * Automatically Creating a List of Directories::
434 * Generating the Command Line Switches::
435 * Overcoming Command Line Length Limits::
438 Memory Management Issues
440 * Some Useful Memory Pools::
441 * The GNAT Debug Pool Facility::
446 Stack Related Facilities
448 * Stack Overflow Checking::
449 * Static Stack Usage Analysis::
450 * Dynamic Stack Usage Analysis::
452 Some Useful Memory Pools
454 The GNAT Debug Pool Facility
460 * Switches for gnatmem::
461 * Example of gnatmem Usage::
464 Verifying Properties Using gnatcheck
466 Sample Bodies Using gnatstub
469 * Switches for gnatstub::
471 Other Utility Programs
473 * Using Other Utility Programs with GNAT::
474 * The External Symbol Naming Scheme of GNAT::
475 * Converting Ada Files to html with gnathtml::
478 Code Coverage and Profiling
480 * Code Coverage of Ada Programs using gcov::
481 * Profiling an Ada Program using gprof::
484 Running and Debugging Ada Programs
486 * The GNAT Debugger GDB::
488 * Introduction to GDB Commands::
489 * Using Ada Expressions::
490 * Calling User-Defined Subprograms::
491 * Using the Next Command in a Function::
494 * Debugging Generic Units::
495 * Remote Debugging using gdbserver::
496 * GNAT Abnormal Termination or Failure to Terminate::
497 * Naming Conventions for GNAT Source Files::
498 * Getting Internal Debugging Information::
506 Compatibility with HP Ada
508 * Ada Language Compatibility::
509 * Differences in the Definition of Package System::
510 * Language-Related Features::
511 * The Package STANDARD::
512 * The Package SYSTEM::
513 * Tasking and Task-Related Features::
514 * Pragmas and Pragma-Related Features::
515 * Library of Predefined Units::
517 * Main Program Definition::
518 * Implementation-Defined Attributes::
519 * Compiler and Run-Time Interfacing::
520 * Program Compilation and Library Management::
522 * Implementation Limits::
523 * Tools and Utilities::
525 Language-Related Features
527 * Integer Types and Representations::
528 * Floating-Point Types and Representations::
529 * Pragmas Float_Representation and Long_Float::
530 * Fixed-Point Types and Representations::
531 * Record and Array Component Alignment::
533 * Other Representation Clauses::
535 Tasking and Task-Related Features
537 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
538 * Assigning Task IDs::
539 * Task IDs and Delays::
540 * Task-Related Pragmas::
541 * Scheduling and Task Priority::
543 * External Interrupts::
545 Pragmas and Pragma-Related Features
547 * Restrictions on the Pragma INLINE::
548 * Restrictions on the Pragma INTERFACE::
549 * Restrictions on the Pragma SYSTEM_NAME::
551 Library of Predefined Units
553 * Changes to DECLIB::
557 * Shared Libraries and Options Files::
561 Platform-Specific Information for the Run-Time Libraries
563 * Summary of Run-Time Configurations::
564 * Specifying a Run-Time Library::
565 * Choosing the Scheduling Policy::
566 * Solaris-Specific Considerations::
567 * Linux-Specific Considerations::
568 * AIX-Specific Considerations::
569 * Irix-Specific Considerations::
570 * RTX-Specific Considerations::
571 * HP-UX-Specific Considerations::
573 Example of Binder Output File
575 Elaboration Order Handling in GNAT
578 * Checking the Elaboration Order::
579 * Controlling the Elaboration Order::
580 * Controlling Elaboration in GNAT - Internal Calls::
581 * Controlling Elaboration in GNAT - External Calls::
582 * Default Behavior in GNAT - Ensuring Safety::
583 * Treatment of Pragma Elaborate::
584 * Elaboration Issues for Library Tasks::
585 * Mixing Elaboration Models::
586 * What to Do If the Default Elaboration Behavior Fails::
587 * Elaboration for Access-to-Subprogram Values::
588 * Summary of Procedures for Elaboration Control::
589 * Other Elaboration Order Considerations::
591 Conditional Compilation
592 * Use of Boolean Constants::
593 * Debugging - A Special Case::
594 * Conditionalizing Declarations::
595 * Use of Alternative Implementations::
600 * Basic Assembler Syntax::
601 * A Simple Example of Inline Assembler::
602 * Output Variables in Inline Assembler::
603 * Input Variables in Inline Assembler::
604 * Inlining Inline Assembler Code::
605 * Other Asm Functionality::
607 Compatibility and Porting Guide
609 * Compatibility with Ada 83::
610 * Compatibility between Ada 95 and Ada 2005::
611 * Implementation-dependent characteristics::
613 @c This brief section is only in the non-VMS version
614 @c The complete chapter on HP Ada issues is in the VMS version
615 * Compatibility with HP Ada 83::
617 * Compatibility with Other Ada Systems::
618 * Representation Clauses::
620 * Transitioning to 64-Bit GNAT for OpenVMS::
624 Microsoft Windows Topics
626 * Using GNAT on Windows::
627 * CONSOLE and WINDOWS subsystems::
629 * Mixed-Language Programming on Windows::
630 * Windows Calling Conventions::
631 * Introduction to Dynamic Link Libraries (DLLs)::
632 * Using DLLs with GNAT::
633 * Building DLLs with GNAT::
634 * GNAT and Windows Resources::
636 * Setting Stack Size from gnatlink::
637 * Setting Heap Size from gnatlink::
644 @node About This Guide
645 @unnumbered About This Guide
649 This guide describes the use of @value{EDITION},
650 a compiler and software development toolset for the full Ada
651 programming language, implemented on OpenVMS for HP's Alpha and
652 Integrity server (I64) platforms.
655 This guide describes the use of @value{EDITION},
656 a compiler and software development
657 toolset for the full Ada programming language.
659 It documents the features of the compiler and tools, and explains
660 how to use them to build Ada applications.
662 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
663 Ada 83 compatibility mode.
664 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
665 but you can override with a compiler switch
666 (@pxref{Compiling Different Versions of Ada})
667 to explicitly specify the language version.
668 Throughout this manual, references to ``Ada'' without a year suffix
669 apply to both the Ada 95 and Ada 2005 versions of the language.
673 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
674 ``GNAT'' in the remainder of this document.
681 * What This Guide Contains::
682 * What You Should Know before Reading This Guide::
683 * Related Information::
687 @node What This Guide Contains
688 @unnumberedsec What This Guide Contains
691 This guide contains the following chapters:
695 @ref{Getting Started with GNAT}, describes how to get started compiling
696 and running Ada programs with the GNAT Ada programming environment.
698 @ref{The GNAT Compilation Model}, describes the compilation model used
702 @ref{Compiling Using gcc}, describes how to compile
703 Ada programs with @command{gcc}, the Ada compiler.
706 @ref{Binding Using gnatbind}, describes how to
707 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
711 @ref{Linking Using gnatlink},
712 describes @command{gnatlink}, a
713 program that provides for linking using the GNAT run-time library to
714 construct a program. @command{gnatlink} can also incorporate foreign language
715 object units into the executable.
718 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
719 utility that automatically determines the set of sources
720 needed by an Ada compilation unit, and executes the necessary compilations
724 @ref{Improving Performance}, shows various techniques for making your
725 Ada program run faster or take less space.
726 It discusses the effect of the compiler's optimization switch and
727 also describes the @command{gnatelim} tool and unused subprogram/data
731 @ref{Renaming Files Using gnatchop}, describes
732 @code{gnatchop}, a utility that allows you to preprocess a file that
733 contains Ada source code, and split it into one or more new files, one
734 for each compilation unit.
737 @ref{Configuration Pragmas}, describes the configuration pragmas
741 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
742 shows how to override the default GNAT file naming conventions,
743 either for an individual unit or globally.
746 @ref{GNAT Project Manager}, describes how to use project files
747 to organize large projects.
750 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
751 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
752 way to navigate through sources.
755 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
756 version of an Ada source file with control over casing, indentation,
757 comment placement, and other elements of program presentation style.
760 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
761 metrics for an Ada source file, such as the number of types and subprograms,
762 and assorted complexity measures.
765 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
766 file name krunching utility, used to handle shortened
767 file names on operating systems with a limit on the length of names.
770 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
771 preprocessor utility that allows a single source file to be used to
772 generate multiple or parameterized source files by means of macro
776 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
777 utility that displays information about compiled units, including dependences
778 on the corresponding sources files, and consistency of compilations.
781 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
782 to delete files that are produced by the compiler, binder and linker.
786 @ref{GNAT and Libraries}, describes the process of creating and using
787 Libraries with GNAT. It also describes how to recompile the GNAT run-time
791 @ref{Using the GNU make Utility}, describes some techniques for using
792 the GNAT toolset in Makefiles.
796 @ref{Memory Management Issues}, describes some useful predefined storage pools
797 and in particular the GNAT Debug Pool facility, which helps detect incorrect
800 It also describes @command{gnatmem}, a utility that monitors dynamic
801 allocation and deallocation and helps detect ``memory leaks''.
805 @ref{Stack Related Facilities}, describes some useful tools associated with
806 stack checking and analysis.
809 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
810 a utility that checks Ada code against a set of rules.
813 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
814 a utility that generates empty but compilable bodies for library units.
817 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
818 generate automatically Ada bindings from C and C++ headers.
821 @ref{Other Utility Programs}, discusses several other GNAT utilities,
822 including @code{gnathtml}.
826 @ref{Code Coverage and Profiling}, describes how to perform a structural
827 coverage and profile the execution of Ada programs.
831 @ref{Running and Debugging Ada Programs}, describes how to run and debug
836 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
837 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
838 developed by Digital Equipment Corporation and currently supported by HP.}
839 for OpenVMS Alpha. This product was formerly known as DEC Ada,
842 historical compatibility reasons, the relevant libraries still use the
847 @ref{Platform-Specific Information for the Run-Time Libraries},
848 describes the various run-time
849 libraries supported by GNAT on various platforms and explains how to
850 choose a particular library.
853 @ref{Example of Binder Output File}, shows the source code for the binder
854 output file for a sample program.
857 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
858 you deal with elaboration order issues.
861 @ref{Conditional Compilation}, describes how to model conditional compilation,
862 both with Ada in general and with GNAT facilities in particular.
865 @ref{Inline Assembler}, shows how to use the inline assembly facility
869 @ref{Compatibility and Porting Guide}, contains sections on compatibility
870 of GNAT with other Ada development environments (including Ada 83 systems),
871 to assist in porting code from those environments.
875 @ref{Microsoft Windows Topics}, presents information relevant to the
876 Microsoft Windows platform.
880 @c *************************************************
881 @node What You Should Know before Reading This Guide
882 @c *************************************************
883 @unnumberedsec What You Should Know before Reading This Guide
885 @cindex Ada 95 Language Reference Manual
886 @cindex Ada 2005 Language Reference Manual
888 This guide assumes a basic familiarity with the Ada 95 language, as
889 described in the International Standard ANSI/ISO/IEC-8652:1995, January
891 It does not require knowledge of the new features introduced by Ada 2005,
892 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
894 Both reference manuals are included in the GNAT documentation
897 @node Related Information
898 @unnumberedsec Related Information
901 For further information about related tools, refer to the following
906 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
907 Reference Manual}, which contains all reference material for the GNAT
908 implementation of Ada.
912 @cite{Using the GNAT Programming Studio}, which describes the GPS
913 Integrated Development Environment.
916 @cite{GNAT Programming Studio Tutorial}, which introduces the
917 main GPS features through examples.
921 @cite{Ada 95 Reference Manual}, which contains reference
922 material for the Ada 95 programming language.
925 @cite{Ada 2005 Reference Manual}, which contains reference
926 material for the Ada 2005 programming language.
929 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
931 in the GNU:[DOCS] directory,
933 for all details on the use of the GNU source-level debugger.
936 @xref{Top,, The extensible self-documenting text editor, emacs,
939 located in the GNU:[DOCS] directory if the EMACS kit is installed,
941 for full information on the extensible editor and programming
948 @unnumberedsec Conventions
950 @cindex Typographical conventions
953 Following are examples of the typographical and graphic conventions used
958 @code{Functions}, @command{utility program names}, @code{standard names},
962 @option{Option flags}
965 @file{File names}, @samp{button names}, and @samp{field names}.
968 @code{Variables}, @env{environment variables}, and @var{metasyntactic
975 @r{[}optional information or parameters@r{]}
978 Examples are described by text
980 and then shown this way.
985 Commands that are entered by the user are preceded in this manual by the
986 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
987 uses this sequence as a prompt, then the commands will appear exactly as
988 you see them in the manual. If your system uses some other prompt, then
989 the command will appear with the @code{$} replaced by whatever prompt
990 character you are using.
993 Full file names are shown with the ``@code{/}'' character
994 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
995 If you are using GNAT on a Windows platform, please note that
996 the ``@code{\}'' character should be used instead.
999 @c ****************************
1000 @node Getting Started with GNAT
1001 @chapter Getting Started with GNAT
1004 This chapter describes some simple ways of using GNAT to build
1005 executable Ada programs.
1007 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1008 show how to use the command line environment.
1009 @ref{Introduction to GPS}, provides a brief
1010 introduction to the GNAT Programming Studio, a visually-oriented
1011 Integrated Development Environment for GNAT.
1012 GPS offers a graphical ``look and feel'', support for development in
1013 other programming languages, comprehensive browsing features, and
1014 many other capabilities.
1015 For information on GPS please refer to
1016 @cite{Using the GNAT Programming Studio}.
1021 * Running a Simple Ada Program::
1022 * Running a Program with Multiple Units::
1023 * Using the gnatmake Utility::
1025 * Editing with Emacs::
1028 * Introduction to GPS::
1033 @section Running GNAT
1036 Three steps are needed to create an executable file from an Ada source
1041 The source file(s) must be compiled.
1043 The file(s) must be bound using the GNAT binder.
1045 All appropriate object files must be linked to produce an executable.
1049 All three steps are most commonly handled by using the @command{gnatmake}
1050 utility program that, given the name of the main program, automatically
1051 performs the necessary compilation, binding and linking steps.
1053 @node Running a Simple Ada Program
1054 @section Running a Simple Ada Program
1057 Any text editor may be used to prepare an Ada program.
1059 used, the optional Ada mode may be helpful in laying out the program.)
1061 program text is a normal text file. We will assume in our initial
1062 example that you have used your editor to prepare the following
1063 standard format text file:
1065 @smallexample @c ada
1067 with Ada.Text_IO; use Ada.Text_IO;
1070 Put_Line ("Hello WORLD!");
1076 This file should be named @file{hello.adb}.
1077 With the normal default file naming conventions, GNAT requires
1079 contain a single compilation unit whose file name is the
1081 with periods replaced by hyphens; the
1082 extension is @file{ads} for a
1083 spec and @file{adb} for a body.
1084 You can override this default file naming convention by use of the
1085 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1086 Alternatively, if you want to rename your files according to this default
1087 convention, which is probably more convenient if you will be using GNAT
1088 for all your compilations, then the @code{gnatchop} utility
1089 can be used to generate correctly-named source files
1090 (@pxref{Renaming Files Using gnatchop}).
1092 You can compile the program using the following command (@code{$} is used
1093 as the command prompt in the examples in this document):
1100 @command{gcc} is the command used to run the compiler. This compiler is
1101 capable of compiling programs in several languages, including Ada and
1102 C. It assumes that you have given it an Ada program if the file extension is
1103 either @file{.ads} or @file{.adb}, and it will then call
1104 the GNAT compiler to compile the specified file.
1107 The @option{-c} switch is required. It tells @command{gcc} to only do a
1108 compilation. (For C programs, @command{gcc} can also do linking, but this
1109 capability is not used directly for Ada programs, so the @option{-c}
1110 switch must always be present.)
1113 This compile command generates a file
1114 @file{hello.o}, which is the object
1115 file corresponding to your Ada program. It also generates
1116 an ``Ada Library Information'' file @file{hello.ali},
1117 which contains additional information used to check
1118 that an Ada program is consistent.
1119 To build an executable file,
1120 use @code{gnatbind} to bind the program
1121 and @command{gnatlink} to link it. The
1122 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1123 @file{ALI} file, but the default extension of @file{.ali} can
1124 be omitted. This means that in the most common case, the argument
1125 is simply the name of the main program:
1133 A simpler method of carrying out these steps is to use
1135 a master program that invokes all the required
1136 compilation, binding and linking tools in the correct order. In particular,
1137 @command{gnatmake} automatically recompiles any sources that have been
1138 modified since they were last compiled, or sources that depend
1139 on such modified sources, so that ``version skew'' is avoided.
1140 @cindex Version skew (avoided by @command{gnatmake})
1143 $ gnatmake hello.adb
1147 The result is an executable program called @file{hello}, which can be
1155 assuming that the current directory is on the search path
1156 for executable programs.
1159 and, if all has gone well, you will see
1166 appear in response to this command.
1168 @c ****************************************
1169 @node Running a Program with Multiple Units
1170 @section Running a Program with Multiple Units
1173 Consider a slightly more complicated example that has three files: a
1174 main program, and the spec and body of a package:
1176 @smallexample @c ada
1179 package Greetings is
1184 with Ada.Text_IO; use Ada.Text_IO;
1185 package body Greetings is
1188 Put_Line ("Hello WORLD!");
1191 procedure Goodbye is
1193 Put_Line ("Goodbye WORLD!");
1210 Following the one-unit-per-file rule, place this program in the
1211 following three separate files:
1215 spec of package @code{Greetings}
1218 body of package @code{Greetings}
1221 body of main program
1225 To build an executable version of
1226 this program, we could use four separate steps to compile, bind, and link
1227 the program, as follows:
1231 $ gcc -c greetings.adb
1237 Note that there is no required order of compilation when using GNAT.
1238 In particular it is perfectly fine to compile the main program first.
1239 Also, it is not necessary to compile package specs in the case where
1240 there is an accompanying body; you only need to compile the body. If you want
1241 to submit these files to the compiler for semantic checking and not code
1242 generation, then use the
1243 @option{-gnatc} switch:
1246 $ gcc -c greetings.ads -gnatc
1250 Although the compilation can be done in separate steps as in the
1251 above example, in practice it is almost always more convenient
1252 to use the @command{gnatmake} tool. All you need to know in this case
1253 is the name of the main program's source file. The effect of the above four
1254 commands can be achieved with a single one:
1257 $ gnatmake gmain.adb
1261 In the next section we discuss the advantages of using @command{gnatmake} in
1264 @c *****************************
1265 @node Using the gnatmake Utility
1266 @section Using the @command{gnatmake} Utility
1269 If you work on a program by compiling single components at a time using
1270 @command{gcc}, you typically keep track of the units you modify. In order to
1271 build a consistent system, you compile not only these units, but also any
1272 units that depend on the units you have modified.
1273 For example, in the preceding case,
1274 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1275 you edit @file{greetings.ads}, you must recompile both
1276 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1277 units that depend on @file{greetings.ads}.
1279 @code{gnatbind} will warn you if you forget one of these compilation
1280 steps, so that it is impossible to generate an inconsistent program as a
1281 result of forgetting to do a compilation. Nevertheless it is tedious and
1282 error-prone to keep track of dependencies among units.
1283 One approach to handle the dependency-bookkeeping is to use a
1284 makefile. However, makefiles present maintenance problems of their own:
1285 if the dependencies change as you change the program, you must make
1286 sure that the makefile is kept up-to-date manually, which is also an
1287 error-prone process.
1289 The @command{gnatmake} utility takes care of these details automatically.
1290 Invoke it using either one of the following forms:
1293 $ gnatmake gmain.adb
1294 $ gnatmake ^gmain^GMAIN^
1298 The argument is the name of the file containing the main program;
1299 you may omit the extension. @command{gnatmake}
1300 examines the environment, automatically recompiles any files that need
1301 recompiling, and binds and links the resulting set of object files,
1302 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1303 In a large program, it
1304 can be extremely helpful to use @command{gnatmake}, because working out by hand
1305 what needs to be recompiled can be difficult.
1307 Note that @command{gnatmake}
1308 takes into account all the Ada rules that
1309 establish dependencies among units. These include dependencies that result
1310 from inlining subprogram bodies, and from
1311 generic instantiation. Unlike some other
1312 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1313 found by the compiler on a previous compilation, which may possibly
1314 be wrong when sources change. @command{gnatmake} determines the exact set of
1315 dependencies from scratch each time it is run.
1318 @node Editing with Emacs
1319 @section Editing with Emacs
1323 Emacs is an extensible self-documenting text editor that is available in a
1324 separate VMSINSTAL kit.
1326 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1327 click on the Emacs Help menu and run the Emacs Tutorial.
1328 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1329 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1331 Documentation on Emacs and other tools is available in Emacs under the
1332 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1333 use the middle mouse button to select a topic (e.g.@: Emacs).
1335 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1336 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1337 get to the Emacs manual.
1338 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1341 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1342 which is sufficiently extensible to provide for a complete programming
1343 environment and shell for the sophisticated user.
1347 @node Introduction to GPS
1348 @section Introduction to GPS
1349 @cindex GPS (GNAT Programming Studio)
1350 @cindex GNAT Programming Studio (GPS)
1352 Although the command line interface (@command{gnatmake}, etc.) alone
1353 is sufficient, a graphical Interactive Development
1354 Environment can make it easier for you to compose, navigate, and debug
1355 programs. This section describes the main features of GPS
1356 (``GNAT Programming Studio''), the GNAT graphical IDE.
1357 You will see how to use GPS to build and debug an executable, and
1358 you will also learn some of the basics of the GNAT ``project'' facility.
1360 GPS enables you to do much more than is presented here;
1361 e.g., you can produce a call graph, interface to a third-party
1362 Version Control System, and inspect the generated assembly language
1364 Indeed, GPS also supports languages other than Ada.
1365 Such additional information, and an explanation of all of the GPS menu
1366 items. may be found in the on-line help, which includes
1367 a user's guide and a tutorial (these are also accessible from the GNAT
1371 * Building a New Program with GPS::
1372 * Simple Debugging with GPS::
1375 @node Building a New Program with GPS
1376 @subsection Building a New Program with GPS
1378 GPS invokes the GNAT compilation tools using information
1379 contained in a @emph{project} (also known as a @emph{project file}):
1380 a collection of properties such
1381 as source directories, identities of main subprograms, tool switches, etc.,
1382 and their associated values.
1383 See @ref{GNAT Project Manager} for details.
1384 In order to run GPS, you will need to either create a new project
1385 or else open an existing one.
1387 This section will explain how you can use GPS to create a project,
1388 to associate Ada source files with a project, and to build and run
1392 @item @emph{Creating a project}
1394 Invoke GPS, either from the command line or the platform's IDE.
1395 After it starts, GPS will display a ``Welcome'' screen with three
1400 @code{Start with default project in directory}
1403 @code{Create new project with wizard}
1406 @code{Open existing project}
1410 Select @code{Create new project with wizard} and press @code{OK}.
1411 A new window will appear. In the text box labeled with
1412 @code{Enter the name of the project to create}, type @file{sample}
1413 as the project name.
1414 In the next box, browse to choose the directory in which you
1415 would like to create the project file.
1416 After selecting an appropriate directory, press @code{Forward}.
1418 A window will appear with the title
1419 @code{Version Control System Configuration}.
1420 Simply press @code{Forward}.
1422 A window will appear with the title
1423 @code{Please select the source directories for this project}.
1424 The directory that you specified for the project file will be selected
1425 by default as the one to use for sources; simply press @code{Forward}.
1427 A window will appear with the title
1428 @code{Please select the build directory for this project}.
1429 The directory that you specified for the project file will be selected
1430 by default for object files and executables;
1431 simply press @code{Forward}.
1433 A window will appear with the title
1434 @code{Please select the main units for this project}.
1435 You will supply this information later, after creating the source file.
1436 Simply press @code{Forward} for now.
1438 A window will appear with the title
1439 @code{Please select the switches to build the project}.
1440 Press @code{Apply}. This will create a project file named
1441 @file{sample.prj} in the directory that you had specified.
1443 @item @emph{Creating and saving the source file}
1445 After you create the new project, a GPS window will appear, which is
1446 partitioned into two main sections:
1450 A @emph{Workspace area}, initially greyed out, which you will use for
1451 creating and editing source files
1454 Directly below, a @emph{Messages area}, which initially displays a
1455 ``Welcome'' message.
1456 (If the Messages area is not visible, drag its border upward to expand it.)
1460 Select @code{File} on the menu bar, and then the @code{New} command.
1461 The Workspace area will become white, and you can now
1462 enter the source program explicitly.
1463 Type the following text
1465 @smallexample @c ada
1467 with Ada.Text_IO; use Ada.Text_IO;
1470 Put_Line("Hello from GPS!");
1476 Select @code{File}, then @code{Save As}, and enter the source file name
1478 The file will be saved in the same directory you specified as the
1479 location of the default project file.
1481 @item @emph{Updating the project file}
1483 You need to add the new source file to the project.
1485 the @code{Project} menu and then @code{Edit project properties}.
1486 Click the @code{Main files} tab on the left, and then the
1488 Choose @file{hello.adb} from the list, and press @code{Open}.
1489 The project settings window will reflect this action.
1492 @item @emph{Building and running the program}
1494 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1495 and select @file{hello.adb}.
1496 The Messages window will display the resulting invocations of @command{gcc},
1497 @command{gnatbind}, and @command{gnatlink}
1498 (reflecting the default switch settings from the
1499 project file that you created) and then a ``successful compilation/build''
1502 To run the program, choose the @code{Build} menu, then @code{Run}, and
1503 select @command{hello}.
1504 An @emph{Arguments Selection} window will appear.
1505 There are no command line arguments, so just click @code{OK}.
1507 The Messages window will now display the program's output (the string
1508 @code{Hello from GPS}), and at the bottom of the GPS window a status
1509 update is displayed (@code{Run: hello}).
1510 Close the GPS window (or select @code{File}, then @code{Exit}) to
1511 terminate this GPS session.
1514 @node Simple Debugging with GPS
1515 @subsection Simple Debugging with GPS
1517 This section illustrates basic debugging techniques (setting breakpoints,
1518 examining/modifying variables, single stepping).
1521 @item @emph{Opening a project}
1523 Start GPS and select @code{Open existing project}; browse to
1524 specify the project file @file{sample.prj} that you had created in the
1527 @item @emph{Creating a source file}
1529 Select @code{File}, then @code{New}, and type in the following program:
1531 @smallexample @c ada
1533 with Ada.Text_IO; use Ada.Text_IO;
1534 procedure Example is
1535 Line : String (1..80);
1538 Put_Line("Type a line of text at each prompt; an empty line to exit");
1542 Put_Line (Line (1..N) );
1550 Select @code{File}, then @code{Save as}, and enter the file name
1553 @item @emph{Updating the project file}
1555 Add @code{Example} as a new main unit for the project:
1558 Select @code{Project}, then @code{Edit Project Properties}.
1561 Select the @code{Main files} tab, click @code{Add}, then
1562 select the file @file{example.adb} from the list, and
1564 You will see the file name appear in the list of main units
1570 @item @emph{Building/running the executable}
1572 To build the executable
1573 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1575 Run the program to see its effect (in the Messages area).
1576 Each line that you enter is displayed; an empty line will
1577 cause the loop to exit and the program to terminate.
1579 @item @emph{Debugging the program}
1581 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1582 which are required for debugging, are on by default when you create
1584 Thus unless you intentionally remove these settings, you will be able
1585 to debug any program that you develop using GPS.
1588 @item @emph{Initializing}
1590 Select @code{Debug}, then @code{Initialize}, then @file{example}
1592 @item @emph{Setting a breakpoint}
1594 After performing the initialization step, you will observe a small
1595 icon to the right of each line number.
1596 This serves as a toggle for breakpoints; clicking the icon will
1597 set a breakpoint at the corresponding line (the icon will change to
1598 a red circle with an ``x''), and clicking it again
1599 will remove the breakpoint / reset the icon.
1601 For purposes of this example, set a breakpoint at line 10 (the
1602 statement @code{Put_Line@ (Line@ (1..N));}
1604 @item @emph{Starting program execution}
1606 Select @code{Debug}, then @code{Run}. When the
1607 @code{Program Arguments} window appears, click @code{OK}.
1608 A console window will appear; enter some line of text,
1609 e.g.@: @code{abcde}, at the prompt.
1610 The program will pause execution when it gets to the
1611 breakpoint, and the corresponding line is highlighted.
1613 @item @emph{Examining a variable}
1615 Move the mouse over one of the occurrences of the variable @code{N}.
1616 You will see the value (5) displayed, in ``tool tip'' fashion.
1617 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1618 You will see information about @code{N} appear in the @code{Debugger Data}
1619 pane, showing the value as 5.
1621 @item @emph{Assigning a new value to a variable}
1623 Right click on the @code{N} in the @code{Debugger Data} pane, and
1624 select @code{Set value of N}.
1625 When the input window appears, enter the value @code{4} and click
1627 This value does not automatically appear in the @code{Debugger Data}
1628 pane; to see it, right click again on the @code{N} in the
1629 @code{Debugger Data} pane and select @code{Update value}.
1630 The new value, 4, will appear in red.
1632 @item @emph{Single stepping}
1634 Select @code{Debug}, then @code{Next}.
1635 This will cause the next statement to be executed, in this case the
1636 call of @code{Put_Line} with the string slice.
1637 Notice in the console window that the displayed string is simply
1638 @code{abcd} and not @code{abcde} which you had entered.
1639 This is because the upper bound of the slice is now 4 rather than 5.
1641 @item @emph{Removing a breakpoint}
1643 Toggle the breakpoint icon at line 10.
1645 @item @emph{Resuming execution from a breakpoint}
1647 Select @code{Debug}, then @code{Continue}.
1648 The program will reach the next iteration of the loop, and
1649 wait for input after displaying the prompt.
1650 This time, just hit the @kbd{Enter} key.
1651 The value of @code{N} will be 0, and the program will terminate.
1652 The console window will disappear.
1657 @node The GNAT Compilation Model
1658 @chapter The GNAT Compilation Model
1659 @cindex GNAT compilation model
1660 @cindex Compilation model
1663 * Source Representation::
1664 * Foreign Language Representation::
1665 * File Naming Rules::
1666 * Using Other File Names::
1667 * Alternative File Naming Schemes::
1668 * Generating Object Files::
1669 * Source Dependencies::
1670 * The Ada Library Information Files::
1671 * Binding an Ada Program::
1672 * Mixed Language Programming::
1674 * Building Mixed Ada & C++ Programs::
1675 * Comparison between GNAT and C/C++ Compilation Models::
1677 * Comparison between GNAT and Conventional Ada Library Models::
1679 * Placement of temporary files::
1684 This chapter describes the compilation model used by GNAT. Although
1685 similar to that used by other languages, such as C and C++, this model
1686 is substantially different from the traditional Ada compilation models,
1687 which are based on a library. The model is initially described without
1688 reference to the library-based model. If you have not previously used an
1689 Ada compiler, you need only read the first part of this chapter. The
1690 last section describes and discusses the differences between the GNAT
1691 model and the traditional Ada compiler models. If you have used other
1692 Ada compilers, this section will help you to understand those
1693 differences, and the advantages of the GNAT model.
1695 @node Source Representation
1696 @section Source Representation
1700 Ada source programs are represented in standard text files, using
1701 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1702 7-bit ASCII set, plus additional characters used for
1703 representing foreign languages (@pxref{Foreign Language Representation}
1704 for support of non-USA character sets). The format effector characters
1705 are represented using their standard ASCII encodings, as follows:
1710 Vertical tab, @code{16#0B#}
1714 Horizontal tab, @code{16#09#}
1718 Carriage return, @code{16#0D#}
1722 Line feed, @code{16#0A#}
1726 Form feed, @code{16#0C#}
1730 Source files are in standard text file format. In addition, GNAT will
1731 recognize a wide variety of stream formats, in which the end of
1732 physical lines is marked by any of the following sequences:
1733 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1734 in accommodating files that are imported from other operating systems.
1736 @cindex End of source file
1737 @cindex Source file, end
1739 The end of a source file is normally represented by the physical end of
1740 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1741 recognized as signalling the end of the source file. Again, this is
1742 provided for compatibility with other operating systems where this
1743 code is used to represent the end of file.
1745 Each file contains a single Ada compilation unit, including any pragmas
1746 associated with the unit. For example, this means you must place a
1747 package declaration (a package @dfn{spec}) and the corresponding body in
1748 separate files. An Ada @dfn{compilation} (which is a sequence of
1749 compilation units) is represented using a sequence of files. Similarly,
1750 you will place each subunit or child unit in a separate file.
1752 @node Foreign Language Representation
1753 @section Foreign Language Representation
1756 GNAT supports the standard character sets defined in Ada as well as
1757 several other non-standard character sets for use in localized versions
1758 of the compiler (@pxref{Character Set Control}).
1761 * Other 8-Bit Codes::
1762 * Wide Character Encodings::
1770 The basic character set is Latin-1. This character set is defined by ISO
1771 standard 8859, part 1. The lower half (character codes @code{16#00#}
1772 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1773 half is used to represent additional characters. These include extended letters
1774 used by European languages, such as French accents, the vowels with umlauts
1775 used in German, and the extra letter A-ring used in Swedish.
1777 @findex Ada.Characters.Latin_1
1778 For a complete list of Latin-1 codes and their encodings, see the source
1779 file of library unit @code{Ada.Characters.Latin_1} in file
1780 @file{a-chlat1.ads}.
1781 You may use any of these extended characters freely in character or
1782 string literals. In addition, the extended characters that represent
1783 letters can be used in identifiers.
1785 @node Other 8-Bit Codes
1786 @subsection Other 8-Bit Codes
1789 GNAT also supports several other 8-bit coding schemes:
1792 @item ISO 8859-2 (Latin-2)
1795 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1798 @item ISO 8859-3 (Latin-3)
1801 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1804 @item ISO 8859-4 (Latin-4)
1807 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1810 @item ISO 8859-5 (Cyrillic)
1813 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1814 lowercase equivalence.
1816 @item ISO 8859-15 (Latin-9)
1819 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1820 lowercase equivalence
1822 @item IBM PC (code page 437)
1823 @cindex code page 437
1824 This code page is the normal default for PCs in the U.S. It corresponds
1825 to the original IBM PC character set. This set has some, but not all, of
1826 the extended Latin-1 letters, but these letters do not have the same
1827 encoding as Latin-1. In this mode, these letters are allowed in
1828 identifiers with uppercase and lowercase equivalence.
1830 @item IBM PC (code page 850)
1831 @cindex code page 850
1832 This code page is a modification of 437 extended to include all the
1833 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1834 mode, all these letters are allowed in identifiers with uppercase and
1835 lowercase equivalence.
1837 @item Full Upper 8-bit
1838 Any character in the range 80-FF allowed in identifiers, and all are
1839 considered distinct. In other words, there are no uppercase and lowercase
1840 equivalences in this range. This is useful in conjunction with
1841 certain encoding schemes used for some foreign character sets (e.g.,
1842 the typical method of representing Chinese characters on the PC).
1845 No upper-half characters in the range 80-FF are allowed in identifiers.
1846 This gives Ada 83 compatibility for identifier names.
1850 For precise data on the encodings permitted, and the uppercase and lowercase
1851 equivalences that are recognized, see the file @file{csets.adb} in
1852 the GNAT compiler sources. You will need to obtain a full source release
1853 of GNAT to obtain this file.
1855 @node Wide Character Encodings
1856 @subsection Wide Character Encodings
1859 GNAT allows wide character codes to appear in character and string
1860 literals, and also optionally in identifiers, by means of the following
1861 possible encoding schemes:
1866 In this encoding, a wide character is represented by the following five
1874 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1875 characters (using uppercase letters) of the wide character code. For
1876 example, ESC A345 is used to represent the wide character with code
1878 This scheme is compatible with use of the full Wide_Character set.
1880 @item Upper-Half Coding
1881 @cindex Upper-Half Coding
1882 The wide character with encoding @code{16#abcd#} where the upper bit is on
1883 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1884 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1885 character, but is not required to be in the upper half. This method can
1886 be also used for shift-JIS or EUC, where the internal coding matches the
1889 @item Shift JIS Coding
1890 @cindex Shift JIS Coding
1891 A wide character is represented by a two-character sequence,
1893 @code{16#cd#}, with the restrictions described for upper-half encoding as
1894 described above. The internal character code is the corresponding JIS
1895 character according to the standard algorithm for Shift-JIS
1896 conversion. Only characters defined in the JIS code set table can be
1897 used with this encoding method.
1901 A wide character is represented by a two-character sequence
1903 @code{16#cd#}, with both characters being in the upper half. The internal
1904 character code is the corresponding JIS character according to the EUC
1905 encoding algorithm. Only characters defined in the JIS code set table
1906 can be used with this encoding method.
1909 A wide character is represented using
1910 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1911 10646-1/Am.2. Depending on the character value, the representation
1912 is a one, two, or three byte sequence:
1917 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1918 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1919 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1924 where the @var{xxx} bits correspond to the left-padded bits of the
1925 16-bit character value. Note that all lower half ASCII characters
1926 are represented as ASCII bytes and all upper half characters and
1927 other wide characters are represented as sequences of upper-half
1928 (The full UTF-8 scheme allows for encoding 31-bit characters as
1929 6-byte sequences, but in this implementation, all UTF-8 sequences
1930 of four or more bytes length will be treated as illegal).
1931 @item Brackets Coding
1932 In this encoding, a wide character is represented by the following eight
1940 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1941 characters (using uppercase letters) of the wide character code. For
1942 example, [``A345''] is used to represent the wide character with code
1943 @code{16#A345#}. It is also possible (though not required) to use the
1944 Brackets coding for upper half characters. For example, the code
1945 @code{16#A3#} can be represented as @code{[``A3'']}.
1947 This scheme is compatible with use of the full Wide_Character set,
1948 and is also the method used for wide character encoding in the standard
1949 ACVC (Ada Compiler Validation Capability) test suite distributions.
1954 Note: Some of these coding schemes do not permit the full use of the
1955 Ada character set. For example, neither Shift JIS, nor EUC allow the
1956 use of the upper half of the Latin-1 set.
1958 @node File Naming Rules
1959 @section File Naming Rules
1962 The default file name is determined by the name of the unit that the
1963 file contains. The name is formed by taking the full expanded name of
1964 the unit and replacing the separating dots with hyphens and using
1965 ^lowercase^uppercase^ for all letters.
1967 An exception arises if the file name generated by the above rules starts
1968 with one of the characters
1970 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1973 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1975 and the second character is a
1976 minus. In this case, the character ^tilde^dollar sign^ is used in place
1977 of the minus. The reason for this special rule is to avoid clashes with
1978 the standard names for child units of the packages System, Ada,
1979 Interfaces, and GNAT, which use the prefixes
1981 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1984 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1988 The file extension is @file{.ads} for a spec and
1989 @file{.adb} for a body. The following list shows some
1990 examples of these rules.
1997 @item arith_functions.ads
1998 Arith_Functions (package spec)
1999 @item arith_functions.adb
2000 Arith_Functions (package body)
2002 Func.Spec (child package spec)
2004 Func.Spec (child package body)
2006 Sub (subunit of Main)
2007 @item ^a~bad.adb^A$BAD.ADB^
2008 A.Bad (child package body)
2012 Following these rules can result in excessively long
2013 file names if corresponding
2014 unit names are long (for example, if child units or subunits are
2015 heavily nested). An option is available to shorten such long file names
2016 (called file name ``krunching''). This may be particularly useful when
2017 programs being developed with GNAT are to be used on operating systems
2018 with limited file name lengths. @xref{Using gnatkr}.
2020 Of course, no file shortening algorithm can guarantee uniqueness over
2021 all possible unit names; if file name krunching is used, it is your
2022 responsibility to ensure no name clashes occur. Alternatively you
2023 can specify the exact file names that you want used, as described
2024 in the next section. Finally, if your Ada programs are migrating from a
2025 compiler with a different naming convention, you can use the gnatchop
2026 utility to produce source files that follow the GNAT naming conventions.
2027 (For details @pxref{Renaming Files Using gnatchop}.)
2029 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2030 systems, case is not significant. So for example on @code{Windows XP}
2031 if the canonical name is @code{main-sub.adb}, you can use the file name
2032 @code{Main-Sub.adb} instead. However, case is significant for other
2033 operating systems, so for example, if you want to use other than
2034 canonically cased file names on a Unix system, you need to follow
2035 the procedures described in the next section.
2037 @node Using Other File Names
2038 @section Using Other File Names
2042 In the previous section, we have described the default rules used by
2043 GNAT to determine the file name in which a given unit resides. It is
2044 often convenient to follow these default rules, and if you follow them,
2045 the compiler knows without being explicitly told where to find all
2048 However, in some cases, particularly when a program is imported from
2049 another Ada compiler environment, it may be more convenient for the
2050 programmer to specify which file names contain which units. GNAT allows
2051 arbitrary file names to be used by means of the Source_File_Name pragma.
2052 The form of this pragma is as shown in the following examples:
2053 @cindex Source_File_Name pragma
2055 @smallexample @c ada
2057 pragma Source_File_Name (My_Utilities.Stacks,
2058 Spec_File_Name => "myutilst_a.ada");
2059 pragma Source_File_name (My_Utilities.Stacks,
2060 Body_File_Name => "myutilst.ada");
2065 As shown in this example, the first argument for the pragma is the unit
2066 name (in this example a child unit). The second argument has the form
2067 of a named association. The identifier
2068 indicates whether the file name is for a spec or a body;
2069 the file name itself is given by a string literal.
2071 The source file name pragma is a configuration pragma, which means that
2072 normally it will be placed in the @file{gnat.adc}
2073 file used to hold configuration
2074 pragmas that apply to a complete compilation environment.
2075 For more details on how the @file{gnat.adc} file is created and used
2076 see @ref{Handling of Configuration Pragmas}.
2077 @cindex @file{gnat.adc}
2080 GNAT allows completely arbitrary file names to be specified using the
2081 source file name pragma. However, if the file name specified has an
2082 extension other than @file{.ads} or @file{.adb} it is necessary to use
2083 a special syntax when compiling the file. The name in this case must be
2084 preceded by the special sequence @option{-x} followed by a space and the name
2085 of the language, here @code{ada}, as in:
2088 $ gcc -c -x ada peculiar_file_name.sim
2093 @command{gnatmake} handles non-standard file names in the usual manner (the
2094 non-standard file name for the main program is simply used as the
2095 argument to gnatmake). Note that if the extension is also non-standard,
2096 then it must be included in the @command{gnatmake} command, it may not
2099 @node Alternative File Naming Schemes
2100 @section Alternative File Naming Schemes
2101 @cindex File naming schemes, alternative
2104 In the previous section, we described the use of the @code{Source_File_Name}
2105 pragma to allow arbitrary names to be assigned to individual source files.
2106 However, this approach requires one pragma for each file, and especially in
2107 large systems can result in very long @file{gnat.adc} files, and also create
2108 a maintenance problem.
2110 GNAT also provides a facility for specifying systematic file naming schemes
2111 other than the standard default naming scheme previously described. An
2112 alternative scheme for naming is specified by the use of
2113 @code{Source_File_Name} pragmas having the following format:
2114 @cindex Source_File_Name pragma
2116 @smallexample @c ada
2117 pragma Source_File_Name (
2118 Spec_File_Name => FILE_NAME_PATTERN
2119 @r{[},Casing => CASING_SPEC@r{]}
2120 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2122 pragma Source_File_Name (
2123 Body_File_Name => FILE_NAME_PATTERN
2124 @r{[},Casing => CASING_SPEC@r{]}
2125 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2127 pragma Source_File_Name (
2128 Subunit_File_Name => FILE_NAME_PATTERN
2129 @r{[},Casing => CASING_SPEC@r{]}
2130 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2132 FILE_NAME_PATTERN ::= STRING_LITERAL
2133 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2137 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2138 It contains a single asterisk character, and the unit name is substituted
2139 systematically for this asterisk. The optional parameter
2140 @code{Casing} indicates
2141 whether the unit name is to be all upper-case letters, all lower-case letters,
2142 or mixed-case. If no
2143 @code{Casing} parameter is used, then the default is all
2144 ^lower-case^upper-case^.
2146 The optional @code{Dot_Replacement} string is used to replace any periods
2147 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2148 argument is used then separating dots appear unchanged in the resulting
2150 Although the above syntax indicates that the
2151 @code{Casing} argument must appear
2152 before the @code{Dot_Replacement} argument, but it
2153 is also permissible to write these arguments in the opposite order.
2155 As indicated, it is possible to specify different naming schemes for
2156 bodies, specs, and subunits. Quite often the rule for subunits is the
2157 same as the rule for bodies, in which case, there is no need to give
2158 a separate @code{Subunit_File_Name} rule, and in this case the
2159 @code{Body_File_name} rule is used for subunits as well.
2161 The separate rule for subunits can also be used to implement the rather
2162 unusual case of a compilation environment (e.g.@: a single directory) which
2163 contains a subunit and a child unit with the same unit name. Although
2164 both units cannot appear in the same partition, the Ada Reference Manual
2165 allows (but does not require) the possibility of the two units coexisting
2166 in the same environment.
2168 The file name translation works in the following steps:
2173 If there is a specific @code{Source_File_Name} pragma for the given unit,
2174 then this is always used, and any general pattern rules are ignored.
2177 If there is a pattern type @code{Source_File_Name} pragma that applies to
2178 the unit, then the resulting file name will be used if the file exists. If
2179 more than one pattern matches, the latest one will be tried first, and the
2180 first attempt resulting in a reference to a file that exists will be used.
2183 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2184 for which the corresponding file exists, then the standard GNAT default
2185 naming rules are used.
2190 As an example of the use of this mechanism, consider a commonly used scheme
2191 in which file names are all lower case, with separating periods copied
2192 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2193 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2196 @smallexample @c ada
2197 pragma Source_File_Name
2198 (Spec_File_Name => "*.1.ada");
2199 pragma Source_File_Name
2200 (Body_File_Name => "*.2.ada");
2204 The default GNAT scheme is actually implemented by providing the following
2205 default pragmas internally:
2207 @smallexample @c ada
2208 pragma Source_File_Name
2209 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2210 pragma Source_File_Name
2211 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2215 Our final example implements a scheme typically used with one of the
2216 Ada 83 compilers, where the separator character for subunits was ``__''
2217 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2218 by adding @file{.ADA}, and subunits by
2219 adding @file{.SEP}. All file names were
2220 upper case. Child units were not present of course since this was an
2221 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2222 the same double underscore separator for child units.
2224 @smallexample @c ada
2225 pragma Source_File_Name
2226 (Spec_File_Name => "*_.ADA",
2227 Dot_Replacement => "__",
2228 Casing = Uppercase);
2229 pragma Source_File_Name
2230 (Body_File_Name => "*.ADA",
2231 Dot_Replacement => "__",
2232 Casing = Uppercase);
2233 pragma Source_File_Name
2234 (Subunit_File_Name => "*.SEP",
2235 Dot_Replacement => "__",
2236 Casing = Uppercase);
2239 @node Generating Object Files
2240 @section Generating Object Files
2243 An Ada program consists of a set of source files, and the first step in
2244 compiling the program is to generate the corresponding object files.
2245 These are generated by compiling a subset of these source files.
2246 The files you need to compile are the following:
2250 If a package spec has no body, compile the package spec to produce the
2251 object file for the package.
2254 If a package has both a spec and a body, compile the body to produce the
2255 object file for the package. The source file for the package spec need
2256 not be compiled in this case because there is only one object file, which
2257 contains the code for both the spec and body of the package.
2260 For a subprogram, compile the subprogram body to produce the object file
2261 for the subprogram. The spec, if one is present, is as usual in a
2262 separate file, and need not be compiled.
2266 In the case of subunits, only compile the parent unit. A single object
2267 file is generated for the entire subunit tree, which includes all the
2271 Compile child units independently of their parent units
2272 (though, of course, the spec of all the ancestor unit must be present in order
2273 to compile a child unit).
2277 Compile generic units in the same manner as any other units. The object
2278 files in this case are small dummy files that contain at most the
2279 flag used for elaboration checking. This is because GNAT always handles generic
2280 instantiation by means of macro expansion. However, it is still necessary to
2281 compile generic units, for dependency checking and elaboration purposes.
2285 The preceding rules describe the set of files that must be compiled to
2286 generate the object files for a program. Each object file has the same
2287 name as the corresponding source file, except that the extension is
2290 You may wish to compile other files for the purpose of checking their
2291 syntactic and semantic correctness. For example, in the case where a
2292 package has a separate spec and body, you would not normally compile the
2293 spec. However, it is convenient in practice to compile the spec to make
2294 sure it is error-free before compiling clients of this spec, because such
2295 compilations will fail if there is an error in the spec.
2297 GNAT provides an option for compiling such files purely for the
2298 purposes of checking correctness; such compilations are not required as
2299 part of the process of building a program. To compile a file in this
2300 checking mode, use the @option{-gnatc} switch.
2302 @node Source Dependencies
2303 @section Source Dependencies
2306 A given object file clearly depends on the source file which is compiled
2307 to produce it. Here we are using @dfn{depends} in the sense of a typical
2308 @code{make} utility; in other words, an object file depends on a source
2309 file if changes to the source file require the object file to be
2311 In addition to this basic dependency, a given object may depend on
2312 additional source files as follows:
2316 If a file being compiled @code{with}'s a unit @var{X}, the object file
2317 depends on the file containing the spec of unit @var{X}. This includes
2318 files that are @code{with}'ed implicitly either because they are parents
2319 of @code{with}'ed child units or they are run-time units required by the
2320 language constructs used in a particular unit.
2323 If a file being compiled instantiates a library level generic unit, the
2324 object file depends on both the spec and body files for this generic
2328 If a file being compiled instantiates a generic unit defined within a
2329 package, the object file depends on the body file for the package as
2330 well as the spec file.
2334 @cindex @option{-gnatn} switch
2335 If a file being compiled contains a call to a subprogram for which
2336 pragma @code{Inline} applies and inlining is activated with the
2337 @option{-gnatn} switch, the object file depends on the file containing the
2338 body of this subprogram as well as on the file containing the spec. Note
2339 that for inlining to actually occur as a result of the use of this switch,
2340 it is necessary to compile in optimizing mode.
2342 @cindex @option{-gnatN} switch
2343 The use of @option{-gnatN} activates inlining optimization
2344 that is performed by the front end of the compiler. This inlining does
2345 not require that the code generation be optimized. Like @option{-gnatn},
2346 the use of this switch generates additional dependencies.
2348 When using a gcc-based back end (in practice this means using any version
2349 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2350 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2351 Historically front end inlining was more extensive than the gcc back end
2352 inlining, but that is no longer the case.
2355 If an object file @file{O} depends on the proper body of a subunit through
2356 inlining or instantiation, it depends on the parent unit of the subunit.
2357 This means that any modification of the parent unit or one of its subunits
2358 affects the compilation of @file{O}.
2361 The object file for a parent unit depends on all its subunit body files.
2364 The previous two rules meant that for purposes of computing dependencies and
2365 recompilation, a body and all its subunits are treated as an indivisible whole.
2368 These rules are applied transitively: if unit @code{A} @code{with}'s
2369 unit @code{B}, whose elaboration calls an inlined procedure in package
2370 @code{C}, the object file for unit @code{A} will depend on the body of
2371 @code{C}, in file @file{c.adb}.
2373 The set of dependent files described by these rules includes all the
2374 files on which the unit is semantically dependent, as dictated by the
2375 Ada language standard. However, it is a superset of what the
2376 standard describes, because it includes generic, inline, and subunit
2379 An object file must be recreated by recompiling the corresponding source
2380 file if any of the source files on which it depends are modified. For
2381 example, if the @code{make} utility is used to control compilation,
2382 the rule for an Ada object file must mention all the source files on
2383 which the object file depends, according to the above definition.
2384 The determination of the necessary
2385 recompilations is done automatically when one uses @command{gnatmake}.
2388 @node The Ada Library Information Files
2389 @section The Ada Library Information Files
2390 @cindex Ada Library Information files
2391 @cindex @file{ALI} files
2394 Each compilation actually generates two output files. The first of these
2395 is the normal object file that has a @file{.o} extension. The second is a
2396 text file containing full dependency information. It has the same
2397 name as the source file, but an @file{.ali} extension.
2398 This file is known as the Ada Library Information (@file{ALI}) file.
2399 The following information is contained in the @file{ALI} file.
2403 Version information (indicates which version of GNAT was used to compile
2404 the unit(s) in question)
2407 Main program information (including priority and time slice settings,
2408 as well as the wide character encoding used during compilation).
2411 List of arguments used in the @command{gcc} command for the compilation
2414 Attributes of the unit, including configuration pragmas used, an indication
2415 of whether the compilation was successful, exception model used etc.
2418 A list of relevant restrictions applying to the unit (used for consistency)
2422 Categorization information (e.g.@: use of pragma @code{Pure}).
2425 Information on all @code{with}'ed units, including presence of
2426 @code{Elaborate} or @code{Elaborate_All} pragmas.
2429 Information from any @code{Linker_Options} pragmas used in the unit
2432 Information on the use of @code{Body_Version} or @code{Version}
2433 attributes in the unit.
2436 Dependency information. This is a list of files, together with
2437 time stamp and checksum information. These are files on which
2438 the unit depends in the sense that recompilation is required
2439 if any of these units are modified.
2442 Cross-reference data. Contains information on all entities referenced
2443 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2444 provide cross-reference information.
2449 For a full detailed description of the format of the @file{ALI} file,
2450 see the source of the body of unit @code{Lib.Writ}, contained in file
2451 @file{lib-writ.adb} in the GNAT compiler sources.
2453 @node Binding an Ada Program
2454 @section Binding an Ada Program
2457 When using languages such as C and C++, once the source files have been
2458 compiled the only remaining step in building an executable program
2459 is linking the object modules together. This means that it is possible to
2460 link an inconsistent version of a program, in which two units have
2461 included different versions of the same header.
2463 The rules of Ada do not permit such an inconsistent program to be built.
2464 For example, if two clients have different versions of the same package,
2465 it is illegal to build a program containing these two clients.
2466 These rules are enforced by the GNAT binder, which also determines an
2467 elaboration order consistent with the Ada rules.
2469 The GNAT binder is run after all the object files for a program have
2470 been created. It is given the name of the main program unit, and from
2471 this it determines the set of units required by the program, by reading the
2472 corresponding ALI files. It generates error messages if the program is
2473 inconsistent or if no valid order of elaboration exists.
2475 If no errors are detected, the binder produces a main program, in Ada by
2476 default, that contains calls to the elaboration procedures of those
2477 compilation unit that require them, followed by
2478 a call to the main program. This Ada program is compiled to generate the
2479 object file for the main program. The name of
2480 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2481 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2484 Finally, the linker is used to build the resulting executable program,
2485 using the object from the main program from the bind step as well as the
2486 object files for the Ada units of the program.
2488 @node Mixed Language Programming
2489 @section Mixed Language Programming
2490 @cindex Mixed Language Programming
2493 This section describes how to develop a mixed-language program,
2494 specifically one that comprises units in both Ada and C.
2497 * Interfacing to C::
2498 * Calling Conventions::
2501 @node Interfacing to C
2502 @subsection Interfacing to C
2504 Interfacing Ada with a foreign language such as C involves using
2505 compiler directives to import and/or export entity definitions in each
2506 language---using @code{extern} statements in C, for instance, and the
2507 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2508 A full treatment of these topics is provided in Appendix B, section 1
2509 of the Ada Reference Manual.
2511 There are two ways to build a program using GNAT that contains some Ada
2512 sources and some foreign language sources, depending on whether or not
2513 the main subprogram is written in Ada. Here is a source example with
2514 the main subprogram in Ada:
2520 void print_num (int num)
2522 printf ("num is %d.\n", num);
2528 /* num_from_Ada is declared in my_main.adb */
2529 extern int num_from_Ada;
2533 return num_from_Ada;
2537 @smallexample @c ada
2539 procedure My_Main is
2541 -- Declare then export an Integer entity called num_from_Ada
2542 My_Num : Integer := 10;
2543 pragma Export (C, My_Num, "num_from_Ada");
2545 -- Declare an Ada function spec for Get_Num, then use
2546 -- C function get_num for the implementation.
2547 function Get_Num return Integer;
2548 pragma Import (C, Get_Num, "get_num");
2550 -- Declare an Ada procedure spec for Print_Num, then use
2551 -- C function print_num for the implementation.
2552 procedure Print_Num (Num : Integer);
2553 pragma Import (C, Print_Num, "print_num");
2556 Print_Num (Get_Num);
2562 To build this example, first compile the foreign language files to
2563 generate object files:
2565 ^gcc -c file1.c^gcc -c FILE1.C^
2566 ^gcc -c file2.c^gcc -c FILE2.C^
2570 Then, compile the Ada units to produce a set of object files and ALI
2573 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2577 Run the Ada binder on the Ada main program:
2579 gnatbind my_main.ali
2583 Link the Ada main program, the Ada objects and the other language
2586 gnatlink my_main.ali file1.o file2.o
2590 The last three steps can be grouped in a single command:
2592 gnatmake my_main.adb -largs file1.o file2.o
2595 @cindex Binder output file
2597 If the main program is in a language other than Ada, then you may have
2598 more than one entry point into the Ada subsystem. You must use a special
2599 binder option to generate callable routines that initialize and
2600 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2601 Calls to the initialization and finalization routines must be inserted
2602 in the main program, or some other appropriate point in the code. The
2603 call to initialize the Ada units must occur before the first Ada
2604 subprogram is called, and the call to finalize the Ada units must occur
2605 after the last Ada subprogram returns. The binder will place the
2606 initialization and finalization subprograms into the
2607 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2608 sources. To illustrate, we have the following example:
2612 extern void adainit (void);
2613 extern void adafinal (void);
2614 extern int add (int, int);
2615 extern int sub (int, int);
2617 int main (int argc, char *argv[])
2623 /* Should print "21 + 7 = 28" */
2624 printf ("%d + %d = %d\n", a, b, add (a, b));
2625 /* Should print "21 - 7 = 14" */
2626 printf ("%d - %d = %d\n", a, b, sub (a, b));
2632 @smallexample @c ada
2635 function Add (A, B : Integer) return Integer;
2636 pragma Export (C, Add, "add");
2640 package body Unit1 is
2641 function Add (A, B : Integer) return Integer is
2649 function Sub (A, B : Integer) return Integer;
2650 pragma Export (C, Sub, "sub");
2654 package body Unit2 is
2655 function Sub (A, B : Integer) return Integer is
2664 The build procedure for this application is similar to the last
2665 example's. First, compile the foreign language files to generate object
2668 ^gcc -c main.c^gcc -c main.c^
2672 Next, compile the Ada units to produce a set of object files and ALI
2675 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2676 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2680 Run the Ada binder on every generated ALI file. Make sure to use the
2681 @option{-n} option to specify a foreign main program:
2683 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2687 Link the Ada main program, the Ada objects and the foreign language
2688 objects. You need only list the last ALI file here:
2690 gnatlink unit2.ali main.o -o exec_file
2693 This procedure yields a binary executable called @file{exec_file}.
2697 Depending on the circumstances (for example when your non-Ada main object
2698 does not provide symbol @code{main}), you may also need to instruct the
2699 GNAT linker not to include the standard startup objects by passing the
2700 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2702 @node Calling Conventions
2703 @subsection Calling Conventions
2704 @cindex Foreign Languages
2705 @cindex Calling Conventions
2706 GNAT follows standard calling sequence conventions and will thus interface
2707 to any other language that also follows these conventions. The following
2708 Convention identifiers are recognized by GNAT:
2711 @cindex Interfacing to Ada
2712 @cindex Other Ada compilers
2713 @cindex Convention Ada
2715 This indicates that the standard Ada calling sequence will be
2716 used and all Ada data items may be passed without any limitations in the
2717 case where GNAT is used to generate both the caller and callee. It is also
2718 possible to mix GNAT generated code and code generated by another Ada
2719 compiler. In this case, the data types should be restricted to simple
2720 cases, including primitive types. Whether complex data types can be passed
2721 depends on the situation. Probably it is safe to pass simple arrays, such
2722 as arrays of integers or floats. Records may or may not work, depending
2723 on whether both compilers lay them out identically. Complex structures
2724 involving variant records, access parameters, tasks, or protected types,
2725 are unlikely to be able to be passed.
2727 Note that in the case of GNAT running
2728 on a platform that supports HP Ada 83, a higher degree of compatibility
2729 can be guaranteed, and in particular records are layed out in an identical
2730 manner in the two compilers. Note also that if output from two different
2731 compilers is mixed, the program is responsible for dealing with elaboration
2732 issues. Probably the safest approach is to write the main program in the
2733 version of Ada other than GNAT, so that it takes care of its own elaboration
2734 requirements, and then call the GNAT-generated adainit procedure to ensure
2735 elaboration of the GNAT components. Consult the documentation of the other
2736 Ada compiler for further details on elaboration.
2738 However, it is not possible to mix the tasking run time of GNAT and
2739 HP Ada 83, All the tasking operations must either be entirely within
2740 GNAT compiled sections of the program, or entirely within HP Ada 83
2741 compiled sections of the program.
2743 @cindex Interfacing to Assembly
2744 @cindex Convention Assembler
2746 Specifies assembler as the convention. In practice this has the
2747 same effect as convention Ada (but is not equivalent in the sense of being
2748 considered the same convention).
2750 @cindex Convention Asm
2753 Equivalent to Assembler.
2755 @cindex Interfacing to COBOL
2756 @cindex Convention COBOL
2759 Data will be passed according to the conventions described
2760 in section B.4 of the Ada Reference Manual.
2763 @cindex Interfacing to C
2764 @cindex Convention C
2766 Data will be passed according to the conventions described
2767 in section B.3 of the Ada Reference Manual.
2769 A note on interfacing to a C ``varargs'' function:
2770 @findex C varargs function
2771 @cindex Interfacing to C varargs function
2772 @cindex varargs function interfaces
2776 In C, @code{varargs} allows a function to take a variable number of
2777 arguments. There is no direct equivalent in this to Ada. One
2778 approach that can be used is to create a C wrapper for each
2779 different profile and then interface to this C wrapper. For
2780 example, to print an @code{int} value using @code{printf},
2781 create a C function @code{printfi} that takes two arguments, a
2782 pointer to a string and an int, and calls @code{printf}.
2783 Then in the Ada program, use pragma @code{Import} to
2784 interface to @code{printfi}.
2787 It may work on some platforms to directly interface to
2788 a @code{varargs} function by providing a specific Ada profile
2789 for a particular call. However, this does not work on
2790 all platforms, since there is no guarantee that the
2791 calling sequence for a two argument normal C function
2792 is the same as for calling a @code{varargs} C function with
2793 the same two arguments.
2796 @cindex Convention Default
2801 @cindex Convention External
2808 @cindex Interfacing to C++
2809 @cindex Convention C++
2810 @item C_Plus_Plus (or CPP)
2811 This stands for C++. For most purposes this is identical to C.
2812 See the separate description of the specialized GNAT pragmas relating to
2813 C++ interfacing for further details.
2817 @cindex Interfacing to Fortran
2818 @cindex Convention Fortran
2820 Data will be passed according to the conventions described
2821 in section B.5 of the Ada Reference Manual.
2824 This applies to an intrinsic operation, as defined in the Ada
2825 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2826 this means that the body of the subprogram is provided by the compiler itself,
2827 usually by means of an efficient code sequence, and that the user does not
2828 supply an explicit body for it. In an application program, the pragma may
2829 be applied to the following sets of names:
2833 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2834 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2835 two formal parameters. The
2836 first one must be a signed integer type or a modular type with a binary
2837 modulus, and the second parameter must be of type Natural.
2838 The return type must be the same as the type of the first argument. The size
2839 of this type can only be 8, 16, 32, or 64.
2842 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2843 The corresponding operator declaration must have parameters and result type
2844 that have the same root numeric type (for example, all three are long_float
2845 types). This simplifies the definition of operations that use type checking
2846 to perform dimensional checks:
2848 @smallexample @c ada
2849 type Distance is new Long_Float;
2850 type Time is new Long_Float;
2851 type Velocity is new Long_Float;
2852 function "/" (D : Distance; T : Time)
2854 pragma Import (Intrinsic, "/");
2858 This common idiom is often programmed with a generic definition and an
2859 explicit body. The pragma makes it simpler to introduce such declarations.
2860 It incurs no overhead in compilation time or code size, because it is
2861 implemented as a single machine instruction.
2864 General subprogram entities, to bind an Ada subprogram declaration to
2865 a compiler builtin by name with back-ends where such interfaces are
2866 available. A typical example is the set of ``__builtin'' functions
2867 exposed by the GCC back-end, as in the following example:
2869 @smallexample @c ada
2870 function builtin_sqrt (F : Float) return Float;
2871 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2874 Most of the GCC builtins are accessible this way, and as for other
2875 import conventions (e.g. C), it is the user's responsibility to ensure
2876 that the Ada subprogram profile matches the underlying builtin
2884 @cindex Convention Stdcall
2886 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2887 and specifies that the @code{Stdcall} calling sequence will be used,
2888 as defined by the NT API. Nevertheless, to ease building
2889 cross-platform bindings this convention will be handled as a @code{C} calling
2890 convention on non-Windows platforms.
2893 @cindex Convention DLL
2895 This is equivalent to @code{Stdcall}.
2898 @cindex Convention Win32
2900 This is equivalent to @code{Stdcall}.
2904 @cindex Convention Stubbed
2906 This is a special convention that indicates that the compiler
2907 should provide a stub body that raises @code{Program_Error}.
2911 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2912 that can be used to parameterize conventions and allow additional synonyms
2913 to be specified. For example if you have legacy code in which the convention
2914 identifier Fortran77 was used for Fortran, you can use the configuration
2917 @smallexample @c ada
2918 pragma Convention_Identifier (Fortran77, Fortran);
2922 And from now on the identifier Fortran77 may be used as a convention
2923 identifier (for example in an @code{Import} pragma) with the same
2927 @node Building Mixed Ada & C++ Programs
2928 @section Building Mixed Ada and C++ Programs
2931 A programmer inexperienced with mixed-language development may find that
2932 building an application containing both Ada and C++ code can be a
2933 challenge. This section gives a few
2934 hints that should make this task easier. The first section addresses
2935 the differences between interfacing with C and interfacing with C++.
2937 looks into the delicate problem of linking the complete application from
2938 its Ada and C++ parts. The last section gives some hints on how the GNAT
2939 run-time library can be adapted in order to allow inter-language dispatching
2940 with a new C++ compiler.
2943 * Interfacing to C++::
2944 * Linking a Mixed C++ & Ada Program::
2945 * A Simple Example::
2946 * Interfacing with C++ constructors::
2947 * Interfacing with C++ at the Class Level::
2950 @node Interfacing to C++
2951 @subsection Interfacing to C++
2954 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2955 generating code that is compatible with the G++ Application Binary
2956 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2959 Interfacing can be done at 3 levels: simple data, subprograms, and
2960 classes. In the first two cases, GNAT offers a specific @code{Convention
2961 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2962 Usually, C++ mangles the names of subprograms. To generate proper mangled
2963 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2964 This problem can also be addressed manually in two ways:
2968 by modifying the C++ code in order to force a C convention using
2969 the @code{extern "C"} syntax.
2972 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2973 Link_Name argument of the pragma import.
2977 Interfacing at the class level can be achieved by using the GNAT specific
2978 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2979 gnat_rm, GNAT Reference Manual}, for additional information.
2981 @node Linking a Mixed C++ & Ada Program
2982 @subsection Linking a Mixed C++ & Ada Program
2985 Usually the linker of the C++ development system must be used to link
2986 mixed applications because most C++ systems will resolve elaboration
2987 issues (such as calling constructors on global class instances)
2988 transparently during the link phase. GNAT has been adapted to ease the
2989 use of a foreign linker for the last phase. Three cases can be
2994 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2995 The C++ linker can simply be called by using the C++ specific driver
2998 Note that if the C++ code uses inline functions, you will need to
2999 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3000 order to provide an existing function implementation that the Ada code can
3004 $ g++ -c -fkeep-inline-functions file1.C
3005 $ g++ -c -fkeep-inline-functions file2.C
3006 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3010 Using GNAT and G++ from two different GCC installations: If both
3011 compilers are on the @env{PATH}, the previous method may be used. It is
3012 important to note that environment variables such as
3013 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3014 @env{GCC_ROOT} will affect both compilers
3015 at the same time and may make one of the two compilers operate
3016 improperly if set during invocation of the wrong compiler. It is also
3017 very important that the linker uses the proper @file{libgcc.a} GCC
3018 library -- that is, the one from the C++ compiler installation. The
3019 implicit link command as suggested in the @command{gnatmake} command
3020 from the former example can be replaced by an explicit link command with
3021 the full-verbosity option in order to verify which library is used:
3024 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3026 If there is a problem due to interfering environment variables, it can
3027 be worked around by using an intermediate script. The following example
3028 shows the proper script to use when GNAT has not been installed at its
3029 default location and g++ has been installed at its default location:
3037 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3041 Using a non-GNU C++ compiler: The commands previously described can be
3042 used to insure that the C++ linker is used. Nonetheless, you need to add
3043 a few more parameters to the link command line, depending on the exception
3046 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3047 to the libgcc libraries are required:
3052 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3053 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3056 Where CC is the name of the non-GNU C++ compiler.
3058 If the @code{zero cost} exception mechanism is used, and the platform
3059 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3060 paths to more objects are required:
3065 CC `gcc -print-file-name=crtbegin.o` $* \
3066 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3067 `gcc -print-file-name=crtend.o`
3068 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3071 If the @code{zero cost} exception mechanism is used, and the platform
3072 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3073 Tru64 or AIX), the simple approach described above will not work and
3074 a pre-linking phase using GNAT will be necessary.
3078 Another alternative is to use the @command{gprbuild} multi-language builder
3079 which has a large knowledge base and knows how to link Ada and C++ code
3080 together automatically in most cases.
3082 @node A Simple Example
3083 @subsection A Simple Example
3085 The following example, provided as part of the GNAT examples, shows how
3086 to achieve procedural interfacing between Ada and C++ in both
3087 directions. The C++ class A has two methods. The first method is exported
3088 to Ada by the means of an extern C wrapper function. The second method
3089 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3090 a limited record with a layout comparable to the C++ class. The Ada
3091 subprogram, in turn, calls the C++ method. So, starting from the C++
3092 main program, the process passes back and forth between the two
3096 Here are the compilation commands:
3098 $ gnatmake -c simple_cpp_interface
3101 $ gnatbind -n simple_cpp_interface
3102 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3103 -lstdc++ ex7.o cpp_main.o
3107 Here are the corresponding sources:
3115 void adainit (void);
3116 void adafinal (void);
3117 void method1 (A *t);
3139 class A : public Origin @{
3141 void method1 (void);
3142 void method2 (int v);
3152 extern "C" @{ void ada_method2 (A *t, int v);@}
3154 void A::method1 (void)
3157 printf ("in A::method1, a_value = %d \n",a_value);
3161 void A::method2 (int v)
3163 ada_method2 (this, v);
3164 printf ("in A::method2, a_value = %d \n",a_value);
3171 printf ("in A::A, a_value = %d \n",a_value);
3175 @smallexample @c ada
3177 package body Simple_Cpp_Interface is
3179 procedure Ada_Method2 (This : in out A; V : Integer) is
3185 end Simple_Cpp_Interface;
3188 package Simple_Cpp_Interface is
3191 Vptr : System.Address;
3195 pragma Convention (C, A);
3197 procedure Method1 (This : in out A);
3198 pragma Import (C, Method1);
3200 procedure Ada_Method2 (This : in out A; V : Integer);
3201 pragma Export (C, Ada_Method2);
3203 end Simple_Cpp_Interface;
3206 @node Interfacing with C++ constructors
3207 @subsection Interfacing with C++ constructors
3210 In order to interface with C++ constructors GNAT provides the
3211 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3212 gnat_rm, GNAT Reference Manual}, for additional information).
3213 In this section we present some common uses of C++ constructors
3214 in mixed-languages programs in GNAT.
3216 Let us assume that we need to interface with the following
3224 @b{virtual} int Get_Value ();
3225 Root(); // Default constructor
3226 Root(int v); // 1st non-default constructor
3227 Root(int v, int w); // 2nd non-default constructor
3231 For this purpose we can write the following package spec (further
3232 information on how to build this spec is available in
3233 @ref{Interfacing with C++ at the Class Level} and
3234 @ref{Generating Ada Bindings for C and C++ headers}).
3236 @smallexample @c ada
3237 with Interfaces.C; use Interfaces.C;
3239 type Root is tagged limited record
3243 pragma Import (CPP, Root);
3245 function Get_Value (Obj : Root) return int;
3246 pragma Import (CPP, Get_Value);
3248 function Constructor return Root;
3249 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3251 function Constructor (v : Integer) return Root;
3252 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3254 function Constructor (v, w : Integer) return Root;
3255 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3259 On the Ada side the constructor is represented by a function (whose
3260 name is arbitrary) that returns the classwide type corresponding to
3261 the imported C++ class. Although the constructor is described as a
3262 function, it is typically a procedure with an extra implicit argument
3263 (the object being initialized) at the implementation level. GNAT
3264 issues the appropriate call, whatever it is, to get the object
3265 properly initialized.
3267 Constructors can only appear in the following contexts:
3271 On the right side of an initialization of an object of type @var{T}.
3273 On the right side of an initialization of a record component of type @var{T}.
3275 In an Ada 2005 limited aggregate.
3277 In an Ada 2005 nested limited aggregate.
3279 In an Ada 2005 limited aggregate that initializes an object built in
3280 place by an extended return statement.
3284 In a declaration of an object whose type is a class imported from C++,
3285 either the default C++ constructor is implicitly called by GNAT, or
3286 else the required C++ constructor must be explicitly called in the
3287 expression that initializes the object. For example:
3289 @smallexample @c ada
3291 Obj2 : Root := Constructor;
3292 Obj3 : Root := Constructor (v => 10);
3293 Obj4 : Root := Constructor (30, 40);
3296 The first two declarations are equivalent: in both cases the default C++
3297 constructor is invoked (in the former case the call to the constructor is
3298 implicit, and in the latter case the call is explicit in the object
3299 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3300 that takes an integer argument, and @code{Obj4} is initialized by the
3301 non-default C++ constructor that takes two integers.
3303 Let us derive the imported C++ class in the Ada side. For example:
3305 @smallexample @c ada
3306 type DT is new Root with record
3307 C_Value : Natural := 2009;
3311 In this case the components DT inherited from the C++ side must be
3312 initialized by a C++ constructor, and the additional Ada components
3313 of type DT are initialized by GNAT. The initialization of such an
3314 object is done either by default, or by means of a function returning
3315 an aggregate of type DT, or by means of an extension aggregate.
3317 @smallexample @c ada
3319 Obj6 : DT := Function_Returning_DT (50);
3320 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3323 The declaration of @code{Obj5} invokes the default constructors: the
3324 C++ default constructor of the parent type takes care of the initialization
3325 of the components inherited from Root, and GNAT takes care of the default
3326 initialization of the additional Ada components of type DT (that is,
3327 @code{C_Value} is initialized to value 2009). The order of invocation of
3328 the constructors is consistent with the order of elaboration required by
3329 Ada and C++. That is, the constructor of the parent type is always called
3330 before the constructor of the derived type.
3332 Let us now consider a record that has components whose type is imported
3333 from C++. For example:
3335 @smallexample @c ada
3336 type Rec1 is limited record
3337 Data1 : Root := Constructor (10);
3338 Value : Natural := 1000;
3341 type Rec2 (D : Integer := 20) is limited record
3343 Data2 : Root := Constructor (D, 30);
3347 The initialization of an object of type @code{Rec2} will call the
3348 non-default C++ constructors specified for the imported components.
3351 @smallexample @c ada
3355 Using Ada 2005 we can use limited aggregates to initialize an object
3356 invoking C++ constructors that differ from those specified in the type
3357 declarations. For example:
3359 @smallexample @c ada
3360 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3365 The above declaration uses an Ada 2005 limited aggregate to
3366 initialize @code{Obj9}, and the C++ constructor that has two integer
3367 arguments is invoked to initialize the @code{Data1} component instead
3368 of the constructor specified in the declaration of type @code{Rec1}. In
3369 Ada 2005 the box in the aggregate indicates that unspecified components
3370 are initialized using the expression (if any) available in the component
3371 declaration. That is, in this case discriminant @code{D} is initialized
3372 to value @code{20}, @code{Value} is initialized to value 1000, and the
3373 non-default C++ constructor that handles two integers takes care of
3374 initializing component @code{Data2} with values @code{20,30}.
3376 In Ada 2005 we can use the extended return statement to build the Ada
3377 equivalent to C++ non-default constructors. For example:
3379 @smallexample @c ada
3380 function Constructor (V : Integer) return Rec2 is
3382 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3385 -- Further actions required for construction of
3386 -- objects of type Rec2
3392 In this example the extended return statement construct is used to
3393 build in place the returned object whose components are initialized
3394 by means of a limited aggregate. Any further action associated with
3395 the constructor can be placed inside the construct.
3397 @node Interfacing with C++ at the Class Level
3398 @subsection Interfacing with C++ at the Class Level
3400 In this section we demonstrate the GNAT features for interfacing with
3401 C++ by means of an example making use of Ada 2005 abstract interface
3402 types. This example consists of a classification of animals; classes
3403 have been used to model our main classification of animals, and
3404 interfaces provide support for the management of secondary
3405 classifications. We first demonstrate a case in which the types and
3406 constructors are defined on the C++ side and imported from the Ada
3407 side, and latter the reverse case.
3409 The root of our derivation will be the @code{Animal} class, with a
3410 single private attribute (the @code{Age} of the animal) and two public
3411 primitives to set and get the value of this attribute.
3416 @b{virtual} void Set_Age (int New_Age);
3417 @b{virtual} int Age ();
3423 Abstract interface types are defined in C++ by means of classes with pure
3424 virtual functions and no data members. In our example we will use two
3425 interfaces that provide support for the common management of @code{Carnivore}
3426 and @code{Domestic} animals:
3429 @b{class} Carnivore @{
3431 @b{virtual} int Number_Of_Teeth () = 0;
3434 @b{class} Domestic @{
3436 @b{virtual void} Set_Owner (char* Name) = 0;
3440 Using these declarations, we can now say that a @code{Dog} is an animal that is
3441 both Carnivore and Domestic, that is:
3444 @b{class} Dog : Animal, Carnivore, Domestic @{
3446 @b{virtual} int Number_Of_Teeth ();
3447 @b{virtual} void Set_Owner (char* Name);
3449 Dog(); // Constructor
3456 In the following examples we will assume that the previous declarations are
3457 located in a file named @code{animals.h}. The following package demonstrates
3458 how to import these C++ declarations from the Ada side:
3460 @smallexample @c ada
3461 with Interfaces.C.Strings; use Interfaces.C.Strings;
3463 type Carnivore is interface;
3464 pragma Convention (C_Plus_Plus, Carnivore);
3465 function Number_Of_Teeth (X : Carnivore)
3466 return Natural is abstract;
3468 type Domestic is interface;
3469 pragma Convention (C_Plus_Plus, Set_Owner);
3471 (X : in out Domestic;
3472 Name : Chars_Ptr) is abstract;
3474 type Animal is tagged record
3477 pragma Import (C_Plus_Plus, Animal);
3479 procedure Set_Age (X : in out Animal; Age : Integer);
3480 pragma Import (C_Plus_Plus, Set_Age);
3482 function Age (X : Animal) return Integer;
3483 pragma Import (C_Plus_Plus, Age);
3485 type Dog is new Animal and Carnivore and Domestic with record
3486 Tooth_Count : Natural;
3487 Owner : String (1 .. 30);
3489 pragma Import (C_Plus_Plus, Dog);
3491 function Number_Of_Teeth (A : Dog) return Integer;
3492 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3494 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3495 pragma Import (C_Plus_Plus, Set_Owner);
3497 function New_Dog return Dog;
3498 pragma CPP_Constructor (New_Dog);
3499 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3503 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3504 interfacing with these C++ classes is easy. The only requirement is that all
3505 the primitives and components must be declared exactly in the same order in
3508 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3509 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3510 the arguments to the called primitives will be the same as for C++. For the
3511 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3512 to indicate that they have been defined on the C++ side; this is required
3513 because the dispatch table associated with these tagged types will be built
3514 in the C++ side and therefore will not contain the predefined Ada primitives
3515 which Ada would otherwise expect.
3517 As the reader can see there is no need to indicate the C++ mangled names
3518 associated with each subprogram because it is assumed that all the calls to
3519 these primitives will be dispatching calls. The only exception is the
3520 constructor, which must be registered with the compiler by means of
3521 @code{pragma CPP_Constructor} and needs to provide its associated C++
3522 mangled name because the Ada compiler generates direct calls to it.
3524 With the above packages we can now declare objects of type Dog on the Ada side
3525 and dispatch calls to the corresponding subprograms on the C++ side. We can
3526 also extend the tagged type Dog with further fields and primitives, and
3527 override some of its C++ primitives on the Ada side. For example, here we have
3528 a type derivation defined on the Ada side that inherits all the dispatching
3529 primitives of the ancestor from the C++ side.
3532 @b{with} Animals; @b{use} Animals;
3533 @b{package} Vaccinated_Animals @b{is}
3534 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3535 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3536 @b{end} Vaccinated_Animals;
3539 It is important to note that, because of the ABI compatibility, the programmer
3540 does not need to add any further information to indicate either the object
3541 layout or the dispatch table entry associated with each dispatching operation.
3543 Now let us define all the types and constructors on the Ada side and export
3544 them to C++, using the same hierarchy of our previous example:
3546 @smallexample @c ada
3547 with Interfaces.C.Strings;
3548 use Interfaces.C.Strings;
3550 type Carnivore is interface;
3551 pragma Convention (C_Plus_Plus, Carnivore);
3552 function Number_Of_Teeth (X : Carnivore)
3553 return Natural is abstract;
3555 type Domestic is interface;
3556 pragma Convention (C_Plus_Plus, Set_Owner);
3558 (X : in out Domestic;
3559 Name : Chars_Ptr) is abstract;
3561 type Animal is tagged record
3564 pragma Convention (C_Plus_Plus, Animal);
3566 procedure Set_Age (X : in out Animal; Age : Integer);
3567 pragma Export (C_Plus_Plus, Set_Age);
3569 function Age (X : Animal) return Integer;
3570 pragma Export (C_Plus_Plus, Age);
3572 type Dog is new Animal and Carnivore and Domestic with record
3573 Tooth_Count : Natural;
3574 Owner : String (1 .. 30);
3576 pragma Convention (C_Plus_Plus, Dog);
3578 function Number_Of_Teeth (A : Dog) return Integer;
3579 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3581 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3582 pragma Export (C_Plus_Plus, Set_Owner);
3584 function New_Dog return Dog'Class;
3585 pragma Export (C_Plus_Plus, New_Dog);
3589 Compared with our previous example the only difference is the use of
3590 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3591 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3592 nothing else to be done; as explained above, the only requirement is that all
3593 the primitives and components are declared in exactly the same order.
3595 For completeness, let us see a brief C++ main program that uses the
3596 declarations available in @code{animals.h} (presented in our first example) to
3597 import and use the declarations from the Ada side, properly initializing and
3598 finalizing the Ada run-time system along the way:
3601 @b{#include} "animals.h"
3602 @b{#include} <iostream>
3603 @b{using namespace} std;
3605 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3606 void Check_Domestic (Domestic *obj) @{@dots{}@}
3607 void Check_Animal (Animal *obj) @{@dots{}@}
3608 void Check_Dog (Dog *obj) @{@dots{}@}
3611 void adainit (void);
3612 void adafinal (void);
3618 Dog *obj = new_dog(); // Ada constructor
3619 Check_Carnivore (obj); // Check secondary DT
3620 Check_Domestic (obj); // Check secondary DT
3621 Check_Animal (obj); // Check primary DT
3622 Check_Dog (obj); // Check primary DT
3627 adainit (); test(); adafinal ();
3632 @node Comparison between GNAT and C/C++ Compilation Models
3633 @section Comparison between GNAT and C/C++ Compilation Models
3636 The GNAT model of compilation is close to the C and C++ models. You can
3637 think of Ada specs as corresponding to header files in C. As in C, you
3638 don't need to compile specs; they are compiled when they are used. The
3639 Ada @code{with} is similar in effect to the @code{#include} of a C
3642 One notable difference is that, in Ada, you may compile specs separately
3643 to check them for semantic and syntactic accuracy. This is not always
3644 possible with C headers because they are fragments of programs that have
3645 less specific syntactic or semantic rules.
3647 The other major difference is the requirement for running the binder,
3648 which performs two important functions. First, it checks for
3649 consistency. In C or C++, the only defense against assembling
3650 inconsistent programs lies outside the compiler, in a makefile, for
3651 example. The binder satisfies the Ada requirement that it be impossible
3652 to construct an inconsistent program when the compiler is used in normal
3655 @cindex Elaboration order control
3656 The other important function of the binder is to deal with elaboration
3657 issues. There are also elaboration issues in C++ that are handled
3658 automatically. This automatic handling has the advantage of being
3659 simpler to use, but the C++ programmer has no control over elaboration.
3660 Where @code{gnatbind} might complain there was no valid order of
3661 elaboration, a C++ compiler would simply construct a program that
3662 malfunctioned at run time.
3665 @node Comparison between GNAT and Conventional Ada Library Models
3666 @section Comparison between GNAT and Conventional Ada Library Models
3669 This section is intended for Ada programmers who have
3670 used an Ada compiler implementing the traditional Ada library
3671 model, as described in the Ada Reference Manual.
3673 @cindex GNAT library
3674 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3675 source files themselves acts as the library. Compiling Ada programs does
3676 not generate any centralized information, but rather an object file and
3677 a ALI file, which are of interest only to the binder and linker.
3678 In a traditional system, the compiler reads information not only from
3679 the source file being compiled, but also from the centralized library.
3680 This means that the effect of a compilation depends on what has been
3681 previously compiled. In particular:
3685 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3686 to the version of the unit most recently compiled into the library.
3689 Inlining is effective only if the necessary body has already been
3690 compiled into the library.
3693 Compiling a unit may obsolete other units in the library.
3697 In GNAT, compiling one unit never affects the compilation of any other
3698 units because the compiler reads only source files. Only changes to source
3699 files can affect the results of a compilation. In particular:
3703 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3704 to the source version of the unit that is currently accessible to the
3709 Inlining requires the appropriate source files for the package or
3710 subprogram bodies to be available to the compiler. Inlining is always
3711 effective, independent of the order in which units are complied.
3714 Compiling a unit never affects any other compilations. The editing of
3715 sources may cause previous compilations to be out of date if they
3716 depended on the source file being modified.
3720 The most important result of these differences is that order of compilation
3721 is never significant in GNAT. There is no situation in which one is
3722 required to do one compilation before another. What shows up as order of
3723 compilation requirements in the traditional Ada library becomes, in
3724 GNAT, simple source dependencies; in other words, there is only a set
3725 of rules saying what source files must be present when a file is
3729 @node Placement of temporary files
3730 @section Placement of temporary files
3731 @cindex Temporary files (user control over placement)
3734 GNAT creates temporary files in the directory designated by the environment
3735 variable @env{TMPDIR}.
3736 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3737 for detailed information on how environment variables are resolved.
3738 For most users the easiest way to make use of this feature is to simply
3739 define @env{TMPDIR} as a job level logical name).
3740 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3741 for compiler temporary files, then you can include something like the
3742 following command in your @file{LOGIN.COM} file:
3745 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3749 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3750 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3751 designated by @env{TEMP}.
3752 If none of these environment variables are defined then GNAT uses the
3753 directory designated by the logical name @code{SYS$SCRATCH:}
3754 (by default the user's home directory). If all else fails
3755 GNAT uses the current directory for temporary files.
3758 @c *************************
3759 @node Compiling Using gcc
3760 @chapter Compiling Using @command{gcc}
3763 This chapter discusses how to compile Ada programs using the @command{gcc}
3764 command. It also describes the set of switches
3765 that can be used to control the behavior of the compiler.
3767 * Compiling Programs::
3768 * Switches for gcc::
3769 * Search Paths and the Run-Time Library (RTL)::
3770 * Order of Compilation Issues::
3774 @node Compiling Programs
3775 @section Compiling Programs
3778 The first step in creating an executable program is to compile the units
3779 of the program using the @command{gcc} command. You must compile the
3784 the body file (@file{.adb}) for a library level subprogram or generic
3788 the spec file (@file{.ads}) for a library level package or generic
3789 package that has no body
3792 the body file (@file{.adb}) for a library level package
3793 or generic package that has a body
3798 You need @emph{not} compile the following files
3803 the spec of a library unit which has a body
3810 because they are compiled as part of compiling related units. GNAT
3812 when the corresponding body is compiled, and subunits when the parent is
3815 @cindex cannot generate code
3816 If you attempt to compile any of these files, you will get one of the
3817 following error messages (where @var{fff} is the name of the file you
3821 cannot generate code for file @var{fff} (package spec)
3822 to check package spec, use -gnatc
3824 cannot generate code for file @var{fff} (missing subunits)
3825 to check parent unit, use -gnatc
3827 cannot generate code for file @var{fff} (subprogram spec)
3828 to check subprogram spec, use -gnatc
3830 cannot generate code for file @var{fff} (subunit)
3831 to check subunit, use -gnatc
3835 As indicated by the above error messages, if you want to submit
3836 one of these files to the compiler to check for correct semantics
3837 without generating code, then use the @option{-gnatc} switch.
3839 The basic command for compiling a file containing an Ada unit is
3842 @c $ gcc -c @ovar{switches} @file{file name}
3843 @c Expanding @ovar macro inline (explanation in macro def comments)
3844 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3848 where @var{file name} is the name of the Ada file (usually
3850 @file{.ads} for a spec or @file{.adb} for a body).
3853 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3855 The result of a successful compilation is an object file, which has the
3856 same name as the source file but an extension of @file{.o} and an Ada
3857 Library Information (ALI) file, which also has the same name as the
3858 source file, but with @file{.ali} as the extension. GNAT creates these
3859 two output files in the current directory, but you may specify a source
3860 file in any directory using an absolute or relative path specification
3861 containing the directory information.
3864 @command{gcc} is actually a driver program that looks at the extensions of
3865 the file arguments and loads the appropriate compiler. For example, the
3866 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3867 These programs are in directories known to the driver program (in some
3868 configurations via environment variables you set), but need not be in
3869 your path. The @command{gcc} driver also calls the assembler and any other
3870 utilities needed to complete the generation of the required object
3873 It is possible to supply several file names on the same @command{gcc}
3874 command. This causes @command{gcc} to call the appropriate compiler for
3875 each file. For example, the following command lists three separate
3876 files to be compiled:
3879 $ gcc -c x.adb y.adb z.c
3883 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3884 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3885 The compiler generates three object files @file{x.o}, @file{y.o} and
3886 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3887 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3890 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3893 @node Switches for gcc
3894 @section Switches for @command{gcc}
3897 The @command{gcc} command accepts switches that control the
3898 compilation process. These switches are fully described in this section.
3899 First we briefly list all the switches, in alphabetical order, then we
3900 describe the switches in more detail in functionally grouped sections.
3902 More switches exist for GCC than those documented here, especially
3903 for specific targets. However, their use is not recommended as
3904 they may change code generation in ways that are incompatible with
3905 the Ada run-time library, or can cause inconsistencies between
3909 * Output and Error Message Control::
3910 * Warning Message Control::
3911 * Debugging and Assertion Control::
3912 * Validity Checking::
3915 * Using gcc for Syntax Checking::
3916 * Using gcc for Semantic Checking::
3917 * Compiling Different Versions of Ada::
3918 * Character Set Control::
3919 * File Naming Control::
3920 * Subprogram Inlining Control::
3921 * Auxiliary Output Control::
3922 * Debugging Control::
3923 * Exception Handling Control::
3924 * Units to Sources Mapping Files::
3925 * Integrated Preprocessing::
3926 * Code Generation Control::
3935 @cindex @option{-b} (@command{gcc})
3936 @item -b @var{target}
3937 Compile your program to run on @var{target}, which is the name of a
3938 system configuration. You must have a GNAT cross-compiler built if
3939 @var{target} is not the same as your host system.
3942 @cindex @option{-B} (@command{gcc})
3943 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3944 from @var{dir} instead of the default location. Only use this switch
3945 when multiple versions of the GNAT compiler are available.
3946 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3947 GNU Compiler Collection (GCC)}, for further details. You would normally
3948 use the @option{-b} or @option{-V} switch instead.
3951 @cindex @option{-c} (@command{gcc})
3952 Compile. Always use this switch when compiling Ada programs.
3954 Note: for some other languages when using @command{gcc}, notably in
3955 the case of C and C++, it is possible to use
3956 use @command{gcc} without a @option{-c} switch to
3957 compile and link in one step. In the case of GNAT, you
3958 cannot use this approach, because the binder must be run
3959 and @command{gcc} cannot be used to run the GNAT binder.
3963 @cindex @option{-fno-inline} (@command{gcc})
3964 Suppresses all inlining, even if other optimization or inlining
3965 switches are set. This includes suppression of inlining that
3966 results from the use of the pragma @code{Inline_Always}.
3967 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3968 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3969 effect if this switch is present.
3971 @item -fno-inline-functions
3972 @cindex @option{-fno-inline-functions} (@command{gcc})
3973 Suppresses automatic inlining of subprograms, which is enabled
3974 if @option{-O3} is used.
3976 @item -fno-inline-small-functions
3977 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3978 Suppresses automatic inlining of small subprograms, which is enabled
3979 if @option{-O2} is used.
3981 @item -fno-inline-functions-called-once
3982 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3983 Suppresses inlining of subprograms local to the unit and called once
3984 from within it, which is enabled if @option{-O1} is used.
3987 @cindex @option{-fno-ivopts} (@command{gcc})
3988 Suppresses high-level loop induction variable optimizations, which are
3989 enabled if @option{-O1} is used. These optimizations are generally
3990 profitable but, for some specific cases of loops with numerous uses
3991 of the iteration variable that follow a common pattern, they may end
3992 up destroying the regularity that could be exploited at a lower level
3993 and thus producing inferior code.
3995 @item -fno-strict-aliasing
3996 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3997 Causes the compiler to avoid assumptions regarding non-aliasing
3998 of objects of different types. See
3999 @ref{Optimization and Strict Aliasing} for details.
4002 @cindex @option{-fstack-check} (@command{gcc})
4003 Activates stack checking.
4004 See @ref{Stack Overflow Checking} for details.
4007 @cindex @option{-fstack-usage} (@command{gcc})
4008 Makes the compiler output stack usage information for the program, on a
4009 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4011 @item -fcallgraph-info@r{[}=su@r{]}
4012 @cindex @option{-fcallgraph-info} (@command{gcc})
4013 Makes the compiler output callgraph information for the program, on a
4014 per-file basis. The information is generated in the VCG format. It can
4015 be decorated with stack-usage per-node information.
4018 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4019 Generate debugging information. This information is stored in the object
4020 file and copied from there to the final executable file by the linker,
4021 where it can be read by the debugger. You must use the
4022 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4025 @cindex @option{-gnat83} (@command{gcc})
4026 Enforce Ada 83 restrictions.
4029 @cindex @option{-gnat95} (@command{gcc})
4030 Enforce Ada 95 restrictions.
4033 @cindex @option{-gnat05} (@command{gcc})
4034 Allow full Ada 2005 features.
4037 @cindex @option{-gnat2005} (@command{gcc})
4038 Allow full Ada 2005 features (same as @option{-gnat05})
4041 @cindex @option{-gnat12} (@command{gcc})
4044 @cindex @option{-gnat2012} (@command{gcc})
4045 Allow full Ada 2012 features (same as @option{-gnat12})
4048 @cindex @option{-gnata} (@command{gcc})
4049 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4050 activated. Note that these pragmas can also be controlled using the
4051 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4052 It also activates pragmas @code{Check}, @code{Precondition}, and
4053 @code{Postcondition}. Note that these pragmas can also be controlled
4054 using the configuration pragma @code{Check_Policy}.
4057 @cindex @option{-gnatA} (@command{gcc})
4058 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4062 @cindex @option{-gnatb} (@command{gcc})
4063 Generate brief messages to @file{stderr} even if verbose mode set.
4066 @cindex @option{-gnatB} (@command{gcc})
4067 Assume no invalid (bad) values except for 'Valid attribute use
4068 (@pxref{Validity Checking}).
4071 @cindex @option{-gnatc} (@command{gcc})
4072 Check syntax and semantics only (no code generation attempted).
4075 @cindex @option{-gnatC} (@command{gcc})
4076 Generate CodePeer information (no code generation attempted).
4077 This switch will generate an intermediate representation suitable for
4078 use by CodePeer (@file{.scil} files). This switch is not compatible with
4079 code generation (it will, among other things, disable some switches such
4080 as -gnatn, and enable others such as -gnata).
4083 @cindex @option{-gnatd} (@command{gcc})
4084 Specify debug options for the compiler. The string of characters after
4085 the @option{-gnatd} specify the specific debug options. The possible
4086 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4087 compiler source file @file{debug.adb} for details of the implemented
4088 debug options. Certain debug options are relevant to applications
4089 programmers, and these are documented at appropriate points in this
4094 @cindex @option{-gnatD[nn]} (@command{gcc})
4097 @item /XDEBUG /LXDEBUG=nnn
4099 Create expanded source files for source level debugging. This switch
4100 also suppress generation of cross-reference information
4101 (see @option{-gnatx}).
4103 @item -gnatec=@var{path}
4104 @cindex @option{-gnatec} (@command{gcc})
4105 Specify a configuration pragma file
4107 (the equal sign is optional)
4109 (@pxref{The Configuration Pragmas Files}).
4111 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4112 @cindex @option{-gnateD} (@command{gcc})
4113 Defines a symbol, associated with @var{value}, for preprocessing.
4114 (@pxref{Integrated Preprocessing}).
4117 @cindex @option{-gnateE} (@command{gcc})
4118 Generate extra information in exception messages. In particular, display
4119 extra column information and the value and range associated with index and
4120 range check failures, and extra column information for access checks.
4121 In cases where the compiler is able to determine at compile time that
4122 a check will fail, it gives a warning, and the extra information is not
4123 produced at run time.
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.
4134 @cindex @option{-gnateI} (@command{gcc})
4135 Indicates that the source is a multi-unit source and that the index of the
4136 unit to compile is nnn. nnn needs to be a positive number and need to
4137 be a valid index in the multi-unit source.
4139 @item -gnatem=@var{path}
4140 @cindex @option{-gnatem} (@command{gcc})
4141 Specify a mapping file
4143 (the equal sign is optional)
4145 (@pxref{Units to Sources Mapping Files}).
4147 @item -gnatep=@var{file}
4148 @cindex @option{-gnatep} (@command{gcc})
4149 Specify a preprocessing data file
4151 (the equal sign is optional)
4153 (@pxref{Integrated Preprocessing}).
4156 @cindex @option{-gnateP} (@command{gcc})
4157 Turn categorization dependency errors into warnings.
4158 Ada requires that units that WITH one another have compatible categories, for
4159 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4160 these errors become warnings (which can be ignored, or suppressed in the usual
4161 manner). This can be useful in some specialized circumstances such as the
4162 temporary use of special test software.
4164 @cindex @option{-gnateS} (@command{gcc})
4165 Generate SCO (Source Coverage Obligation) information in the ALI
4166 file. This information is used by advanced coverage tools. See
4167 unit @file{SCOs} in the compiler sources for details in files
4168 @file{scos.ads} and @file{scos.adb}.
4171 @cindex @option{-gnatE} (@command{gcc})
4172 Full dynamic elaboration checks.
4175 @cindex @option{-gnatf} (@command{gcc})
4176 Full errors. Multiple errors per line, all undefined references, do not
4177 attempt to suppress cascaded errors.
4180 @cindex @option{-gnatF} (@command{gcc})
4181 Externals names are folded to all uppercase.
4183 @item ^-gnatg^/GNAT_INTERNAL^
4184 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4185 Internal GNAT implementation mode. This should not be used for
4186 applications programs, it is intended only for use by the compiler
4187 and its run-time library. For documentation, see the GNAT sources.
4188 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4189 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4190 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4191 so that all standard warnings and all standard style options are turned on.
4192 All warnings and style messages are treated as errors.
4196 @cindex @option{-gnatG[nn]} (@command{gcc})
4199 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4201 List generated expanded code in source form.
4203 @item ^-gnath^/HELP^
4204 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4205 Output usage information. The output is written to @file{stdout}.
4207 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4208 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4209 Identifier character set
4211 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4213 For details of the possible selections for @var{c},
4214 see @ref{Character Set Control}.
4216 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4217 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4218 Ignore representation clauses. When this switch is used,
4219 representation clauses are treated as comments. This is useful
4220 when initially porting code where you want to ignore rep clause
4221 problems, and also for compiling foreign code (particularly
4222 for use with ASIS). The representation clauses that are ignored
4223 are: enumeration_representation_clause, record_representation_clause,
4224 and attribute_definition_clause for the following attributes:
4225 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4226 Object_Size, Size, Small, Stream_Size, and Value_Size.
4227 Note that this option should be used only for compiling -- the
4228 code is likely to malfunction at run time.
4231 @cindex @option{-gnatjnn} (@command{gcc})
4232 Reformat error messages to fit on nn character lines
4234 @item -gnatk=@var{n}
4235 @cindex @option{-gnatk} (@command{gcc})
4236 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4239 @cindex @option{-gnatl} (@command{gcc})
4240 Output full source listing with embedded error messages.
4243 @cindex @option{-gnatL} (@command{gcc})
4244 Used in conjunction with -gnatG or -gnatD to intersperse original
4245 source lines (as comment lines with line numbers) in the expanded
4248 @item -gnatm=@var{n}
4249 @cindex @option{-gnatm} (@command{gcc})
4250 Limit number of detected error or warning messages to @var{n}
4251 where @var{n} is in the range 1..999999. The default setting if
4252 no switch is given is 9999. If the number of warnings reaches this
4253 limit, then a message is output and further warnings are suppressed,
4254 but the compilation is continued. If the number of error messages
4255 reaches this limit, then a message is output and the compilation
4256 is abandoned. The equal sign here is optional. A value of zero
4257 means that no limit applies.
4260 @cindex @option{-gnatn} (@command{gcc})
4261 Activate inlining for subprograms for which
4262 pragma @code{Inline} is specified. This inlining is performed
4263 by the GCC back-end.
4266 @cindex @option{-gnatN} (@command{gcc})
4267 Activate front end inlining for subprograms for which
4268 pragma @code{Inline} is specified. This inlining is performed
4269 by the front end and will be visible in the
4270 @option{-gnatG} output.
4272 When using a gcc-based back end (in practice this means using any version
4273 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4274 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4275 Historically front end inlining was more extensive than the gcc back end
4276 inlining, but that is no longer the case.
4279 @cindex @option{-gnato} (@command{gcc})
4280 Enable numeric overflow checking (which is not normally enabled by
4281 default). Note that division by zero is a separate check that is not
4282 controlled by this switch (division by zero checking is on by default).
4285 @cindex @option{-gnatp} (@command{gcc})
4286 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4287 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4290 @cindex @option{-gnat-p} (@command{gcc})
4291 Cancel effect of previous @option{-gnatp} switch.
4294 @cindex @option{-gnatP} (@command{gcc})
4295 Enable polling. This is required on some systems (notably Windows NT) to
4296 obtain asynchronous abort and asynchronous transfer of control capability.
4297 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4301 @cindex @option{-gnatq} (@command{gcc})
4302 Don't quit. Try semantics, even if parse errors.
4305 @cindex @option{-gnatQ} (@command{gcc})
4306 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4309 @cindex @option{-gnatr} (@command{gcc})
4310 Treat pragma Restrictions as Restriction_Warnings.
4312 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4313 @cindex @option{-gnatR} (@command{gcc})
4314 Output representation information for declared types and objects.
4317 @cindex @option{-gnats} (@command{gcc})
4321 @cindex @option{-gnatS} (@command{gcc})
4322 Print package Standard.
4325 @cindex @option{-gnatt} (@command{gcc})
4326 Generate tree output file.
4328 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4329 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4330 All compiler tables start at @var{nnn} times usual starting size.
4333 @cindex @option{-gnatu} (@command{gcc})
4334 List units for this compilation.
4337 @cindex @option{-gnatU} (@command{gcc})
4338 Tag all error messages with the unique string ``error:''
4341 @cindex @option{-gnatv} (@command{gcc})
4342 Verbose mode. Full error output with source lines to @file{stdout}.
4345 @cindex @option{-gnatV} (@command{gcc})
4346 Control level of validity checking (@pxref{Validity Checking}).
4348 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4349 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4351 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4352 the exact warnings that
4353 are enabled or disabled (@pxref{Warning Message Control}).
4355 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4356 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4357 Wide character encoding method
4359 (@var{e}=n/h/u/s/e/8).
4362 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4366 @cindex @option{-gnatx} (@command{gcc})
4367 Suppress generation of cross-reference information.
4370 @cindex @option{-gnatX} (@command{gcc})
4371 Enable GNAT implementation extensions and latest Ada version.
4373 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4374 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4375 Enable built-in style checks (@pxref{Style Checking}).
4377 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4378 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4379 Distribution stub generation and compilation
4381 (@var{m}=r/c for receiver/caller stubs).
4384 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4385 to be generated and compiled).
4388 @item ^-I^/SEARCH=^@var{dir}
4389 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4391 Direct GNAT to search the @var{dir} directory for source files needed by
4392 the current compilation
4393 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4395 @item ^-I-^/NOCURRENT_DIRECTORY^
4396 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4398 Except for the source file named in the command line, do not look for source
4399 files in the directory containing the source file named in the command line
4400 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4404 @cindex @option{-mbig-switch} (@command{gcc})
4405 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4406 This standard gcc switch causes the compiler to use larger offsets in its
4407 jump table representation for @code{case} statements.
4408 This may result in less efficient code, but is sometimes necessary
4409 (for example on HP-UX targets)
4410 @cindex HP-UX and @option{-mbig-switch} option
4411 in order to compile large and/or nested @code{case} statements.
4414 @cindex @option{-o} (@command{gcc})
4415 This switch is used in @command{gcc} to redirect the generated object file
4416 and its associated ALI file. Beware of this switch with GNAT, because it may
4417 cause the object file and ALI file to have different names which in turn
4418 may confuse the binder and the linker.
4422 @cindex @option{-nostdinc} (@command{gcc})
4423 Inhibit the search of the default location for the GNAT Run Time
4424 Library (RTL) source files.
4427 @cindex @option{-nostdlib} (@command{gcc})
4428 Inhibit the search of the default location for the GNAT Run Time
4429 Library (RTL) ALI files.
4433 @c Expanding @ovar macro inline (explanation in macro def comments)
4434 @item -O@r{[}@var{n}@r{]}
4435 @cindex @option{-O} (@command{gcc})
4436 @var{n} controls the optimization level.
4440 No optimization, the default setting if no @option{-O} appears
4443 Normal optimization, the default if you specify @option{-O} without
4444 an operand. A good compromise between code quality and compilation
4448 Extensive optimization, may improve execution time, possibly at the cost of
4449 substantially increased compilation time.
4452 Same as @option{-O2}, and also includes inline expansion for small subprograms
4456 Optimize space usage
4460 See also @ref{Optimization Levels}.
4465 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4466 Equivalent to @option{/OPTIMIZE=NONE}.
4467 This is the default behavior in the absence of an @option{/OPTIMIZE}
4470 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4471 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4472 Selects the level of optimization for your program. The supported
4473 keywords are as follows:
4476 Perform most optimizations, including those that
4478 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4479 without keyword options.
4482 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4485 Perform some optimizations, but omit ones that are costly.
4488 Same as @code{SOME}.
4491 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4492 automatic inlining of small subprograms within a unit
4495 Try to unroll loops. This keyword may be specified together with
4496 any keyword above other than @code{NONE}. Loop unrolling
4497 usually, but not always, improves the performance of programs.
4500 Optimize space usage
4504 See also @ref{Optimization Levels}.
4508 @item -pass-exit-codes
4509 @cindex @option{-pass-exit-codes} (@command{gcc})
4510 Catch exit codes from the compiler and use the most meaningful as
4514 @item --RTS=@var{rts-path}
4515 @cindex @option{--RTS} (@command{gcc})
4516 Specifies the default location of the runtime library. Same meaning as the
4517 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4520 @cindex @option{^-S^/ASM^} (@command{gcc})
4521 ^Used in place of @option{-c} to^Used to^
4522 cause the assembler source file to be
4523 generated, using @file{^.s^.S^} as the extension,
4524 instead of the object file.
4525 This may be useful if you need to examine the generated assembly code.
4527 @item ^-fverbose-asm^/VERBOSE_ASM^
4528 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4529 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4530 to cause the generated assembly code file to be annotated with variable
4531 names, making it significantly easier to follow.
4534 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4535 Show commands generated by the @command{gcc} driver. Normally used only for
4536 debugging purposes or if you need to be sure what version of the
4537 compiler you are executing.
4541 @cindex @option{-V} (@command{gcc})
4542 Execute @var{ver} version of the compiler. This is the @command{gcc}
4543 version, not the GNAT version.
4546 @item ^-w^/NO_BACK_END_WARNINGS^
4547 @cindex @option{-w} (@command{gcc})
4548 Turn off warnings generated by the back end of the compiler. Use of
4549 this switch also causes the default for front end warnings to be set
4550 to suppress (as though @option{-gnatws} had appeared at the start of
4556 @c Combining qualifiers does not work on VMS
4557 You may combine a sequence of GNAT switches into a single switch. For
4558 example, the combined switch
4560 @cindex Combining GNAT switches
4566 is equivalent to specifying the following sequence of switches:
4569 -gnato -gnatf -gnati3
4574 The following restrictions apply to the combination of switches
4579 The switch @option{-gnatc} if combined with other switches must come
4580 first in the string.
4583 The switch @option{-gnats} if combined with other switches must come
4584 first in the string.
4588 ^^@option{/DISTRIBUTION_STUBS=},^
4589 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4590 switches, and only one of them may appear in the command line.
4593 The switch @option{-gnat-p} may not be combined with any other switch.
4597 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4598 switch), then all further characters in the switch are interpreted
4599 as style modifiers (see description of @option{-gnaty}).
4602 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4603 switch), then all further characters in the switch are interpreted
4604 as debug flags (see description of @option{-gnatd}).
4607 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4608 switch), then all further characters in the switch are interpreted
4609 as warning mode modifiers (see description of @option{-gnatw}).
4612 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4613 switch), then all further characters in the switch are interpreted
4614 as validity checking options (@pxref{Validity Checking}).
4617 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4618 a combined list of options.
4622 @node Output and Error Message Control
4623 @subsection Output and Error Message Control
4627 The standard default format for error messages is called ``brief format''.
4628 Brief format messages are written to @file{stderr} (the standard error
4629 file) and have the following form:
4632 e.adb:3:04: Incorrect spelling of keyword "function"
4633 e.adb:4:20: ";" should be "is"
4637 The first integer after the file name is the line number in the file,
4638 and the second integer is the column number within the line.
4640 @code{GPS} can parse the error messages
4641 and point to the referenced character.
4643 The following switches provide control over the error message
4649 @cindex @option{-gnatv} (@command{gcc})
4652 The v stands for verbose.
4654 The effect of this setting is to write long-format error
4655 messages to @file{stdout} (the standard output file.
4656 The same program compiled with the
4657 @option{-gnatv} switch would generate:
4661 3. funcion X (Q : Integer)
4663 >>> Incorrect spelling of keyword "function"
4666 >>> ";" should be "is"
4671 The vertical bar indicates the location of the error, and the @samp{>>>}
4672 prefix can be used to search for error messages. When this switch is
4673 used the only source lines output are those with errors.
4676 @cindex @option{-gnatl} (@command{gcc})
4678 The @code{l} stands for list.
4680 This switch causes a full listing of
4681 the file to be generated. In the case where a body is
4682 compiled, the corresponding spec is also listed, along
4683 with any subunits. Typical output from compiling a package
4684 body @file{p.adb} might look like:
4686 @smallexample @c ada
4690 1. package body p is
4692 3. procedure a is separate;
4703 2. pragma Elaborate_Body
4727 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4728 standard output is redirected, a brief summary is written to
4729 @file{stderr} (standard error) giving the number of error messages and
4730 warning messages generated.
4732 @item ^-gnatl^/OUTPUT_FILE^=file
4733 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4734 This has the same effect as @option{-gnatl} except that the output is
4735 written to a file instead of to standard output. If the given name
4736 @file{fname} does not start with a period, then it is the full name
4737 of the file to be written. If @file{fname} is an extension, it is
4738 appended to the name of the file being compiled. For example, if
4739 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4740 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4743 @cindex @option{-gnatU} (@command{gcc})
4744 This switch forces all error messages to be preceded by the unique
4745 string ``error:''. This means that error messages take a few more
4746 characters in space, but allows easy searching for and identification
4750 @cindex @option{-gnatb} (@command{gcc})
4752 The @code{b} stands for brief.
4754 This switch causes GNAT to generate the
4755 brief format error messages to @file{stderr} (the standard error
4756 file) as well as the verbose
4757 format message or full listing (which as usual is written to
4758 @file{stdout} (the standard output file).
4760 @item -gnatm=@var{n}
4761 @cindex @option{-gnatm} (@command{gcc})
4763 The @code{m} stands for maximum.
4765 @var{n} is a decimal integer in the
4766 range of 1 to 999999 and limits the number of error or warning
4767 messages to be generated. For example, using
4768 @option{-gnatm2} might yield
4771 e.adb:3:04: Incorrect spelling of keyword "function"
4772 e.adb:5:35: missing ".."
4773 fatal error: maximum number of errors detected
4774 compilation abandoned
4778 The default setting if
4779 no switch is given is 9999. If the number of warnings reaches this
4780 limit, then a message is output and further warnings are suppressed,
4781 but the compilation is continued. If the number of error messages
4782 reaches this limit, then a message is output and the compilation
4783 is abandoned. A value of zero means that no limit applies.
4786 Note that the equal sign is optional, so the switches
4787 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4790 @cindex @option{-gnatf} (@command{gcc})
4791 @cindex Error messages, suppressing
4793 The @code{f} stands for full.
4795 Normally, the compiler suppresses error messages that are likely to be
4796 redundant. This switch causes all error
4797 messages to be generated. In particular, in the case of
4798 references to undefined variables. If a given variable is referenced
4799 several times, the normal format of messages is
4801 e.adb:7:07: "V" is undefined (more references follow)
4805 where the parenthetical comment warns that there are additional
4806 references to the variable @code{V}. Compiling the same program with the
4807 @option{-gnatf} switch yields
4810 e.adb:7:07: "V" is undefined
4811 e.adb:8:07: "V" is undefined
4812 e.adb:8:12: "V" is undefined
4813 e.adb:8:16: "V" is undefined
4814 e.adb:9:07: "V" is undefined
4815 e.adb:9:12: "V" is undefined
4819 The @option{-gnatf} switch also generates additional information for
4820 some error messages. Some examples are:
4824 Details on possibly non-portable unchecked conversion
4826 List possible interpretations for ambiguous calls
4828 Additional details on incorrect parameters
4832 @cindex @option{-gnatjnn} (@command{gcc})
4833 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4834 with continuation lines are treated as though the continuation lines were
4835 separate messages (and so a warning with two continuation lines counts as
4836 three warnings, and is listed as three separate messages).
4838 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4839 messages are output in a different manner. A message and all its continuation
4840 lines are treated as a unit, and count as only one warning or message in the
4841 statistics totals. Furthermore, the message is reformatted so that no line
4842 is longer than nn characters.
4845 @cindex @option{-gnatq} (@command{gcc})
4847 The @code{q} stands for quit (really ``don't quit'').
4849 In normal operation mode, the compiler first parses the program and
4850 determines if there are any syntax errors. If there are, appropriate
4851 error messages are generated and compilation is immediately terminated.
4853 GNAT to continue with semantic analysis even if syntax errors have been
4854 found. This may enable the detection of more errors in a single run. On
4855 the other hand, the semantic analyzer is more likely to encounter some
4856 internal fatal error when given a syntactically invalid tree.
4859 @cindex @option{-gnatQ} (@command{gcc})
4860 In normal operation mode, the @file{ALI} file is not generated if any
4861 illegalities are detected in the program. The use of @option{-gnatQ} forces
4862 generation of the @file{ALI} file. This file is marked as being in
4863 error, so it cannot be used for binding purposes, but it does contain
4864 reasonably complete cross-reference information, and thus may be useful
4865 for use by tools (e.g., semantic browsing tools or integrated development
4866 environments) that are driven from the @file{ALI} file. This switch
4867 implies @option{-gnatq}, since the semantic phase must be run to get a
4868 meaningful ALI file.
4870 In addition, if @option{-gnatt} is also specified, then the tree file is
4871 generated even if there are illegalities. It may be useful in this case
4872 to also specify @option{-gnatq} to ensure that full semantic processing
4873 occurs. The resulting tree file can be processed by ASIS, for the purpose
4874 of providing partial information about illegal units, but if the error
4875 causes the tree to be badly malformed, then ASIS may crash during the
4878 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4879 being in error, @command{gnatmake} will attempt to recompile the source when it
4880 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4882 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4883 since ALI files are never generated if @option{-gnats} is set.
4887 @node Warning Message Control
4888 @subsection Warning Message Control
4889 @cindex Warning messages
4891 In addition to error messages, which correspond to illegalities as defined
4892 in the Ada Reference Manual, the compiler detects two kinds of warning
4895 First, the compiler considers some constructs suspicious and generates a
4896 warning message to alert you to a possible error. Second, if the
4897 compiler detects a situation that is sure to raise an exception at
4898 run time, it generates a warning message. The following shows an example
4899 of warning messages:
4901 e.adb:4:24: warning: creation of object may raise Storage_Error
4902 e.adb:10:17: warning: static value out of range
4903 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4907 GNAT considers a large number of situations as appropriate
4908 for the generation of warning messages. As always, warnings are not
4909 definite indications of errors. For example, if you do an out-of-range
4910 assignment with the deliberate intention of raising a
4911 @code{Constraint_Error} exception, then the warning that may be
4912 issued does not indicate an error. Some of the situations for which GNAT
4913 issues warnings (at least some of the time) are given in the following
4914 list. This list is not complete, and new warnings are often added to
4915 subsequent versions of GNAT. The list is intended to give a general idea
4916 of the kinds of warnings that are generated.
4920 Possible infinitely recursive calls
4923 Out-of-range values being assigned
4926 Possible order of elaboration problems
4929 Assertions (pragma Assert) that are sure to fail
4935 Address clauses with possibly unaligned values, or where an attempt is
4936 made to overlay a smaller variable with a larger one.
4939 Fixed-point type declarations with a null range
4942 Direct_IO or Sequential_IO instantiated with a type that has access values
4945 Variables that are never assigned a value
4948 Variables that are referenced before being initialized
4951 Task entries with no corresponding @code{accept} statement
4954 Duplicate accepts for the same task entry in a @code{select}
4957 Objects that take too much storage
4960 Unchecked conversion between types of differing sizes
4963 Missing @code{return} statement along some execution path in a function
4966 Incorrect (unrecognized) pragmas
4969 Incorrect external names
4972 Allocation from empty storage pool
4975 Potentially blocking operation in protected type
4978 Suspicious parenthesization of expressions
4981 Mismatching bounds in an aggregate
4984 Attempt to return local value by reference
4987 Premature instantiation of a generic body
4990 Attempt to pack aliased components
4993 Out of bounds array subscripts
4996 Wrong length on string assignment
4999 Violations of style rules if style checking is enabled
5002 Unused @code{with} clauses
5005 @code{Bit_Order} usage that does not have any effect
5008 @code{Standard.Duration} used to resolve universal fixed expression
5011 Dereference of possibly null value
5014 Declaration that is likely to cause storage error
5017 Internal GNAT unit @code{with}'ed by application unit
5020 Values known to be out of range at compile time
5023 Unreferenced labels and variables
5026 Address overlays that could clobber memory
5029 Unexpected initialization when address clause present
5032 Bad alignment for address clause
5035 Useless type conversions
5038 Redundant assignment statements and other redundant constructs
5041 Useless exception handlers
5044 Accidental hiding of name by child unit
5047 Access before elaboration detected at compile time
5050 A range in a @code{for} loop that is known to be null or might be null
5055 The following section lists compiler switches that are available
5056 to control the handling of warning messages. It is also possible
5057 to exercise much finer control over what warnings are issued and
5058 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5059 gnat_rm, GNAT Reference manual}.
5064 @emph{Activate most optional warnings.}
5065 @cindex @option{-gnatwa} (@command{gcc})
5066 This switch activates most optional warning messages. See the remaining list
5067 in this section for details on optional warning messages that can be
5068 individually controlled. The warnings that are not turned on by this
5070 @option{-gnatwd} (implicit dereferencing),
5071 @option{-gnatwh} (hiding),
5072 @option{-gnatw.h} (holes (gaps) in record layouts)
5073 @option{-gnatwl} (elaboration warnings),
5074 @option{-gnatw.o} (warn on values set by out parameters ignored)
5075 and @option{-gnatwt} (tracking of deleted conditional code).
5076 All other optional warnings are turned on.
5079 @emph{Suppress all optional errors.}
5080 @cindex @option{-gnatwA} (@command{gcc})
5081 This switch suppresses all optional warning messages, see remaining list
5082 in this section for details on optional warning messages that can be
5083 individually controlled.
5086 @emph{Activate warnings on failing assertions.}
5087 @cindex @option{-gnatw.a} (@command{gcc})
5088 @cindex Assert failures
5089 This switch activates warnings for assertions where the compiler can tell at
5090 compile time that the assertion will fail. Note that this warning is given
5091 even if assertions are disabled. The default is that such warnings are
5095 @emph{Suppress warnings on failing assertions.}
5096 @cindex @option{-gnatw.A} (@command{gcc})
5097 @cindex Assert failures
5098 This switch suppresses warnings for assertions where the compiler can tell at
5099 compile time that the assertion will fail.
5102 @emph{Activate warnings on bad fixed values.}
5103 @cindex @option{-gnatwb} (@command{gcc})
5104 @cindex Bad fixed values
5105 @cindex Fixed-point Small value
5107 This switch activates warnings for static fixed-point expressions whose
5108 value is not an exact multiple of Small. Such values are implementation
5109 dependent, since an implementation is free to choose either of the multiples
5110 that surround the value. GNAT always chooses the closer one, but this is not
5111 required behavior, and it is better to specify a value that is an exact
5112 multiple, ensuring predictable execution. The default is that such warnings
5116 @emph{Suppress warnings on bad fixed values.}
5117 @cindex @option{-gnatwB} (@command{gcc})
5118 This switch suppresses warnings for static fixed-point expressions whose
5119 value is not an exact multiple of Small.
5122 @emph{Activate warnings on biased representation.}
5123 @cindex @option{-gnatw.b} (@command{gcc})
5124 @cindex Biased representation
5125 This switch activates warnings when a size clause, value size clause, component
5126 clause, or component size clause forces the use of biased representation for an
5127 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5128 to represent 10/11). The default is that such warnings are generated.
5131 @emph{Suppress warnings on biased representation.}
5132 @cindex @option{-gnatwB} (@command{gcc})
5133 This switch suppresses warnings for representation clauses that force the use
5134 of biased representation.
5137 @emph{Activate warnings on conditionals.}
5138 @cindex @option{-gnatwc} (@command{gcc})
5139 @cindex Conditionals, constant
5140 This switch activates warnings for conditional expressions used in
5141 tests that are known to be True or False at compile time. The default
5142 is that such warnings are not generated.
5143 Note that this warning does
5144 not get issued for the use of boolean variables or constants whose
5145 values are known at compile time, since this is a standard technique
5146 for conditional compilation in Ada, and this would generate too many
5147 false positive warnings.
5149 This warning option also activates a special test for comparisons using
5150 the operators ``>='' and`` <=''.
5151 If the compiler can tell that only the equality condition is possible,
5152 then it will warn that the ``>'' or ``<'' part of the test
5153 is useless and that the operator could be replaced by ``=''.
5154 An example would be comparing a @code{Natural} variable <= 0.
5156 This warning option also generates warnings if
5157 one or both tests is optimized away in a membership test for integer
5158 values if the result can be determined at compile time. Range tests on
5159 enumeration types are not included, since it is common for such tests
5160 to include an end point.
5162 This warning can also be turned on using @option{-gnatwa}.
5165 @emph{Suppress warnings on conditionals.}
5166 @cindex @option{-gnatwC} (@command{gcc})
5167 This switch suppresses warnings for conditional expressions used in
5168 tests that are known to be True or False at compile time.
5171 @emph{Activate warnings on missing component clauses.}
5172 @cindex @option{-gnatw.c} (@command{gcc})
5173 @cindex Component clause, missing
5174 This switch activates warnings for record components where a record
5175 representation clause is present and has component clauses for the
5176 majority, but not all, of the components. A warning is given for each
5177 component for which no component clause is present.
5179 This warning can also be turned on using @option{-gnatwa}.
5182 @emph{Suppress warnings on missing component clauses.}
5183 @cindex @option{-gnatwC} (@command{gcc})
5184 This switch suppresses warnings for record components that are
5185 missing a component clause in the situation described above.
5188 @emph{Activate warnings on implicit dereferencing.}
5189 @cindex @option{-gnatwd} (@command{gcc})
5190 If this switch is set, then the use of a prefix of an access type
5191 in an indexed component, slice, or selected component without an
5192 explicit @code{.all} will generate a warning. With this warning
5193 enabled, access checks occur only at points where an explicit
5194 @code{.all} appears in the source code (assuming no warnings are
5195 generated as a result of this switch). The default is that such
5196 warnings are not generated.
5197 Note that @option{-gnatwa} does not affect the setting of
5198 this warning option.
5201 @emph{Suppress warnings on implicit dereferencing.}
5202 @cindex @option{-gnatwD} (@command{gcc})
5203 @cindex Implicit dereferencing
5204 @cindex Dereferencing, implicit
5205 This switch suppresses warnings for implicit dereferences in
5206 indexed components, slices, and selected components.
5209 @emph{Treat warnings and style checks as errors.}
5210 @cindex @option{-gnatwe} (@command{gcc})
5211 @cindex Warnings, treat as error
5212 This switch causes warning messages and style check messages to be
5214 The warning string still appears, but the warning messages are counted
5215 as errors, and prevent the generation of an object file. Note that this
5216 is the only -gnatw switch that affects the handling of style check messages.
5219 @emph{Activate every optional warning}
5220 @cindex @option{-gnatw.e} (@command{gcc})
5221 @cindex Warnings, activate every optional warning
5222 This switch activates all optional warnings, including those which
5223 are not activated by @code{-gnatwa}.
5226 @emph{Activate warnings on unreferenced formals.}
5227 @cindex @option{-gnatwf} (@command{gcc})
5228 @cindex Formals, unreferenced
5229 This switch causes a warning to be generated if a formal parameter
5230 is not referenced in the body of the subprogram. This warning can
5231 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5232 default is that these warnings are not generated.
5235 @emph{Suppress warnings on unreferenced formals.}
5236 @cindex @option{-gnatwF} (@command{gcc})
5237 This switch suppresses warnings for unreferenced formal
5238 parameters. Note that the
5239 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5240 effect of warning on unreferenced entities other than subprogram
5244 @emph{Activate warnings on unrecognized pragmas.}
5245 @cindex @option{-gnatwg} (@command{gcc})
5246 @cindex Pragmas, unrecognized
5247 This switch causes a warning to be generated if an unrecognized
5248 pragma is encountered. Apart from issuing this warning, the
5249 pragma is ignored and has no effect. This warning can
5250 also be turned on using @option{-gnatwa}. The default
5251 is that such warnings are issued (satisfying the Ada Reference
5252 Manual requirement that such warnings appear).
5255 @emph{Suppress warnings on unrecognized pragmas.}
5256 @cindex @option{-gnatwG} (@command{gcc})
5257 This switch suppresses warnings for unrecognized pragmas.
5260 @emph{Activate warnings on hiding.}
5261 @cindex @option{-gnatwh} (@command{gcc})
5262 @cindex Hiding of Declarations
5263 This switch activates warnings on hiding declarations.
5264 A declaration is considered hiding
5265 if it is for a non-overloadable entity, and it declares an entity with the
5266 same name as some other entity that is directly or use-visible. The default
5267 is that such warnings are not generated.
5268 Note that @option{-gnatwa} does not affect the setting of this warning option.
5271 @emph{Suppress warnings on hiding.}
5272 @cindex @option{-gnatwH} (@command{gcc})
5273 This switch suppresses warnings on hiding declarations.
5276 @emph{Activate warnings on holes/gaps in records.}
5277 @cindex @option{-gnatw.h} (@command{gcc})
5278 @cindex Record Representation (gaps)
5279 This switch activates warnings on component clauses in record
5280 representation clauses that leave holes (gaps) in the record layout.
5281 If this warning option is active, then record representation clauses
5282 should specify a contiguous layout, adding unused fill fields if needed.
5283 Note that @option{-gnatwa} does not affect the setting of this warning option.
5286 @emph{Suppress warnings on holes/gaps in records.}
5287 @cindex @option{-gnatw.H} (@command{gcc})
5288 This switch suppresses warnings on component clauses in record
5289 representation clauses that leave holes (haps) in the record layout.
5292 @emph{Activate warnings on implementation units.}
5293 @cindex @option{-gnatwi} (@command{gcc})
5294 This switch activates warnings for a @code{with} of an internal GNAT
5295 implementation unit, defined as any unit from the @code{Ada},
5296 @code{Interfaces}, @code{GNAT},
5297 ^^@code{DEC},^ or @code{System}
5298 hierarchies that is not
5299 documented in either the Ada Reference Manual or the GNAT
5300 Programmer's Reference Manual. Such units are intended only
5301 for internal implementation purposes and should not be @code{with}'ed
5302 by user programs. The default is that such warnings are generated
5303 This warning can also be turned on using @option{-gnatwa}.
5306 @emph{Disable warnings on implementation units.}
5307 @cindex @option{-gnatwI} (@command{gcc})
5308 This switch disables warnings for a @code{with} of an internal GNAT
5309 implementation unit.
5312 @emph{Activate warnings on overlapping actuals.}
5313 @cindex @option{-gnatw.i} (@command{gcc})
5314 This switch enables a warning on statically detectable overlapping actuals in
5315 a subprogram call, when one of the actuals is an in-out parameter, and the
5316 types of the actuals are not by-copy types. The warning is off by default,
5317 and is not included under -gnatwa.
5320 @emph{Disable warnings on overlapping actuals.}
5321 @cindex @option{-gnatw.I} (@command{gcc})
5322 This switch disables warnings on overlapping actuals in a call..
5325 @emph{Activate warnings on obsolescent features (Annex J).}
5326 @cindex @option{-gnatwj} (@command{gcc})
5327 @cindex Features, obsolescent
5328 @cindex Obsolescent features
5329 If this warning option is activated, then warnings are generated for
5330 calls to subprograms marked with @code{pragma Obsolescent} and
5331 for use of features in Annex J of the Ada Reference Manual. In the
5332 case of Annex J, not all features are flagged. In particular use
5333 of the renamed packages (like @code{Text_IO}) and use of package
5334 @code{ASCII} are not flagged, since these are very common and
5335 would generate many annoying positive warnings. The default is that
5336 such warnings are not generated. This warning is also turned on by
5337 the use of @option{-gnatwa}.
5339 In addition to the above cases, warnings are also generated for
5340 GNAT features that have been provided in past versions but which
5341 have been superseded (typically by features in the new Ada standard).
5342 For example, @code{pragma Ravenscar} will be flagged since its
5343 function is replaced by @code{pragma Profile(Ravenscar)}.
5345 Note that this warning option functions differently from the
5346 restriction @code{No_Obsolescent_Features} in two respects.
5347 First, the restriction applies only to annex J features.
5348 Second, the restriction does flag uses of package @code{ASCII}.
5351 @emph{Suppress warnings on obsolescent features (Annex J).}
5352 @cindex @option{-gnatwJ} (@command{gcc})
5353 This switch disables warnings on use of obsolescent features.
5356 @emph{Activate warnings on variables that could be constants.}
5357 @cindex @option{-gnatwk} (@command{gcc})
5358 This switch activates warnings for variables that are initialized but
5359 never modified, and then could be declared constants. The default is that
5360 such warnings are not given.
5361 This warning can also be turned on using @option{-gnatwa}.
5364 @emph{Suppress warnings on variables that could be constants.}
5365 @cindex @option{-gnatwK} (@command{gcc})
5366 This switch disables warnings on variables that could be declared constants.
5369 @emph{Activate warnings for elaboration pragmas.}
5370 @cindex @option{-gnatwl} (@command{gcc})
5371 @cindex Elaboration, warnings
5372 This switch activates warnings on missing
5373 @code{Elaborate_All} and @code{Elaborate} pragmas.
5374 See the section in this guide on elaboration checking for details on
5375 when such pragmas should be used. In dynamic elaboration mode, this switch
5376 generations warnings about the need to add elaboration pragmas. Note however,
5377 that if you blindly follow these warnings, and add @code{Elaborate_All}
5378 warnings wherever they are recommended, you basically end up with the
5379 equivalent of the static elaboration model, which may not be what you want for
5380 legacy code for which the static model does not work.
5382 For the static model, the messages generated are labeled "info:" (for
5383 information messages). They are not warnings to add elaboration pragmas,
5384 merely informational messages showing what implicit elaboration pragmas
5385 have been added, for use in analyzing elaboration circularity problems.
5387 Warnings are also generated if you
5388 are using the static mode of elaboration, and a @code{pragma Elaborate}
5389 is encountered. The default is that such warnings
5391 This warning is not automatically turned on by the use of @option{-gnatwa}.
5394 @emph{Suppress warnings for elaboration pragmas.}
5395 @cindex @option{-gnatwL} (@command{gcc})
5396 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5397 See the section in this guide on elaboration checking for details on
5398 when such pragmas should be used.
5401 @emph{Activate warnings on modified but unreferenced variables.}
5402 @cindex @option{-gnatwm} (@command{gcc})
5403 This switch activates warnings for variables that are assigned (using
5404 an initialization value or with one or more assignment statements) but
5405 whose value is never read. The warning is suppressed for volatile
5406 variables and also for variables that are renamings of other variables
5407 or for which an address clause is given.
5408 This warning can also be turned on using @option{-gnatwa}.
5409 The default is that these warnings are not given.
5412 @emph{Disable warnings on modified but unreferenced variables.}
5413 @cindex @option{-gnatwM} (@command{gcc})
5414 This switch disables warnings for variables that are assigned or
5415 initialized, but never read.
5418 @emph{Activate warnings on suspicious modulus values.}
5419 @cindex @option{-gnatw.m} (@command{gcc})
5420 This switch activates warnings for modulus values that seem suspicious.
5421 The cases caught are where the size is the same as the modulus (e.g.
5422 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5423 with no size clause. The guess in both cases is that 2**x was intended
5424 rather than x. The default is that these warnings are given.
5427 @emph{Disable warnings on suspicious modulus values.}
5428 @cindex @option{-gnatw.M} (@command{gcc})
5429 This switch disables warnings for suspicious modulus values.
5432 @emph{Set normal warnings mode.}
5433 @cindex @option{-gnatwn} (@command{gcc})
5434 This switch sets normal warning mode, in which enabled warnings are
5435 issued and treated as warnings rather than errors. This is the default
5436 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5437 an explicit @option{-gnatws} or
5438 @option{-gnatwe}. It also cancels the effect of the
5439 implicit @option{-gnatwe} that is activated by the
5440 use of @option{-gnatg}.
5443 @emph{Activate warnings on address clause overlays.}
5444 @cindex @option{-gnatwo} (@command{gcc})
5445 @cindex Address Clauses, warnings
5446 This switch activates warnings for possibly unintended initialization
5447 effects of defining address clauses that cause one variable to overlap
5448 another. The default is that such warnings are generated.
5449 This warning can also be turned on using @option{-gnatwa}.
5452 @emph{Suppress warnings on address clause overlays.}
5453 @cindex @option{-gnatwO} (@command{gcc})
5454 This switch suppresses warnings on possibly unintended initialization
5455 effects of defining address clauses that cause one variable to overlap
5459 @emph{Activate warnings on modified but unreferenced out parameters.}
5460 @cindex @option{-gnatw.o} (@command{gcc})
5461 This switch activates warnings for variables that are modified by using
5462 them as actuals for a call to a procedure with an out mode formal, where
5463 the resulting assigned value is never read. It is applicable in the case
5464 where there is more than one out mode formal. If there is only one out
5465 mode formal, the warning is issued by default (controlled by -gnatwu).
5466 The warning is suppressed for volatile
5467 variables and also for variables that are renamings of other variables
5468 or for which an address clause is given.
5469 The default is that these warnings are not given. Note that this warning
5470 is not included in -gnatwa, it must be activated explicitly.
5473 @emph{Disable warnings on modified but unreferenced out parameters.}
5474 @cindex @option{-gnatw.O} (@command{gcc})
5475 This switch suppresses warnings for variables that are modified by using
5476 them as actuals for a call to a procedure with an out mode formal, where
5477 the resulting assigned value is never read.
5480 @emph{Activate warnings on ineffective pragma Inlines.}
5481 @cindex @option{-gnatwp} (@command{gcc})
5482 @cindex Inlining, warnings
5483 This switch activates warnings for failure of front end inlining
5484 (activated by @option{-gnatN}) to inline a particular call. There are
5485 many reasons for not being able to inline a call, including most
5486 commonly that the call is too complex to inline. The default is
5487 that such warnings are not given.
5488 This warning can also be turned on using @option{-gnatwa}.
5489 Warnings on ineffective inlining by the gcc back-end can be activated
5490 separately, using the gcc switch -Winline.
5493 @emph{Suppress warnings on ineffective pragma Inlines.}
5494 @cindex @option{-gnatwP} (@command{gcc})
5495 This switch suppresses warnings on ineffective pragma Inlines. If the
5496 inlining mechanism cannot inline a call, it will simply ignore the
5500 @emph{Activate warnings on parameter ordering.}
5501 @cindex @option{-gnatw.p} (@command{gcc})
5502 @cindex Parameter order, warnings
5503 This switch activates warnings for cases of suspicious parameter
5504 ordering when the list of arguments are all simple identifiers that
5505 match the names of the formals, but are in a different order. The
5506 warning is suppressed if any use of named parameter notation is used,
5507 so this is the appropriate way to suppress a false positive (and
5508 serves to emphasize that the "misordering" is deliberate). The
5510 that such warnings are not given.
5511 This warning can also be turned on using @option{-gnatwa}.
5514 @emph{Suppress warnings on parameter ordering.}
5515 @cindex @option{-gnatw.P} (@command{gcc})
5516 This switch suppresses warnings on cases of suspicious parameter
5520 @emph{Activate warnings on questionable missing parentheses.}
5521 @cindex @option{-gnatwq} (@command{gcc})
5522 @cindex Parentheses, warnings
5523 This switch activates warnings for cases where parentheses are not used and
5524 the result is potential ambiguity from a readers point of view. For example
5525 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5526 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5527 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5528 follow the rule of always parenthesizing to make the association clear, and
5529 this warning switch warns if such parentheses are not present. The default
5530 is that these warnings are given.
5531 This warning can also be turned on using @option{-gnatwa}.
5534 @emph{Suppress warnings on questionable missing parentheses.}
5535 @cindex @option{-gnatwQ} (@command{gcc})
5536 This switch suppresses warnings for cases where the association is not
5537 clear and the use of parentheses is preferred.
5540 @emph{Activate warnings on redundant constructs.}
5541 @cindex @option{-gnatwr} (@command{gcc})
5542 This switch activates warnings for redundant constructs. The following
5543 is the current list of constructs regarded as redundant:
5547 Assignment of an item to itself.
5549 Type conversion that converts an expression to its own type.
5551 Use of the attribute @code{Base} where @code{typ'Base} is the same
5554 Use of pragma @code{Pack} when all components are placed by a record
5555 representation clause.
5557 Exception handler containing only a reraise statement (raise with no
5558 operand) which has no effect.
5560 Use of the operator abs on an operand that is known at compile time
5563 Comparison of boolean expressions to an explicit True value.
5566 This warning can also be turned on using @option{-gnatwa}.
5567 The default is that warnings for redundant constructs are not given.
5570 @emph{Suppress warnings on redundant constructs.}
5571 @cindex @option{-gnatwR} (@command{gcc})
5572 This switch suppresses warnings for redundant constructs.
5575 @emph{Activate warnings for object renaming function.}
5576 @cindex @option{-gnatw.r} (@command{gcc})
5577 This switch activates warnings for an object renaming that renames a
5578 function call, which is equivalent to a constant declaration (as
5579 opposed to renaming the function itself). The default is that these
5580 warnings are given. This warning can also be turned on using
5584 @emph{Suppress warnings for object renaming function.}
5585 @cindex @option{-gnatwT} (@command{gcc})
5586 This switch suppresses warnings for object renaming function.
5589 @emph{Suppress all warnings.}
5590 @cindex @option{-gnatws} (@command{gcc})
5591 This switch completely suppresses the
5592 output of all warning messages from the GNAT front end.
5593 Note that it does not suppress warnings from the @command{gcc} back end.
5594 To suppress these back end warnings as well, use the switch @option{-w}
5595 in addition to @option{-gnatws}. Also this switch has no effect on the
5596 handling of style check messages.
5599 @emph{Activate warnings on overridden size clauses.}
5600 @cindex @option{-gnatw.s} (@command{gcc})
5601 @cindex Record Representation (component sizes)
5602 This switch activates warnings on component clauses in record
5603 representation clauses where the length given overrides that
5604 specified by an explicit size clause for the component type. A
5605 warning is similarly given in the array case if a specified
5606 component size overrides an explicit size clause for the array
5608 Note that @option{-gnatwa} does not affect the setting of this warning option.
5611 @emph{Suppress warnings on overridden size clauses.}
5612 @cindex @option{-gnatw.S} (@command{gcc})
5613 This switch suppresses warnings on component clauses in record
5614 representation clauses that override size clauses, and similar
5615 warnings when an array component size overrides a size clause.
5618 @emph{Activate warnings for tracking of deleted conditional code.}
5619 @cindex @option{-gnatwt} (@command{gcc})
5620 @cindex Deactivated code, warnings
5621 @cindex Deleted code, warnings
5622 This switch activates warnings for tracking of code in conditionals (IF and
5623 CASE statements) that is detected to be dead code which cannot be executed, and
5624 which is removed by the front end. This warning is off by default, and is not
5625 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5626 useful for detecting deactivated code in certified applications.
5629 @emph{Suppress warnings for tracking of deleted conditional code.}
5630 @cindex @option{-gnatwT} (@command{gcc})
5631 This switch suppresses warnings for tracking of deleted conditional code.
5634 @emph{Activate warnings on unused entities.}
5635 @cindex @option{-gnatwu} (@command{gcc})
5636 This switch activates warnings to be generated for entities that
5637 are declared but not referenced, and for units that are @code{with}'ed
5639 referenced. In the case of packages, a warning is also generated if
5640 no entities in the package are referenced. This means that if the package
5641 is referenced but the only references are in @code{use}
5642 clauses or @code{renames}
5643 declarations, a warning is still generated. A warning is also generated
5644 for a generic package that is @code{with}'ed but never instantiated.
5645 In the case where a package or subprogram body is compiled, and there
5646 is a @code{with} on the corresponding spec
5647 that is only referenced in the body,
5648 a warning is also generated, noting that the
5649 @code{with} can be moved to the body. The default is that
5650 such warnings are not generated.
5651 This switch also activates warnings on unreferenced formals
5652 (it includes the effect of @option{-gnatwf}).
5653 This warning can also be turned on using @option{-gnatwa}.
5656 @emph{Suppress warnings on unused entities.}
5657 @cindex @option{-gnatwU} (@command{gcc})
5658 This switch suppresses warnings for unused entities and packages.
5659 It also turns off warnings on unreferenced formals (and thus includes
5660 the effect of @option{-gnatwF}).
5663 @emph{Activate warnings on unordered enumeration types.}
5664 @cindex @option{-gnatw.u} (@command{gcc})
5665 This switch causes enumeration types to be considered as conceptually
5666 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5667 The effect is to generate warnings in clients that use explicit comparisons
5668 or subranges, since these constructs both treat objects of the type as
5669 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5670 which the type is declared, or its body or subunits.) Please refer to
5671 the description of pragma @code{Ordered} in the
5672 @cite{@value{EDITION} Reference Manual} for further details.
5675 @emph{Deactivate warnings on unordered enumeration types.}
5676 @cindex @option{-gnatw.U} (@command{gcc})
5677 This switch causes all enumeration types to be considered as ordered, so
5678 that no warnings are given for comparisons or subranges for any type.
5681 @emph{Activate warnings on unassigned variables.}
5682 @cindex @option{-gnatwv} (@command{gcc})
5683 @cindex Unassigned variable warnings
5684 This switch activates warnings for access to variables which
5685 may not be properly initialized. The default is that
5686 such warnings are generated.
5687 This warning can also be turned on using @option{-gnatwa}.
5690 @emph{Suppress warnings on unassigned variables.}
5691 @cindex @option{-gnatwV} (@command{gcc})
5692 This switch suppresses warnings for access to variables which
5693 may not be properly initialized.
5694 For variables of a composite type, the warning can also be suppressed in
5695 Ada 2005 by using a default initialization with a box. For example, if
5696 Table is an array of records whose components are only partially uninitialized,
5697 then the following code:
5699 @smallexample @c ada
5700 Tab : Table := (others => <>);
5703 will suppress warnings on subsequent statements that access components
5707 @emph{Activate warnings on wrong low bound assumption.}
5708 @cindex @option{-gnatww} (@command{gcc})
5709 @cindex String indexing warnings
5710 This switch activates warnings for indexing an unconstrained string parameter
5711 with a literal or S'Length. This is a case where the code is assuming that the
5712 low bound is one, which is in general not true (for example when a slice is
5713 passed). The default is that such warnings are generated.
5714 This warning can also be turned on using @option{-gnatwa}.
5717 @emph{Suppress warnings on wrong low bound assumption.}
5718 @cindex @option{-gnatwW} (@command{gcc})
5719 This switch suppresses warnings for indexing an unconstrained string parameter
5720 with a literal or S'Length. Note that this warning can also be suppressed
5721 in a particular case by adding an
5722 assertion that the lower bound is 1,
5723 as shown in the following example.
5725 @smallexample @c ada
5726 procedure K (S : String) is
5727 pragma Assert (S'First = 1);
5732 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5733 @cindex @option{-gnatw.w} (@command{gcc})
5734 @cindex Warnings Off control
5735 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5736 where either the pragma is entirely useless (because it suppresses no
5737 warnings), or it could be replaced by @code{pragma Unreferenced} or
5738 @code{pragma Unmodified}.The default is that these warnings are not given.
5739 Note that this warning is not included in -gnatwa, it must be
5740 activated explicitly.
5743 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5744 @cindex @option{-gnatw.W} (@command{gcc})
5745 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5748 @emph{Activate warnings on Export/Import pragmas.}
5749 @cindex @option{-gnatwx} (@command{gcc})
5750 @cindex Export/Import pragma warnings
5751 This switch activates warnings on Export/Import pragmas when
5752 the compiler detects a possible conflict between the Ada and
5753 foreign language calling sequences. For example, the use of
5754 default parameters in a convention C procedure is dubious
5755 because the C compiler cannot supply the proper default, so
5756 a warning is issued. The default is that such warnings are
5758 This warning can also be turned on using @option{-gnatwa}.
5761 @emph{Suppress warnings on Export/Import pragmas.}
5762 @cindex @option{-gnatwX} (@command{gcc})
5763 This switch suppresses warnings on Export/Import pragmas.
5764 The sense of this is that you are telling the compiler that
5765 you know what you are doing in writing the pragma, and it
5766 should not complain at you.
5769 @emph{Activate warnings for No_Exception_Propagation mode.}
5770 @cindex @option{-gnatwm} (@command{gcc})
5771 This switch activates warnings for exception usage when pragma Restrictions
5772 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5773 explicit exception raises which are not covered by a local handler, and for
5774 exception handlers which do not cover a local raise. The default is that these
5775 warnings are not given.
5778 @emph{Disable warnings for No_Exception_Propagation mode.}
5779 This switch disables warnings for exception usage when pragma Restrictions
5780 (No_Exception_Propagation) is in effect.
5783 @emph{Activate warnings for Ada 2005 compatibility issues.}
5784 @cindex @option{-gnatwy} (@command{gcc})
5785 @cindex Ada 2005 compatibility issues warnings
5786 For the most part Ada 2005 is upwards compatible with Ada 95,
5787 but there are some exceptions (for example the fact that
5788 @code{interface} is now a reserved word in Ada 2005). This
5789 switch activates several warnings to help in identifying
5790 and correcting such incompatibilities. The default is that
5791 these warnings are generated. Note that at one point Ada 2005
5792 was called Ada 0Y, hence the choice of character.
5793 This warning can also be turned on using @option{-gnatwa}.
5796 @emph{Disable warnings for Ada 2005 compatibility issues.}
5797 @cindex @option{-gnatwY} (@command{gcc})
5798 @cindex Ada 2005 compatibility issues warnings
5799 This switch suppresses several warnings intended to help in identifying
5800 incompatibilities between Ada 95 and Ada 2005.
5803 @emph{Activate warnings on unchecked conversions.}
5804 @cindex @option{-gnatwz} (@command{gcc})
5805 @cindex Unchecked_Conversion warnings
5806 This switch activates warnings for unchecked conversions
5807 where the types are known at compile time to have different
5809 is that such warnings are generated. Warnings are also
5810 generated for subprogram pointers with different conventions,
5811 and, on VMS only, for data pointers with different conventions.
5812 This warning can also be turned on using @option{-gnatwa}.
5815 @emph{Suppress warnings on unchecked conversions.}
5816 @cindex @option{-gnatwZ} (@command{gcc})
5817 This switch suppresses warnings for unchecked conversions
5818 where the types are known at compile time to have different
5819 sizes or conventions.
5821 @item ^-Wunused^WARNINGS=UNUSED^
5822 @cindex @option{-Wunused}
5823 The warnings controlled by the @option{-gnatw} switch are generated by
5824 the front end of the compiler. The @option{GCC} back end can provide
5825 additional warnings and they are controlled by the @option{-W} switch.
5826 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5827 warnings for entities that are declared but not referenced.
5829 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5830 @cindex @option{-Wuninitialized}
5831 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5832 the back end warning for uninitialized variables. This switch must be
5833 used in conjunction with an optimization level greater than zero.
5835 @item -Wstack-usage=@var{len}
5836 @cindex @option{-Wstack-usage}
5837 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5838 See @ref{Static Stack Usage Analysis} for details.
5840 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5841 @cindex @option{-Wall}
5842 This switch enables most warnings from the @option{GCC} back end.
5843 The code generator detects a number of warning situations that are missed
5844 by the @option{GNAT} front end, and this switch can be used to activate them.
5845 The use of this switch also sets the default front end warning mode to
5846 @option{-gnatwa}, that is, most front end warnings activated as well.
5848 @item ^-w^/NO_BACK_END_WARNINGS^
5850 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5851 The use of this switch also sets the default front end warning mode to
5852 @option{-gnatws}, that is, front end warnings suppressed as well.
5858 A string of warning parameters can be used in the same parameter. For example:
5865 will turn on all optional warnings except for elaboration pragma warnings,
5866 and also specify that warnings should be treated as errors.
5868 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5893 @node Debugging and Assertion Control
5894 @subsection Debugging and Assertion Control
5898 @cindex @option{-gnata} (@command{gcc})
5904 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5905 are ignored. This switch, where @samp{a} stands for assert, causes
5906 @code{Assert} and @code{Debug} pragmas to be activated.
5908 The pragmas have the form:
5912 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5913 @var{static-string-expression}@r{]})
5914 @b{pragma} Debug (@var{procedure call})
5919 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5920 If the result is @code{True}, the pragma has no effect (other than
5921 possible side effects from evaluating the expression). If the result is
5922 @code{False}, the exception @code{Assert_Failure} declared in the package
5923 @code{System.Assertions} is
5924 raised (passing @var{static-string-expression}, if present, as the
5925 message associated with the exception). If no string expression is
5926 given the default is a string giving the file name and line number
5929 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5930 @code{pragma Debug} may appear within a declaration sequence, allowing
5931 debugging procedures to be called between declarations.
5934 @item /DEBUG@r{[}=debug-level@r{]}
5936 Specifies how much debugging information is to be included in
5937 the resulting object file where 'debug-level' is one of the following:
5940 Include both debugger symbol records and traceback
5942 This is the default setting.
5944 Include both debugger symbol records and traceback in
5947 Excludes both debugger symbol records and traceback
5948 the object file. Same as /NODEBUG.
5950 Includes only debugger symbol records in the object
5951 file. Note that this doesn't include traceback information.
5956 @node Validity Checking
5957 @subsection Validity Checking
5958 @findex Validity Checking
5961 The Ada Reference Manual defines the concept of invalid values (see
5962 RM 13.9.1). The primary source of invalid values is uninitialized
5963 variables. A scalar variable that is left uninitialized may contain
5964 an invalid value; the concept of invalid does not apply to access or
5967 It is an error to read an invalid value, but the RM does not require
5968 run-time checks to detect such errors, except for some minimal
5969 checking to prevent erroneous execution (i.e. unpredictable
5970 behavior). This corresponds to the @option{-gnatVd} switch below,
5971 which is the default. For example, by default, if the expression of a
5972 case statement is invalid, it will raise Constraint_Error rather than
5973 causing a wild jump, and if an array index on the left-hand side of an
5974 assignment is invalid, it will raise Constraint_Error rather than
5975 overwriting an arbitrary memory location.
5977 The @option{-gnatVa} may be used to enable additional validity checks,
5978 which are not required by the RM. These checks are often very
5979 expensive (which is why the RM does not require them). These checks
5980 are useful in tracking down uninitialized variables, but they are
5981 not usually recommended for production builds.
5983 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5984 control; you can enable whichever validity checks you desire. However,
5985 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5986 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5987 sufficient for non-debugging use.
5989 The @option{-gnatB} switch tells the compiler to assume that all
5990 values are valid (that is, within their declared subtype range)
5991 except in the context of a use of the Valid attribute. This means
5992 the compiler can generate more efficient code, since the range
5993 of values is better known at compile time. However, an uninitialized
5994 variable can cause wild jumps and memory corruption in this mode.
5996 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5997 checking mode as described below.
5999 The @code{x} argument is a string of letters that
6000 indicate validity checks that are performed or not performed in addition
6001 to the default checks required by Ada as described above.
6004 The options allowed for this qualifier
6005 indicate validity checks that are performed or not performed in addition
6006 to the default checks required by Ada as described above.
6012 @emph{All validity checks.}
6013 @cindex @option{-gnatVa} (@command{gcc})
6014 All validity checks are turned on.
6016 That is, @option{-gnatVa} is
6017 equivalent to @option{gnatVcdfimorst}.
6021 @emph{Validity checks for copies.}
6022 @cindex @option{-gnatVc} (@command{gcc})
6023 The right hand side of assignments, and the initializing values of
6024 object declarations are validity checked.
6027 @emph{Default (RM) validity checks.}
6028 @cindex @option{-gnatVd} (@command{gcc})
6029 Some validity checks are done by default following normal Ada semantics
6031 A check is done in case statements that the expression is within the range
6032 of the subtype. If it is not, Constraint_Error is raised.
6033 For assignments to array components, a check is done that the expression used
6034 as index is within the range. If it is not, Constraint_Error is raised.
6035 Both these validity checks may be turned off using switch @option{-gnatVD}.
6036 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6037 switch @option{-gnatVd} will leave the checks turned on.
6038 Switch @option{-gnatVD} should be used only if you are sure that all such
6039 expressions have valid values. If you use this switch and invalid values
6040 are present, then the program is erroneous, and wild jumps or memory
6041 overwriting may occur.
6044 @emph{Validity checks for elementary components.}
6045 @cindex @option{-gnatVe} (@command{gcc})
6046 In the absence of this switch, assignments to record or array components are
6047 not validity checked, even if validity checks for assignments generally
6048 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6049 require valid data, but assignment of individual components does. So for
6050 example, there is a difference between copying the elements of an array with a
6051 slice assignment, compared to assigning element by element in a loop. This
6052 switch allows you to turn off validity checking for components, even when they
6053 are assigned component by component.
6056 @emph{Validity checks for floating-point values.}
6057 @cindex @option{-gnatVf} (@command{gcc})
6058 In the absence of this switch, validity checking occurs only for discrete
6059 values. If @option{-gnatVf} is specified, then validity checking also applies
6060 for floating-point values, and NaNs and infinities are considered invalid,
6061 as well as out of range values for constrained types. Note that this means
6062 that standard IEEE infinity mode is not allowed. The exact contexts
6063 in which floating-point values are checked depends on the setting of other
6064 options. For example,
6065 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6066 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6067 (the order does not matter) specifies that floating-point parameters of mode
6068 @code{in} should be validity checked.
6071 @emph{Validity checks for @code{in} mode parameters}
6072 @cindex @option{-gnatVi} (@command{gcc})
6073 Arguments for parameters of mode @code{in} are validity checked in function
6074 and procedure calls at the point of call.
6077 @emph{Validity checks for @code{in out} mode parameters.}
6078 @cindex @option{-gnatVm} (@command{gcc})
6079 Arguments for parameters of mode @code{in out} are validity checked in
6080 procedure calls at the point of call. The @code{'m'} here stands for
6081 modify, since this concerns parameters that can be modified by the call.
6082 Note that there is no specific option to test @code{out} parameters,
6083 but any reference within the subprogram will be tested in the usual
6084 manner, and if an invalid value is copied back, any reference to it
6085 will be subject to validity checking.
6088 @emph{No validity checks.}
6089 @cindex @option{-gnatVn} (@command{gcc})
6090 This switch turns off all validity checking, including the default checking
6091 for case statements and left hand side subscripts. Note that the use of
6092 the switch @option{-gnatp} suppresses all run-time checks, including
6093 validity checks, and thus implies @option{-gnatVn}. When this switch
6094 is used, it cancels any other @option{-gnatV} previously issued.
6097 @emph{Validity checks for operator and attribute operands.}
6098 @cindex @option{-gnatVo} (@command{gcc})
6099 Arguments for predefined operators and attributes are validity checked.
6100 This includes all operators in package @code{Standard},
6101 the shift operators defined as intrinsic in package @code{Interfaces}
6102 and operands for attributes such as @code{Pos}. Checks are also made
6103 on individual component values for composite comparisons, and on the
6104 expressions in type conversions and qualified expressions. Checks are
6105 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6108 @emph{Validity checks for parameters.}
6109 @cindex @option{-gnatVp} (@command{gcc})
6110 This controls the treatment of parameters within a subprogram (as opposed
6111 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6112 of parameters on a call. If either of these call options is used, then
6113 normally an assumption is made within a subprogram that the input arguments
6114 have been validity checking at the point of call, and do not need checking
6115 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6116 is not made, and parameters are not assumed to be valid, so their validity
6117 will be checked (or rechecked) within the subprogram.
6120 @emph{Validity checks for function returns.}
6121 @cindex @option{-gnatVr} (@command{gcc})
6122 The expression in @code{return} statements in functions is validity
6126 @emph{Validity checks for subscripts.}
6127 @cindex @option{-gnatVs} (@command{gcc})
6128 All subscripts expressions are checked for validity, whether they appear
6129 on the right side or left side (in default mode only left side subscripts
6130 are validity checked).
6133 @emph{Validity checks for tests.}
6134 @cindex @option{-gnatVt} (@command{gcc})
6135 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6136 statements are checked, as well as guard expressions in entry calls.
6141 The @option{-gnatV} switch may be followed by
6142 ^a string of letters^a list of options^
6143 to turn on a series of validity checking options.
6145 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6146 specifies that in addition to the default validity checking, copies and
6147 function return expressions are to be validity checked.
6148 In order to make it easier
6149 to specify the desired combination of effects,
6151 the upper case letters @code{CDFIMORST} may
6152 be used to turn off the corresponding lower case option.
6155 the prefix @code{NO} on an option turns off the corresponding validity
6158 @item @code{NOCOPIES}
6159 @item @code{NODEFAULT}
6160 @item @code{NOFLOATS}
6161 @item @code{NOIN_PARAMS}
6162 @item @code{NOMOD_PARAMS}
6163 @item @code{NOOPERANDS}
6164 @item @code{NORETURNS}
6165 @item @code{NOSUBSCRIPTS}
6166 @item @code{NOTESTS}
6170 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6171 turns on all validity checking options except for
6172 checking of @code{@b{in out}} procedure arguments.
6174 The specification of additional validity checking generates extra code (and
6175 in the case of @option{-gnatVa} the code expansion can be substantial).
6176 However, these additional checks can be very useful in detecting
6177 uninitialized variables, incorrect use of unchecked conversion, and other
6178 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6179 is useful in conjunction with the extra validity checking, since this
6180 ensures that wherever possible uninitialized variables have invalid values.
6182 See also the pragma @code{Validity_Checks} which allows modification of
6183 the validity checking mode at the program source level, and also allows for
6184 temporary disabling of validity checks.
6186 @node Style Checking
6187 @subsection Style Checking
6188 @findex Style checking
6191 The @option{-gnaty^x^(option,option,@dots{})^} switch
6192 @cindex @option{-gnaty} (@command{gcc})
6193 causes the compiler to
6194 enforce specified style rules. A limited set of style rules has been used
6195 in writing the GNAT sources themselves. This switch allows user programs
6196 to activate all or some of these checks. If the source program fails a
6197 specified style check, an appropriate message is given, preceded by
6198 the character sequence ``(style)''. This message does not prevent
6199 successful compilation (unless the @option{-gnatwe} switch is used).
6201 Note that this is by no means intended to be a general facility for
6202 checking arbitrary coding standards. It is simply an embedding of the
6203 style rules we have chosen for the GNAT sources. If you are starting
6204 a project which does not have established style standards, you may
6205 find it useful to adopt the entire set of GNAT coding standards, or
6206 some subset of them. If you already have an established set of coding
6207 standards, then it may be that selected style checking options do
6208 indeed correspond to choices you have made, but for general checking
6209 of an existing set of coding rules, you should look to the gnatcheck
6210 tool, which is designed for that purpose.
6213 @code{(option,option,@dots{})} is a sequence of keywords
6216 The string @var{x} is a sequence of letters or digits
6218 indicating the particular style
6219 checks to be performed. The following checks are defined:
6224 @emph{Specify indentation level.}
6225 If a digit from 1-9 appears
6226 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6227 then proper indentation is checked, with the digit indicating the
6228 indentation level required. A value of zero turns off this style check.
6229 The general style of required indentation is as specified by
6230 the examples in the Ada Reference Manual. Full line comments must be
6231 aligned with the @code{--} starting on a column that is a multiple of
6232 the alignment level, or they may be aligned the same way as the following
6233 non-blank line (this is useful when full line comments appear in the middle
6237 @emph{Check attribute casing.}
6238 Attribute names, including the case of keywords such as @code{digits}
6239 used as attributes names, must be written in mixed case, that is, the
6240 initial letter and any letter following an underscore must be uppercase.
6241 All other letters must be lowercase.
6243 @item ^A^ARRAY_INDEXES^
6244 @emph{Use of array index numbers in array attributes.}
6245 When using the array attributes First, Last, Range,
6246 or Length, the index number must be omitted for one-dimensional arrays
6247 and is required for multi-dimensional arrays.
6250 @emph{Blanks not allowed at statement end.}
6251 Trailing blanks are not allowed at the end of statements. The purpose of this
6252 rule, together with h (no horizontal tabs), is to enforce a canonical format
6253 for the use of blanks to separate source tokens.
6255 @item ^B^BOOLEAN_OPERATORS^
6256 @emph{Check Boolean operators.}
6257 The use of AND/OR operators is not permitted except in the cases of modular
6258 operands, array operands, and simple stand-alone boolean variables or
6259 boolean constants. In all other cases AND THEN/OR ELSE are required.
6262 @emph{Check comments.}
6263 Comments must meet the following set of rules:
6268 The ``@code{--}'' that starts the column must either start in column one,
6269 or else at least one blank must precede this sequence.
6272 Comments that follow other tokens on a line must have at least one blank
6273 following the ``@code{--}'' at the start of the comment.
6276 Full line comments must have at least two blanks following the
6277 ``@code{--}'' that starts the comment, with the following exceptions.
6280 A line consisting only of the ``@code{--}'' characters, possibly preceded
6281 by blanks is permitted.
6284 A comment starting with ``@code{--x}'' where @code{x} is a special character
6286 This allows proper processing of the output generated by specialized tools
6287 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6289 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6290 special character is defined as being in one of the ASCII ranges
6291 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6292 Note that this usage is not permitted
6293 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6296 A line consisting entirely of minus signs, possibly preceded by blanks, is
6297 permitted. This allows the construction of box comments where lines of minus
6298 signs are used to form the top and bottom of the box.
6301 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6302 least one blank follows the initial ``@code{--}''. Together with the preceding
6303 rule, this allows the construction of box comments, as shown in the following
6306 ---------------------------
6307 -- This is a box comment --
6308 -- with two text lines. --
6309 ---------------------------
6313 @item ^d^DOS_LINE_ENDINGS^
6314 @emph{Check no DOS line terminators present.}
6315 All lines must be terminated by a single ASCII.LF
6316 character (in particular the DOS line terminator sequence CR/LF is not
6320 @emph{Check end/exit labels.}
6321 Optional labels on @code{end} statements ending subprograms and on
6322 @code{exit} statements exiting named loops, are required to be present.
6325 @emph{No form feeds or vertical tabs.}
6326 Neither form feeds nor vertical tab characters are permitted
6330 @emph{GNAT style mode}
6331 The set of style check switches is set to match that used by the GNAT sources.
6332 This may be useful when developing code that is eventually intended to be
6333 incorporated into GNAT. For further details, see GNAT sources.
6336 @emph{No horizontal tabs.}
6337 Horizontal tab characters are not permitted in the source text.
6338 Together with the b (no blanks at end of line) check, this
6339 enforces a canonical form for the use of blanks to separate
6343 @emph{Check if-then layout.}
6344 The keyword @code{then} must appear either on the same
6345 line as corresponding @code{if}, or on a line on its own, lined
6346 up under the @code{if} with at least one non-blank line in between
6347 containing all or part of the condition to be tested.
6350 @emph{check mode IN keywords}
6351 Mode @code{in} (the default mode) is not
6352 allowed to be given explicitly. @code{in out} is fine,
6353 but not @code{in} on its own.
6356 @emph{Check keyword casing.}
6357 All keywords must be in lower case (with the exception of keywords
6358 such as @code{digits} used as attribute names to which this check
6362 @emph{Check layout.}
6363 Layout of statement and declaration constructs must follow the
6364 recommendations in the Ada Reference Manual, as indicated by the
6365 form of the syntax rules. For example an @code{else} keyword must
6366 be lined up with the corresponding @code{if} keyword.
6368 There are two respects in which the style rule enforced by this check
6369 option are more liberal than those in the Ada Reference Manual. First
6370 in the case of record declarations, it is permissible to put the
6371 @code{record} keyword on the same line as the @code{type} keyword, and
6372 then the @code{end} in @code{end record} must line up under @code{type}.
6373 This is also permitted when the type declaration is split on two lines.
6374 For example, any of the following three layouts is acceptable:
6376 @smallexample @c ada
6399 Second, in the case of a block statement, a permitted alternative
6400 is to put the block label on the same line as the @code{declare} or
6401 @code{begin} keyword, and then line the @code{end} keyword up under
6402 the block label. For example both the following are permitted:
6404 @smallexample @c ada
6422 The same alternative format is allowed for loops. For example, both of
6423 the following are permitted:
6425 @smallexample @c ada
6427 Clear : while J < 10 loop
6438 @item ^Lnnn^MAX_NESTING=nnn^
6439 @emph{Set maximum nesting level}
6440 The maximum level of nesting of constructs (including subprograms, loops,
6441 blocks, packages, and conditionals) may not exceed the given value
6442 @option{nnn}. A value of zero disconnects this style check.
6444 @item ^m^LINE_LENGTH^
6445 @emph{Check maximum line length.}
6446 The length of source lines must not exceed 79 characters, including
6447 any trailing blanks. The value of 79 allows convenient display on an
6448 80 character wide device or window, allowing for possible special
6449 treatment of 80 character lines. Note that this count is of
6450 characters in the source text. This means that a tab character counts
6451 as one character in this count but a wide character sequence counts as
6452 a single character (however many bytes are needed in the encoding).
6454 @item ^Mnnn^MAX_LENGTH=nnn^
6455 @emph{Set maximum line length.}
6456 The length of lines must not exceed the
6457 given value @option{nnn}. The maximum value that can be specified is 32767.
6459 @item ^n^STANDARD_CASING^
6460 @emph{Check casing of entities in Standard.}
6461 Any identifier from Standard must be cased
6462 to match the presentation in the Ada Reference Manual (for example,
6463 @code{Integer} and @code{ASCII.NUL}).
6466 @emph{Turn off all style checks}
6467 All style check options are turned off.
6469 @item ^o^ORDERED_SUBPROGRAMS^
6470 @emph{Check order of subprogram bodies.}
6471 All subprogram bodies in a given scope
6472 (e.g.@: a package body) must be in alphabetical order. The ordering
6473 rule uses normal Ada rules for comparing strings, ignoring casing
6474 of letters, except that if there is a trailing numeric suffix, then
6475 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6478 @item ^O^OVERRIDING_INDICATORS^
6479 @emph{Check that overriding subprograms are explicitly marked as such.}
6480 The declaration of a primitive operation of a type extension that overrides
6481 an inherited operation must carry an overriding indicator.
6484 @emph{Check pragma casing.}
6485 Pragma names must be written in mixed case, that is, the
6486 initial letter and any letter following an underscore must be uppercase.
6487 All other letters must be lowercase.
6489 @item ^r^REFERENCES^
6490 @emph{Check references.}
6491 All identifier references must be cased in the same way as the
6492 corresponding declaration. No specific casing style is imposed on
6493 identifiers. The only requirement is for consistency of references
6496 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6497 @emph{Check no statements after THEN/ELSE.}
6498 No statements are allowed
6499 on the same line as a THEN or ELSE keyword following the
6500 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6501 and a special exception allows a pragma to appear after ELSE.
6504 @emph{Check separate specs.}
6505 Separate declarations (``specs'') are required for subprograms (a
6506 body is not allowed to serve as its own declaration). The only
6507 exception is that parameterless library level procedures are
6508 not required to have a separate declaration. This exception covers
6509 the most frequent form of main program procedures.
6512 @emph{Check token spacing.}
6513 The following token spacing rules are enforced:
6518 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6521 The token @code{=>} must be surrounded by spaces.
6524 The token @code{<>} must be preceded by a space or a left parenthesis.
6527 Binary operators other than @code{**} must be surrounded by spaces.
6528 There is no restriction on the layout of the @code{**} binary operator.
6531 Colon must be surrounded by spaces.
6534 Colon-equal (assignment, initialization) must be surrounded by spaces.
6537 Comma must be the first non-blank character on the line, or be
6538 immediately preceded by a non-blank character, and must be followed
6542 If the token preceding a left parenthesis ends with a letter or digit, then
6543 a space must separate the two tokens.
6546 if the token following a right parenthesis starts with a letter or digit, then
6547 a space must separate the two tokens.
6550 A right parenthesis must either be the first non-blank character on
6551 a line, or it must be preceded by a non-blank character.
6554 A semicolon must not be preceded by a space, and must not be followed by
6555 a non-blank character.
6558 A unary plus or minus may not be followed by a space.
6561 A vertical bar must be surrounded by spaces.
6564 @item ^u^UNNECESSARY_BLANK_LINES^
6565 @emph{Check unnecessary blank lines.}
6566 Unnecessary blank lines are not allowed. A blank line is considered
6567 unnecessary if it appears at the end of the file, or if more than
6568 one blank line occurs in sequence.
6570 @item ^x^XTRA_PARENS^
6571 @emph{Check extra parentheses.}
6572 Unnecessary extra level of parentheses (C-style) are not allowed
6573 around conditions in @code{if} statements, @code{while} statements and
6574 @code{exit} statements.
6576 @item ^y^ALL_BUILTIN^
6577 @emph{Set all standard style check options}
6578 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6579 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6580 @option{-gnatyS}, @option{-gnatyLnnn},
6581 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6585 @emph{Remove style check options}
6586 This causes any subsequent options in the string to act as canceling the
6587 corresponding style check option. To cancel maximum nesting level control,
6588 use @option{L} parameter witout any integer value after that, because any
6589 digit following @option{-} in the parameter string of the @option{-gnaty}
6590 option will be threated as canceling indentation check. The same is true
6591 for @option{M} parameter. @option{y} and @option{N} parameters are not
6592 allowed after @option{-}.
6595 This causes any subsequent options in the string to enable the corresponding
6596 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6602 @emph{Removing style check options}
6603 If the name of a style check is preceded by @option{NO} then the corresponding
6604 style check is turned off. For example @option{NOCOMMENTS} turns off style
6605 checking for comments.
6610 In the above rules, appearing in column one is always permitted, that is,
6611 counts as meeting either a requirement for a required preceding space,
6612 or as meeting a requirement for no preceding space.
6614 Appearing at the end of a line is also always permitted, that is, counts
6615 as meeting either a requirement for a following space, or as meeting
6616 a requirement for no following space.
6619 If any of these style rules is violated, a message is generated giving
6620 details on the violation. The initial characters of such messages are
6621 always ``@code{(style)}''. Note that these messages are treated as warning
6622 messages, so they normally do not prevent the generation of an object
6623 file. The @option{-gnatwe} switch can be used to treat warning messages,
6624 including style messages, as fatal errors.
6628 @option{-gnaty} on its own (that is not
6629 followed by any letters or digits), then the effect is equivalent
6630 to the use of @option{-gnatyy}, as described above, that is all
6631 built-in standard style check options are enabled.
6635 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6636 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6637 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6647 clears any previously set style checks.
6649 @node Run-Time Checks
6650 @subsection Run-Time Checks
6651 @cindex Division by zero
6652 @cindex Access before elaboration
6653 @cindex Checks, division by zero
6654 @cindex Checks, access before elaboration
6655 @cindex Checks, stack overflow checking
6658 By default, the following checks are suppressed: integer overflow
6659 checks, stack overflow checks, and checks for access before
6660 elaboration on subprogram calls. All other checks, including range
6661 checks and array bounds checks, are turned on by default. The
6662 following @command{gcc} switches refine this default behavior.
6667 @cindex @option{-gnatp} (@command{gcc})
6668 @cindex Suppressing checks
6669 @cindex Checks, suppressing
6671 This switch causes the unit to be compiled
6672 as though @code{pragma Suppress (All_checks)}
6673 had been present in the source. Validity checks are also eliminated (in
6674 other words @option{-gnatp} also implies @option{-gnatVn}.
6675 Use this switch to improve the performance
6676 of the code at the expense of safety in the presence of invalid data or
6679 Note that when checks are suppressed, the compiler is allowed, but not
6680 required, to omit the checking code. If the run-time cost of the
6681 checking code is zero or near-zero, the compiler will generate it even
6682 if checks are suppressed. In particular, if the compiler can prove
6683 that a certain check will necessarily fail, it will generate code to
6684 do an unconditional ``raise'', even if checks are suppressed. The
6685 compiler warns in this case. Another case in which checks may not be
6686 eliminated is when they are embedded in certain run time routines such
6687 as math library routines.
6689 Of course, run-time checks are omitted whenever the compiler can prove
6690 that they will not fail, whether or not checks are suppressed.
6692 Note that if you suppress a check that would have failed, program
6693 execution is erroneous, which means the behavior is totally
6694 unpredictable. The program might crash, or print wrong answers, or
6695 do anything else. It might even do exactly what you wanted it to do
6696 (and then it might start failing mysteriously next week or next
6697 year). The compiler will generate code based on the assumption that
6698 the condition being checked is true, which can result in disaster if
6699 that assumption is wrong.
6701 The @option{-gnatp} switch has no effect if a subsequent
6702 @option{-gnat-p} switch appears.
6705 @cindex @option{-gnat-p} (@command{gcc})
6706 @cindex Suppressing checks
6707 @cindex Checks, suppressing
6709 This switch cancels the effect of a previous @option{gnatp} switch.
6712 @cindex @option{-gnato} (@command{gcc})
6713 @cindex Overflow checks
6714 @cindex Check, overflow
6715 Enables overflow checking for integer operations.
6716 This causes GNAT to generate slower and larger executable
6717 programs by adding code to check for overflow (resulting in raising
6718 @code{Constraint_Error} as required by standard Ada
6719 semantics). These overflow checks correspond to situations in which
6720 the true value of the result of an operation may be outside the base
6721 range of the result type. The following example shows the distinction:
6723 @smallexample @c ada
6724 X1 : Integer := "Integer'Last";
6725 X2 : Integer range 1 .. 5 := "5";
6726 X3 : Integer := "Integer'Last";
6727 X4 : Integer range 1 .. 5 := "5";
6728 F : Float := "2.0E+20";
6737 Note that if explicit values are assigned at compile time, the
6738 compiler may be able to detect overflow at compile time, in which case
6739 no actual run-time checking code is required, and Constraint_Error
6740 will be raised unconditionally, with or without
6741 @option{-gnato}. That's why the assigned values in the above fragment
6742 are in quotes, the meaning is "assign a value not known to the
6743 compiler that happens to be equal to ...". The remaining discussion
6744 assumes that the compiler cannot detect the values at compile time.
6746 Here the first addition results in a value that is outside the base range
6747 of Integer, and hence requires an overflow check for detection of the
6748 constraint error. Thus the first assignment to @code{X1} raises a
6749 @code{Constraint_Error} exception only if @option{-gnato} is set.
6751 The second increment operation results in a violation of the explicit
6752 range constraint; such range checks are performed by default, and are
6753 unaffected by @option{-gnato}.
6755 The two conversions of @code{F} both result in values that are outside
6756 the base range of type @code{Integer} and thus will raise
6757 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6758 The fact that the result of the second conversion is assigned to
6759 variable @code{X4} with a restricted range is irrelevant, since the problem
6760 is in the conversion, not the assignment.
6762 Basically the rule is that in the default mode (@option{-gnato} not
6763 used), the generated code assures that all integer variables stay
6764 within their declared ranges, or within the base range if there is
6765 no declared range. This prevents any serious problems like indexes
6766 out of range for array operations.
6768 What is not checked in default mode is an overflow that results in
6769 an in-range, but incorrect value. In the above example, the assignments
6770 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6771 range of the target variable, but the result is wrong in the sense that
6772 it is too large to be represented correctly. Typically the assignment
6773 to @code{X1} will result in wrap around to the largest negative number.
6774 The conversions of @code{F} will result in some @code{Integer} value
6775 and if that integer value is out of the @code{X4} range then the
6776 subsequent assignment would generate an exception.
6778 @findex Machine_Overflows
6779 Note that the @option{-gnato} switch does not affect the code generated
6780 for any floating-point operations; it applies only to integer
6782 For floating-point, GNAT has the @code{Machine_Overflows}
6783 attribute set to @code{False} and the normal mode of operation is to
6784 generate IEEE NaN and infinite values on overflow or invalid operations
6785 (such as dividing 0.0 by 0.0).
6787 The reason that we distinguish overflow checking from other kinds of
6788 range constraint checking is that a failure of an overflow check, unlike
6789 for example the failure of a range check, can result in an incorrect
6790 value, but cannot cause random memory destruction (like an out of range
6791 subscript), or a wild jump (from an out of range case value). Overflow
6792 checking is also quite expensive in time and space, since in general it
6793 requires the use of double length arithmetic.
6795 Note again that @option{-gnato} is off by default, so overflow checking is
6796 not performed in default mode. This means that out of the box, with the
6797 default settings, GNAT does not do all the checks expected from the
6798 language description in the Ada Reference Manual. If you want all constraint
6799 checks to be performed, as described in this Manual, then you must
6800 explicitly use the -gnato switch either on the @command{gnatmake} or
6801 @command{gcc} command.
6804 @cindex @option{-gnatE} (@command{gcc})
6805 @cindex Elaboration checks
6806 @cindex Check, elaboration
6807 Enables dynamic checks for access-before-elaboration
6808 on subprogram calls and generic instantiations.
6809 Note that @option{-gnatE} is not necessary for safety, because in the
6810 default mode, GNAT ensures statically that the checks would not fail.
6811 For full details of the effect and use of this switch,
6812 @xref{Compiling Using gcc}.
6815 @cindex @option{-fstack-check} (@command{gcc})
6816 @cindex Stack Overflow Checking
6817 @cindex Checks, stack overflow checking
6818 Activates stack overflow checking. For full details of the effect and use of
6819 this switch see @ref{Stack Overflow Checking}.
6824 The setting of these switches only controls the default setting of the
6825 checks. You may modify them using either @code{Suppress} (to remove
6826 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6829 @node Using gcc for Syntax Checking
6830 @subsection Using @command{gcc} for Syntax Checking
6833 @cindex @option{-gnats} (@command{gcc})
6837 The @code{s} stands for ``syntax''.
6840 Run GNAT in syntax checking only mode. For
6841 example, the command
6844 $ gcc -c -gnats x.adb
6848 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6849 series of files in a single command
6851 , and can use wild cards to specify such a group of files.
6852 Note that you must specify the @option{-c} (compile
6853 only) flag in addition to the @option{-gnats} flag.
6856 You may use other switches in conjunction with @option{-gnats}. In
6857 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6858 format of any generated error messages.
6860 When the source file is empty or contains only empty lines and/or comments,
6861 the output is a warning:
6864 $ gcc -c -gnats -x ada toto.txt
6865 toto.txt:1:01: warning: empty file, contains no compilation units
6869 Otherwise, the output is simply the error messages, if any. No object file or
6870 ALI file is generated by a syntax-only compilation. Also, no units other
6871 than the one specified are accessed. For example, if a unit @code{X}
6872 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6873 check only mode does not access the source file containing unit
6876 @cindex Multiple units, syntax checking
6877 Normally, GNAT allows only a single unit in a source file. However, this
6878 restriction does not apply in syntax-check-only mode, and it is possible
6879 to check a file containing multiple compilation units concatenated
6880 together. This is primarily used by the @code{gnatchop} utility
6881 (@pxref{Renaming Files Using gnatchop}).
6884 @node Using gcc for Semantic Checking
6885 @subsection Using @command{gcc} for Semantic Checking
6888 @cindex @option{-gnatc} (@command{gcc})
6892 The @code{c} stands for ``check''.
6894 Causes the compiler to operate in semantic check mode,
6895 with full checking for all illegalities specified in the
6896 Ada Reference Manual, but without generation of any object code
6897 (no object file is generated).
6899 Because dependent files must be accessed, you must follow the GNAT
6900 semantic restrictions on file structuring to operate in this mode:
6904 The needed source files must be accessible
6905 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6908 Each file must contain only one compilation unit.
6911 The file name and unit name must match (@pxref{File Naming Rules}).
6914 The output consists of error messages as appropriate. No object file is
6915 generated. An @file{ALI} file is generated for use in the context of
6916 cross-reference tools, but this file is marked as not being suitable
6917 for binding (since no object file is generated).
6918 The checking corresponds exactly to the notion of
6919 legality in the Ada Reference Manual.
6921 Any unit can be compiled in semantics-checking-only mode, including
6922 units that would not normally be compiled (subunits,
6923 and specifications where a separate body is present).
6926 @node Compiling Different Versions of Ada
6927 @subsection Compiling Different Versions of Ada
6930 The switches described in this section allow you to explicitly specify
6931 the version of the Ada language that your programs are written in.
6932 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6933 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6934 indicate Ada 83 compatibility mode.
6937 @cindex Compatibility with Ada 83
6939 @item -gnat83 (Ada 83 Compatibility Mode)
6940 @cindex @option{-gnat83} (@command{gcc})
6941 @cindex ACVC, Ada 83 tests
6945 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6946 specifies that the program is to be compiled in Ada 83 mode. With
6947 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6948 semantics where this can be done easily.
6949 It is not possible to guarantee this switch does a perfect
6950 job; some subtle tests, such as are
6951 found in earlier ACVC tests (and that have been removed from the ACATS suite
6952 for Ada 95), might not compile correctly.
6953 Nevertheless, this switch may be useful in some circumstances, for example
6954 where, due to contractual reasons, existing code needs to be maintained
6955 using only Ada 83 features.
6957 With few exceptions (most notably the need to use @code{<>} on
6958 @cindex Generic formal parameters
6959 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6960 reserved words, and the use of packages
6961 with optional bodies), it is not necessary to specify the
6962 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6963 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6964 a correct Ada 83 program is usually also a correct program
6965 in these later versions of the language standard.
6966 For further information, please refer to @ref{Compatibility and Porting Guide}.
6968 @item -gnat95 (Ada 95 mode)
6969 @cindex @option{-gnat95} (@command{gcc})
6973 This switch directs the compiler to implement the Ada 95 version of the
6975 Since Ada 95 is almost completely upwards
6976 compatible with Ada 83, Ada 83 programs may generally be compiled using
6977 this switch (see the description of the @option{-gnat83} switch for further
6978 information about Ada 83 mode).
6979 If an Ada 2005 program is compiled in Ada 95 mode,
6980 uses of the new Ada 2005 features will cause error
6981 messages or warnings.
6983 This switch also can be used to cancel the effect of a previous
6984 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6985 switch earlier in the command line.
6987 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6988 @cindex @option{-gnat05} (@command{gcc})
6989 @cindex @option{-gnat2005} (@command{gcc})
6990 @cindex Ada 2005 mode
6993 This switch directs the compiler to implement the Ada 2005 version of the
6994 language, as documented in the official Ada standards document.
6995 Since Ada 2005 is almost completely upwards
6996 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6997 may generally be compiled using this switch (see the description of the
6998 @option{-gnat83} and @option{-gnat95} switches for further
7002 Note that even though Ada 2005 is the current official version of the
7003 language, GNAT still compiles in Ada 95 mode by default, so if you are
7004 using Ada 2005 features in your program, you must use this switch (or
7005 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7008 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7009 @cindex @option{-gnat12} (@command{gcc})
7010 @cindex @option{-gnat2012} (@command{gcc})
7011 @cindex Ada 2012 mode
7014 This switch directs the compiler to implement the Ada 2012 version of the
7016 Since Ada 2012 is almost completely upwards
7017 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7018 Ada 83 and Ada 95 programs
7019 may generally be compiled using this switch (see the description of the
7020 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7021 for further information).
7023 For information about the approved ``Ada Issues'' that have been incorporated
7024 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7025 Included with GNAT releases is a file @file{features-ada12} that describes
7026 the set of implemented Ada 2012 features.
7028 @item -gnatX (Enable GNAT Extensions)
7029 @cindex @option{-gnatX} (@command{gcc})
7030 @cindex Ada language extensions
7031 @cindex GNAT extensions
7034 This switch directs the compiler to implement the latest version of the
7035 language (currently Ada 2012) and also to enable certain GNAT implementation
7036 extensions that are not part of any Ada standard. For a full list of these
7037 extensions, see the GNAT reference manual.
7041 @node Character Set Control
7042 @subsection Character Set Control
7044 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7045 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7048 Normally GNAT recognizes the Latin-1 character set in source program
7049 identifiers, as described in the Ada Reference Manual.
7051 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7052 single character ^^or word^ indicating the character set, as follows:
7056 ISO 8859-1 (Latin-1) identifiers
7059 ISO 8859-2 (Latin-2) letters allowed in identifiers
7062 ISO 8859-3 (Latin-3) letters allowed in identifiers
7065 ISO 8859-4 (Latin-4) letters allowed in identifiers
7068 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7071 ISO 8859-15 (Latin-9) letters allowed in identifiers
7074 IBM PC letters (code page 437) allowed in identifiers
7077 IBM PC letters (code page 850) allowed in identifiers
7079 @item ^f^FULL_UPPER^
7080 Full upper-half codes allowed in identifiers
7083 No upper-half codes allowed in identifiers
7086 Wide-character codes (that is, codes greater than 255)
7087 allowed in identifiers
7090 @xref{Foreign Language Representation}, for full details on the
7091 implementation of these character sets.
7093 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7094 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7095 Specify the method of encoding for wide characters.
7096 @var{e} is one of the following:
7101 Hex encoding (brackets coding also recognized)
7104 Upper half encoding (brackets encoding also recognized)
7107 Shift/JIS encoding (brackets encoding also recognized)
7110 EUC encoding (brackets encoding also recognized)
7113 UTF-8 encoding (brackets encoding also recognized)
7116 Brackets encoding only (default value)
7118 For full details on these encoding
7119 methods see @ref{Wide Character Encodings}.
7120 Note that brackets coding is always accepted, even if one of the other
7121 options is specified, so for example @option{-gnatW8} specifies that both
7122 brackets and UTF-8 encodings will be recognized. The units that are
7123 with'ed directly or indirectly will be scanned using the specified
7124 representation scheme, and so if one of the non-brackets scheme is
7125 used, it must be used consistently throughout the program. However,
7126 since brackets encoding is always recognized, it may be conveniently
7127 used in standard libraries, allowing these libraries to be used with
7128 any of the available coding schemes.
7131 If no @option{-gnatW?} parameter is present, then the default
7132 representation is normally Brackets encoding only. However, if the
7133 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7134 byte order mark or BOM for UTF-8), then these three characters are
7135 skipped and the default representation for the file is set to UTF-8.
7137 Note that the wide character representation that is specified (explicitly
7138 or by default) for the main program also acts as the default encoding used
7139 for Wide_Text_IO files if not specifically overridden by a WCEM form
7143 @node File Naming Control
7144 @subsection File Naming Control
7147 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7148 @cindex @option{-gnatk} (@command{gcc})
7149 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7150 1-999, indicates the maximum allowable length of a file name (not
7151 including the @file{.ads} or @file{.adb} extension). The default is not
7152 to enable file name krunching.
7154 For the source file naming rules, @xref{File Naming Rules}.
7157 @node Subprogram Inlining Control
7158 @subsection Subprogram Inlining Control
7163 @cindex @option{-gnatn} (@command{gcc})
7165 The @code{n} here is intended to suggest the first syllable of the
7168 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7169 inlining to actually occur, optimization must be enabled. To enable
7170 inlining of subprograms specified by pragma @code{Inline},
7171 you must also specify this switch.
7172 In the absence of this switch, GNAT does not attempt
7173 inlining and does not need to access the bodies of
7174 subprograms for which @code{pragma Inline} is specified if they are not
7175 in the current unit.
7177 If you specify this switch the compiler will access these bodies,
7178 creating an extra source dependency for the resulting object file, and
7179 where possible, the call will be inlined.
7180 For further details on when inlining is possible
7181 see @ref{Inlining of Subprograms}.
7184 @cindex @option{-gnatN} (@command{gcc})
7185 This switch activates front-end inlining which also
7186 generates additional dependencies.
7188 When using a gcc-based back end (in practice this means using any version
7189 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7190 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7191 Historically front end inlining was more extensive than the gcc back end
7192 inlining, but that is no longer the case.
7195 @node Auxiliary Output Control
7196 @subsection Auxiliary Output Control
7200 @cindex @option{-gnatt} (@command{gcc})
7201 @cindex Writing internal trees
7202 @cindex Internal trees, writing to file
7203 Causes GNAT to write the internal tree for a unit to a file (with the
7204 extension @file{.adt}.
7205 This not normally required, but is used by separate analysis tools.
7207 these tools do the necessary compilations automatically, so you should
7208 not have to specify this switch in normal operation.
7209 Note that the combination of switches @option{-gnatct}
7210 generates a tree in the form required by ASIS applications.
7213 @cindex @option{-gnatu} (@command{gcc})
7214 Print a list of units required by this compilation on @file{stdout}.
7215 The listing includes all units on which the unit being compiled depends
7216 either directly or indirectly.
7219 @item -pass-exit-codes
7220 @cindex @option{-pass-exit-codes} (@command{gcc})
7221 If this switch is not used, the exit code returned by @command{gcc} when
7222 compiling multiple files indicates whether all source files have
7223 been successfully used to generate object files or not.
7225 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7226 exit status and allows an integrated development environment to better
7227 react to a compilation failure. Those exit status are:
7231 There was an error in at least one source file.
7233 At least one source file did not generate an object file.
7235 The compiler died unexpectedly (internal error for example).
7237 An object file has been generated for every source file.
7242 @node Debugging Control
7243 @subsection Debugging Control
7247 @cindex Debugging options
7250 @cindex @option{-gnatd} (@command{gcc})
7251 Activate internal debugging switches. @var{x} is a letter or digit, or
7252 string of letters or digits, which specifies the type of debugging
7253 outputs desired. Normally these are used only for internal development
7254 or system debugging purposes. You can find full documentation for these
7255 switches in the body of the @code{Debug} unit in the compiler source
7256 file @file{debug.adb}.
7260 @cindex @option{-gnatG} (@command{gcc})
7261 This switch causes the compiler to generate auxiliary output containing
7262 a pseudo-source listing of the generated expanded code. Like most Ada
7263 compilers, GNAT works by first transforming the high level Ada code into
7264 lower level constructs. For example, tasking operations are transformed
7265 into calls to the tasking run-time routines. A unique capability of GNAT
7266 is to list this expanded code in a form very close to normal Ada source.
7267 This is very useful in understanding the implications of various Ada
7268 usage on the efficiency of the generated code. There are many cases in
7269 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7270 generate a lot of run-time code. By using @option{-gnatG} you can identify
7271 these cases, and consider whether it may be desirable to modify the coding
7272 approach to improve efficiency.
7274 The optional parameter @code{nn} if present after -gnatG specifies an
7275 alternative maximum line length that overrides the normal default of 72.
7276 This value is in the range 40-999999, values less than 40 being silently
7277 reset to 40. The equal sign is optional.
7279 The format of the output is very similar to standard Ada source, and is
7280 easily understood by an Ada programmer. The following special syntactic
7281 additions correspond to low level features used in the generated code that
7282 do not have any exact analogies in pure Ada source form. The following
7283 is a partial list of these special constructions. See the spec
7284 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7286 If the switch @option{-gnatL} is used in conjunction with
7287 @cindex @option{-gnatL} (@command{gcc})
7288 @option{-gnatG}, then the original source lines are interspersed
7289 in the expanded source (as comment lines with the original line number).
7292 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7293 Shows the storage pool being used for an allocator.
7295 @item at end @var{procedure-name};
7296 Shows the finalization (cleanup) procedure for a scope.
7298 @item (if @var{expr} then @var{expr} else @var{expr})
7299 Conditional expression equivalent to the @code{x?y:z} construction in C.
7301 @item @var{target}^^^(@var{source})
7302 A conversion with floating-point truncation instead of rounding.
7304 @item @var{target}?(@var{source})
7305 A conversion that bypasses normal Ada semantic checking. In particular
7306 enumeration types and fixed-point types are treated simply as integers.
7308 @item @var{target}?^^^(@var{source})
7309 Combines the above two cases.
7311 @item @var{x} #/ @var{y}
7312 @itemx @var{x} #mod @var{y}
7313 @itemx @var{x} #* @var{y}
7314 @itemx @var{x} #rem @var{y}
7315 A division or multiplication of fixed-point values which are treated as
7316 integers without any kind of scaling.
7318 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7319 Shows the storage pool associated with a @code{free} statement.
7321 @item [subtype or type declaration]
7322 Used to list an equivalent declaration for an internally generated
7323 type that is referenced elsewhere in the listing.
7325 @c @item freeze @var{type-name} @ovar{actions}
7326 @c Expanding @ovar macro inline (explanation in macro def comments)
7327 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7328 Shows the point at which @var{type-name} is frozen, with possible
7329 associated actions to be performed at the freeze point.
7331 @item reference @var{itype}
7332 Reference (and hence definition) to internal type @var{itype}.
7334 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7335 Intrinsic function call.
7337 @item @var{label-name} : label
7338 Declaration of label @var{labelname}.
7340 @item #$ @var{subprogram-name}
7341 An implicit call to a run-time support routine
7342 (to meet the requirement of H.3.1(9) in a
7345 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7346 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7347 @var{expr}, but handled more efficiently).
7349 @item [constraint_error]
7350 Raise the @code{Constraint_Error} exception.
7352 @item @var{expression}'reference
7353 A pointer to the result of evaluating @var{expression}.
7355 @item @var{target-type}!(@var{source-expression})
7356 An unchecked conversion of @var{source-expression} to @var{target-type}.
7358 @item [@var{numerator}/@var{denominator}]
7359 Used to represent internal real literals (that) have no exact
7360 representation in base 2-16 (for example, the result of compile time
7361 evaluation of the expression 1.0/27.0).
7365 @cindex @option{-gnatD} (@command{gcc})
7366 When used in conjunction with @option{-gnatG}, this switch causes
7367 the expanded source, as described above for
7368 @option{-gnatG} to be written to files with names
7369 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7370 instead of to the standard output file. For
7371 example, if the source file name is @file{hello.adb}, then a file
7372 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7373 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7374 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7375 you to do source level debugging using the generated code which is
7376 sometimes useful for complex code, for example to find out exactly
7377 which part of a complex construction raised an exception. This switch
7378 also suppress generation of cross-reference information (see
7379 @option{-gnatx}) since otherwise the cross-reference information
7380 would refer to the @file{^.dg^.DG^} file, which would cause
7381 confusion since this is not the original source file.
7383 Note that @option{-gnatD} actually implies @option{-gnatG}
7384 automatically, so it is not necessary to give both options.
7385 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7387 If the switch @option{-gnatL} is used in conjunction with
7388 @cindex @option{-gnatL} (@command{gcc})
7389 @option{-gnatDG}, then the original source lines are interspersed
7390 in the expanded source (as comment lines with the original line number).
7392 The optional parameter @code{nn} if present after -gnatD specifies an
7393 alternative maximum line length that overrides the normal default of 72.
7394 This value is in the range 40-999999, values less than 40 being silently
7395 reset to 40. The equal sign is optional.
7398 @cindex @option{-gnatr} (@command{gcc})
7399 @cindex pragma Restrictions
7400 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7401 so that violation of restrictions causes warnings rather than illegalities.
7402 This is useful during the development process when new restrictions are added
7403 or investigated. The switch also causes pragma Profile to be treated as
7404 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7405 restriction warnings rather than restrictions.
7408 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7409 @cindex @option{-gnatR} (@command{gcc})
7410 This switch controls output from the compiler of a listing showing
7411 representation information for declared types and objects. For
7412 @option{-gnatR0}, no information is output (equivalent to omitting
7413 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7414 so @option{-gnatR} with no parameter has the same effect), size and alignment
7415 information is listed for declared array and record types. For
7416 @option{-gnatR2}, size and alignment information is listed for all
7417 declared types and objects. Finally @option{-gnatR3} includes symbolic
7418 expressions for values that are computed at run time for
7419 variant records. These symbolic expressions have a mostly obvious
7420 format with #n being used to represent the value of the n'th
7421 discriminant. See source files @file{repinfo.ads/adb} in the
7422 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7423 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7424 the output is to a file with the name @file{^file.rep^file_REP^} where
7425 file is the name of the corresponding source file.
7428 @item /REPRESENTATION_INFO
7429 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7430 This qualifier controls output from the compiler of a listing showing
7431 representation information for declared types and objects. For
7432 @option{/REPRESENTATION_INFO=NONE}, no information is output
7433 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7434 @option{/REPRESENTATION_INFO} without option is equivalent to
7435 @option{/REPRESENTATION_INFO=ARRAYS}.
7436 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7437 information is listed for declared array and record types. For
7438 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7439 is listed for all expression information for values that are computed
7440 at run time for variant records. These symbolic expressions have a mostly
7441 obvious format with #n being used to represent the value of the n'th
7442 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7443 @code{GNAT} sources for full details on the format of
7444 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7445 If _FILE is added at the end of an option
7446 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7447 then the output is to a file with the name @file{file_REP} where
7448 file is the name of the corresponding source file.
7450 Note that it is possible for record components to have zero size. In
7451 this case, the component clause uses an obvious extension of permitted
7452 Ada syntax, for example @code{at 0 range 0 .. -1}.
7454 Representation information requires that code be generated (since it is the
7455 code generator that lays out complex data structures). If an attempt is made
7456 to output representation information when no code is generated, for example
7457 when a subunit is compiled on its own, then no information can be generated
7458 and the compiler outputs a message to this effect.
7461 @cindex @option{-gnatS} (@command{gcc})
7462 The use of the switch @option{-gnatS} for an
7463 Ada compilation will cause the compiler to output a
7464 representation of package Standard in a form very
7465 close to standard Ada. It is not quite possible to
7466 do this entirely in standard Ada (since new
7467 numeric base types cannot be created in standard
7468 Ada), but the output is easily
7469 readable to any Ada programmer, and is useful to
7470 determine the characteristics of target dependent
7471 types in package Standard.
7474 @cindex @option{-gnatx} (@command{gcc})
7475 Normally the compiler generates full cross-referencing information in
7476 the @file{ALI} file. This information is used by a number of tools,
7477 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7478 suppresses this information. This saves some space and may slightly
7479 speed up compilation, but means that these tools cannot be used.
7482 @node Exception Handling Control
7483 @subsection Exception Handling Control
7486 GNAT uses two methods for handling exceptions at run-time. The
7487 @code{setjmp/longjmp} method saves the context when entering
7488 a frame with an exception handler. Then when an exception is
7489 raised, the context can be restored immediately, without the
7490 need for tracing stack frames. This method provides very fast
7491 exception propagation, but introduces significant overhead for
7492 the use of exception handlers, even if no exception is raised.
7494 The other approach is called ``zero cost'' exception handling.
7495 With this method, the compiler builds static tables to describe
7496 the exception ranges. No dynamic code is required when entering
7497 a frame containing an exception handler. When an exception is
7498 raised, the tables are used to control a back trace of the
7499 subprogram invocation stack to locate the required exception
7500 handler. This method has considerably poorer performance for
7501 the propagation of exceptions, but there is no overhead for
7502 exception handlers if no exception is raised. Note that in this
7503 mode and in the context of mixed Ada and C/C++ programming,
7504 to propagate an exception through a C/C++ code, the C/C++ code
7505 must be compiled with the @option{-funwind-tables} GCC's
7508 The following switches may be used to control which of the
7509 two exception handling methods is used.
7515 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7516 This switch causes the setjmp/longjmp run-time (when available) to be used
7517 for exception handling. If the default
7518 mechanism for the target is zero cost exceptions, then
7519 this switch can be used to modify this default, and must be
7520 used for all units in the partition.
7521 This option is rarely used. One case in which it may be
7522 advantageous is if you have an application where exception
7523 raising is common and the overall performance of the
7524 application is improved by favoring exception propagation.
7527 @cindex @option{--RTS=zcx} (@command{gnatmake})
7528 @cindex Zero Cost Exceptions
7529 This switch causes the zero cost approach to be used
7530 for exception handling. If this is the default mechanism for the
7531 target (see below), then this switch is unneeded. If the default
7532 mechanism for the target is setjmp/longjmp exceptions, then
7533 this switch can be used to modify this default, and must be
7534 used for all units in the partition.
7535 This option can only be used if the zero cost approach
7536 is available for the target in use, otherwise it will generate an error.
7540 The same option @option{--RTS} must be used both for @command{gcc}
7541 and @command{gnatbind}. Passing this option to @command{gnatmake}
7542 (@pxref{Switches for gnatmake}) will ensure the required consistency
7543 through the compilation and binding steps.
7545 @node Units to Sources Mapping Files
7546 @subsection Units to Sources Mapping Files
7550 @item -gnatem=@var{path}
7551 @cindex @option{-gnatem} (@command{gcc})
7552 A mapping file is a way to communicate to the compiler two mappings:
7553 from unit names to file names (without any directory information) and from
7554 file names to path names (with full directory information). These mappings
7555 are used by the compiler to short-circuit the path search.
7557 The use of mapping files is not required for correct operation of the
7558 compiler, but mapping files can improve efficiency, particularly when
7559 sources are read over a slow network connection. In normal operation,
7560 you need not be concerned with the format or use of mapping files,
7561 and the @option{-gnatem} switch is not a switch that you would use
7562 explicitly. It is intended primarily for use by automatic tools such as
7563 @command{gnatmake} running under the project file facility. The
7564 description here of the format of mapping files is provided
7565 for completeness and for possible use by other tools.
7567 A mapping file is a sequence of sets of three lines. In each set, the
7568 first line is the unit name, in lower case, with @code{%s} appended
7569 for specs and @code{%b} appended for bodies; the second line is the
7570 file name; and the third line is the path name.
7576 /gnat/project1/sources/main.2.ada
7579 When the switch @option{-gnatem} is specified, the compiler will
7580 create in memory the two mappings from the specified file. If there is
7581 any problem (nonexistent file, truncated file or duplicate entries),
7582 no mapping will be created.
7584 Several @option{-gnatem} switches may be specified; however, only the
7585 last one on the command line will be taken into account.
7587 When using a project file, @command{gnatmake} creates a temporary
7588 mapping file and communicates it to the compiler using this switch.
7592 @node Integrated Preprocessing
7593 @subsection Integrated Preprocessing
7596 GNAT sources may be preprocessed immediately before compilation.
7597 In this case, the actual
7598 text of the source is not the text of the source file, but is derived from it
7599 through a process called preprocessing. Integrated preprocessing is specified
7600 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7601 indicates, through a text file, the preprocessing data to be used.
7602 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7605 Note that when integrated preprocessing is used, the output from the
7606 preprocessor is not written to any external file. Instead it is passed
7607 internally to the compiler. If you need to preserve the result of
7608 preprocessing in a file, then you should use @command{gnatprep}
7609 to perform the desired preprocessing in stand-alone mode.
7612 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7613 used when Integrated Preprocessing is used. The reason is that preprocessing
7614 with another Preprocessing Data file without changing the sources will
7615 not trigger recompilation without this switch.
7618 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7619 always trigger recompilation for sources that are preprocessed,
7620 because @command{gnatmake} cannot compute the checksum of the source after
7624 The actual preprocessing function is described in details in section
7625 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7626 preprocessing is triggered and parameterized.
7630 @item -gnatep=@var{file}
7631 @cindex @option{-gnatep} (@command{gcc})
7632 This switch indicates to the compiler the file name (without directory
7633 information) of the preprocessor data file to use. The preprocessor data file
7634 should be found in the source directories.
7637 A preprocessing data file is a text file with significant lines indicating
7638 how should be preprocessed either a specific source or all sources not
7639 mentioned in other lines. A significant line is a nonempty, non-comment line.
7640 Comments are similar to Ada comments.
7643 Each significant line starts with either a literal string or the character '*'.
7644 A literal string is the file name (without directory information) of the source
7645 to preprocess. A character '*' indicates the preprocessing for all the sources
7646 that are not specified explicitly on other lines (order of the lines is not
7647 significant). It is an error to have two lines with the same file name or two
7648 lines starting with the character '*'.
7651 After the file name or the character '*', another optional literal string
7652 indicating the file name of the definition file to be used for preprocessing
7653 (@pxref{Form of Definitions File}). The definition files are found by the
7654 compiler in one of the source directories. In some cases, when compiling
7655 a source in a directory other than the current directory, if the definition
7656 file is in the current directory, it may be necessary to add the current
7657 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7658 the compiler would not find the definition file.
7661 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7662 be found. Those ^switches^switches^ are:
7667 Causes both preprocessor lines and the lines deleted by
7668 preprocessing to be replaced by blank lines, preserving the line number.
7669 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7670 it cancels the effect of @option{-c}.
7673 Causes both preprocessor lines and the lines deleted
7674 by preprocessing to be retained as comments marked
7675 with the special string ``@code{--! }''.
7677 @item -Dsymbol=value
7678 Define or redefine a symbol, associated with value. A symbol is an Ada
7679 identifier, or an Ada reserved word, with the exception of @code{if},
7680 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7681 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7682 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7683 same name defined in a definition file.
7686 Causes a sorted list of symbol names and values to be
7687 listed on the standard output file.
7690 Causes undefined symbols to be treated as having the value @code{FALSE}
7692 of a preprocessor test. In the absence of this option, an undefined symbol in
7693 a @code{#if} or @code{#elsif} test will be treated as an error.
7698 Examples of valid lines in a preprocessor data file:
7701 "toto.adb" "prep.def" -u
7702 -- preprocess "toto.adb", using definition file "prep.def",
7703 -- undefined symbol are False.
7706 -- preprocess all other sources without a definition file;
7707 -- suppressed lined are commented; symbol VERSION has the value V101.
7709 "titi.adb" "prep2.def" -s
7710 -- preprocess "titi.adb", using definition file "prep2.def";
7711 -- list all symbols with their values.
7714 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7715 @cindex @option{-gnateD} (@command{gcc})
7716 Define or redefine a preprocessing symbol, associated with value. If no value
7717 is given on the command line, then the value of the symbol is @code{True}.
7718 A symbol is an identifier, following normal Ada (case-insensitive)
7719 rules for its syntax, and value is any sequence (including an empty sequence)
7720 of characters from the set (letters, digits, period, underline).
7721 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7722 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7725 A symbol declared with this ^switch^switch^ on the command line replaces a
7726 symbol with the same name either in a definition file or specified with a
7727 ^switch^switch^ -D in the preprocessor data file.
7730 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7733 When integrated preprocessing is performed and the preprocessor modifies
7734 the source text, write the result of this preprocessing into a file
7735 <source>^.prep^_prep^.
7739 @node Code Generation Control
7740 @subsection Code Generation Control
7744 The GCC technology provides a wide range of target dependent
7745 @option{-m} switches for controlling
7746 details of code generation with respect to different versions of
7747 architectures. This includes variations in instruction sets (e.g.@:
7748 different members of the power pc family), and different requirements
7749 for optimal arrangement of instructions (e.g.@: different members of
7750 the x86 family). The list of available @option{-m} switches may be
7751 found in the GCC documentation.
7753 Use of these @option{-m} switches may in some cases result in improved
7756 The GNAT Pro technology is tested and qualified without any
7757 @option{-m} switches,
7758 so generally the most reliable approach is to avoid the use of these
7759 switches. However, we generally expect most of these switches to work
7760 successfully with GNAT Pro, and many customers have reported successful
7761 use of these options.
7763 Our general advice is to avoid the use of @option{-m} switches unless
7764 special needs lead to requirements in this area. In particular,
7765 there is no point in using @option{-m} switches to improve performance
7766 unless you actually see a performance improvement.
7770 @subsection Return Codes
7771 @cindex Return Codes
7772 @cindex @option{/RETURN_CODES=VMS}
7775 On VMS, GNAT compiled programs return POSIX-style codes by default,
7776 e.g.@: @option{/RETURN_CODES=POSIX}.
7778 To enable VMS style return codes, use GNAT BIND and LINK with the option
7779 @option{/RETURN_CODES=VMS}. For example:
7782 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7783 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7787 Programs built with /RETURN_CODES=VMS are suitable to be called in
7788 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7789 are suitable for spawning with appropriate GNAT RTL routines.
7793 @node Search Paths and the Run-Time Library (RTL)
7794 @section Search Paths and the Run-Time Library (RTL)
7797 With the GNAT source-based library system, the compiler must be able to
7798 find source files for units that are needed by the unit being compiled.
7799 Search paths are used to guide this process.
7801 The compiler compiles one source file whose name must be given
7802 explicitly on the command line. In other words, no searching is done
7803 for this file. To find all other source files that are needed (the most
7804 common being the specs of units), the compiler examines the following
7805 directories, in the following order:
7809 The directory containing the source file of the main unit being compiled
7810 (the file name on the command line).
7813 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7814 @command{gcc} command line, in the order given.
7817 @findex ADA_PRJ_INCLUDE_FILE
7818 Each of the directories listed in the text file whose name is given
7819 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7822 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7823 driver when project files are used. It should not normally be set
7827 @findex ADA_INCLUDE_PATH
7828 Each of the directories listed in the value of the
7829 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7831 Construct this value
7832 exactly as the @env{PATH} environment variable: a list of directory
7833 names separated by colons (semicolons when working with the NT version).
7836 Normally, define this value as a logical name containing a comma separated
7837 list of directory names.
7839 This variable can also be defined by means of an environment string
7840 (an argument to the HP C exec* set of functions).
7844 DEFINE ANOTHER_PATH FOO:[BAG]
7845 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7848 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7849 first, followed by the standard Ada
7850 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7851 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7852 (Text_IO, Sequential_IO, etc)
7853 instead of the standard Ada packages. Thus, in order to get the standard Ada
7854 packages by default, ADA_INCLUDE_PATH must be redefined.
7858 The content of the @file{ada_source_path} file which is part of the GNAT
7859 installation tree and is used to store standard libraries such as the
7860 GNAT Run Time Library (RTL) source files.
7862 @ref{Installing a library}
7867 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7868 inhibits the use of the directory
7869 containing the source file named in the command line. You can still
7870 have this directory on your search path, but in this case it must be
7871 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7873 Specifying the switch @option{-nostdinc}
7874 inhibits the search of the default location for the GNAT Run Time
7875 Library (RTL) source files.
7877 The compiler outputs its object files and ALI files in the current
7880 Caution: The object file can be redirected with the @option{-o} switch;
7881 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7882 so the @file{ALI} file will not go to the right place. Therefore, you should
7883 avoid using the @option{-o} switch.
7887 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7888 children make up the GNAT RTL, together with the simple @code{System.IO}
7889 package used in the @code{"Hello World"} example. The sources for these units
7890 are needed by the compiler and are kept together in one directory. Not
7891 all of the bodies are needed, but all of the sources are kept together
7892 anyway. In a normal installation, you need not specify these directory
7893 names when compiling or binding. Either the environment variables or
7894 the built-in defaults cause these files to be found.
7896 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7897 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7898 consisting of child units of @code{GNAT}. This is a collection of generally
7899 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7900 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7902 Besides simplifying access to the RTL, a major use of search paths is
7903 in compiling sources from multiple directories. This can make
7904 development environments much more flexible.
7906 @node Order of Compilation Issues
7907 @section Order of Compilation Issues
7910 If, in our earlier example, there was a spec for the @code{hello}
7911 procedure, it would be contained in the file @file{hello.ads}; yet this
7912 file would not have to be explicitly compiled. This is the result of the
7913 model we chose to implement library management. Some of the consequences
7914 of this model are as follows:
7918 There is no point in compiling specs (except for package
7919 specs with no bodies) because these are compiled as needed by clients. If
7920 you attempt a useless compilation, you will receive an error message.
7921 It is also useless to compile subunits because they are compiled as needed
7925 There are no order of compilation requirements: performing a
7926 compilation never obsoletes anything. The only way you can obsolete
7927 something and require recompilations is to modify one of the
7928 source files on which it depends.
7931 There is no library as such, apart from the ALI files
7932 (@pxref{The Ada Library Information Files}, for information on the format
7933 of these files). For now we find it convenient to create separate ALI files,
7934 but eventually the information therein may be incorporated into the object
7938 When you compile a unit, the source files for the specs of all units
7939 that it @code{with}'s, all its subunits, and the bodies of any generics it
7940 instantiates must be available (reachable by the search-paths mechanism
7941 described above), or you will receive a fatal error message.
7948 The following are some typical Ada compilation command line examples:
7951 @item $ gcc -c xyz.adb
7952 Compile body in file @file{xyz.adb} with all default options.
7955 @item $ gcc -c -O2 -gnata xyz-def.adb
7958 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7961 Compile the child unit package in file @file{xyz-def.adb} with extensive
7962 optimizations, and pragma @code{Assert}/@code{Debug} statements
7965 @item $ gcc -c -gnatc abc-def.adb
7966 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7970 @node Binding Using gnatbind
7971 @chapter Binding Using @code{gnatbind}
7975 * Running gnatbind::
7976 * Switches for gnatbind::
7977 * Command-Line Access::
7978 * Search Paths for gnatbind::
7979 * Examples of gnatbind Usage::
7983 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7984 to bind compiled GNAT objects.
7986 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7987 driver (see @ref{The GNAT Driver and Project Files}).
7989 The @code{gnatbind} program performs four separate functions:
7993 Checks that a program is consistent, in accordance with the rules in
7994 Chapter 10 of the Ada Reference Manual. In particular, error
7995 messages are generated if a program uses inconsistent versions of a
7999 Checks that an acceptable order of elaboration exists for the program
8000 and issues an error message if it cannot find an order of elaboration
8001 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8004 Generates a main program incorporating the given elaboration order.
8005 This program is a small Ada package (body and spec) that
8006 must be subsequently compiled
8007 using the GNAT compiler. The necessary compilation step is usually
8008 performed automatically by @command{gnatlink}. The two most important
8009 functions of this program
8010 are to call the elaboration routines of units in an appropriate order
8011 and to call the main program.
8014 Determines the set of object files required by the given main program.
8015 This information is output in the forms of comments in the generated program,
8016 to be read by the @command{gnatlink} utility used to link the Ada application.
8019 @node Running gnatbind
8020 @section Running @code{gnatbind}
8023 The form of the @code{gnatbind} command is
8026 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8027 @c Expanding @ovar macro inline (explanation in macro def comments)
8028 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8032 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8033 unit body. @code{gnatbind} constructs an Ada
8034 package in two files whose names are
8035 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8036 For example, if given the
8037 parameter @file{hello.ali}, for a main program contained in file
8038 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8039 and @file{b~hello.adb}.
8041 When doing consistency checking, the binder takes into consideration
8042 any source files it can locate. For example, if the binder determines
8043 that the given main program requires the package @code{Pack}, whose
8045 file is @file{pack.ali} and whose corresponding source spec file is
8046 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8047 (using the same search path conventions as previously described for the
8048 @command{gcc} command). If it can locate this source file, it checks that
8050 or source checksums of the source and its references to in @file{ALI} files
8051 match. In other words, any @file{ALI} files that mentions this spec must have
8052 resulted from compiling this version of the source file (or in the case
8053 where the source checksums match, a version close enough that the
8054 difference does not matter).
8056 @cindex Source files, use by binder
8057 The effect of this consistency checking, which includes source files, is
8058 that the binder ensures that the program is consistent with the latest
8059 version of the source files that can be located at bind time. Editing a
8060 source file without compiling files that depend on the source file cause
8061 error messages to be generated by the binder.
8063 For example, suppose you have a main program @file{hello.adb} and a
8064 package @code{P}, from file @file{p.ads} and you perform the following
8069 Enter @code{gcc -c hello.adb} to compile the main program.
8072 Enter @code{gcc -c p.ads} to compile package @code{P}.
8075 Edit file @file{p.ads}.
8078 Enter @code{gnatbind hello}.
8082 At this point, the file @file{p.ali} contains an out-of-date time stamp
8083 because the file @file{p.ads} has been edited. The attempt at binding
8084 fails, and the binder generates the following error messages:
8087 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8088 error: "p.ads" has been modified and must be recompiled
8092 Now both files must be recompiled as indicated, and then the bind can
8093 succeed, generating a main program. You need not normally be concerned
8094 with the contents of this file, but for reference purposes a sample
8095 binder output file is given in @ref{Example of Binder Output File}.
8097 In most normal usage, the default mode of @command{gnatbind} which is to
8098 generate the main package in Ada, as described in the previous section.
8099 In particular, this means that any Ada programmer can read and understand
8100 the generated main program. It can also be debugged just like any other
8101 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8102 @command{gnatbind} and @command{gnatlink}.
8104 @node Switches for gnatbind
8105 @section Switches for @command{gnatbind}
8108 The following switches are available with @code{gnatbind}; details will
8109 be presented in subsequent sections.
8112 * Consistency-Checking Modes::
8113 * Binder Error Message Control::
8114 * Elaboration Control::
8116 * Dynamic Allocation Control::
8117 * Binding with Non-Ada Main Programs::
8118 * Binding Programs with No Main Subprogram::
8125 @cindex @option{--version} @command{gnatbind}
8126 Display Copyright and version, then exit disregarding all other options.
8129 @cindex @option{--help} @command{gnatbind}
8130 If @option{--version} was not used, display usage, then exit disregarding
8134 @cindex @option{-a} @command{gnatbind}
8135 Indicates that, if supported by the platform, the adainit procedure should
8136 be treated as an initialisation routine by the linker (a constructor). This
8137 is intended to be used by the Project Manager to automatically initialize
8138 shared Stand-Alone Libraries.
8140 @item ^-aO^/OBJECT_SEARCH^
8141 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8142 Specify directory to be searched for ALI files.
8144 @item ^-aI^/SOURCE_SEARCH^
8145 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8146 Specify directory to be searched for source file.
8148 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8149 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8150 Output ALI list (to standard output or to the named file).
8152 @item ^-b^/REPORT_ERRORS=BRIEF^
8153 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8154 Generate brief messages to @file{stderr} even if verbose mode set.
8156 @item ^-c^/NOOUTPUT^
8157 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8158 Check only, no generation of binder output file.
8160 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8161 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8162 This switch can be used to change the default task stack size value
8163 to a specified size @var{nn}, which is expressed in bytes by default, or
8164 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8166 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8167 in effect, to completing all task specs with
8168 @smallexample @c ada
8169 pragma Storage_Size (nn);
8171 When they do not already have such a pragma.
8173 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8174 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8175 This switch can be used to change the default secondary stack size value
8176 to a specified size @var{nn}, which is expressed in bytes by default, or
8177 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8180 The secondary stack is used to deal with functions that return a variable
8181 sized result, for example a function returning an unconstrained
8182 String. There are two ways in which this secondary stack is allocated.
8184 For most targets, the secondary stack is growing on demand and is allocated
8185 as a chain of blocks in the heap. The -D option is not very
8186 relevant. It only give some control over the size of the allocated
8187 blocks (whose size is the minimum of the default secondary stack size value,
8188 and the actual size needed for the current allocation request).
8190 For certain targets, notably VxWorks 653,
8191 the secondary stack is allocated by carving off a fixed ratio chunk of the
8192 primary task stack. The -D option is used to define the
8193 size of the environment task's secondary stack.
8195 @item ^-e^/ELABORATION_DEPENDENCIES^
8196 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8197 Output complete list of elaboration-order dependencies.
8199 @item ^-E^/STORE_TRACEBACKS^
8200 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8201 Store tracebacks in exception occurrences when the target supports it.
8203 @c The following may get moved to an appendix
8204 This option is currently supported on the following targets:
8205 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8207 See also the packages @code{GNAT.Traceback} and
8208 @code{GNAT.Traceback.Symbolic} for more information.
8210 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8211 @command{gcc} option.
8214 @item ^-F^/FORCE_ELABS_FLAGS^
8215 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8216 Force the checks of elaboration flags. @command{gnatbind} does not normally
8217 generate checks of elaboration flags for the main executable, except when
8218 a Stand-Alone Library is used. However, there are cases when this cannot be
8219 detected by gnatbind. An example is importing an interface of a Stand-Alone
8220 Library through a pragma Import and only specifying through a linker switch
8221 this Stand-Alone Library. This switch is used to guarantee that elaboration
8222 flag checks are generated.
8225 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8226 Output usage (help) information
8228 @item ^-H32^/32_MALLOC^
8229 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8230 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8231 For further details see @ref{Dynamic Allocation Control}.
8233 @item ^-H64^/64_MALLOC^
8234 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8235 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8236 @cindex @code{__gnat_malloc}
8237 For further details see @ref{Dynamic Allocation Control}.
8240 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8241 Specify directory to be searched for source and ALI files.
8243 @item ^-I-^/NOCURRENT_DIRECTORY^
8244 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8245 Do not look for sources in the current directory where @code{gnatbind} was
8246 invoked, and do not look for ALI files in the directory containing the
8247 ALI file named in the @code{gnatbind} command line.
8249 @item ^-l^/ORDER_OF_ELABORATION^
8250 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8251 Output chosen elaboration order.
8253 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8254 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8255 Bind the units for library building. In this case the adainit and
8256 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8257 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8258 ^@var{xxx}final^@var{XXX}FINAL^.
8259 Implies ^-n^/NOCOMPILE^.
8261 (@xref{GNAT and Libraries}, for more details.)
8264 On OpenVMS, these init and final procedures are exported in uppercase
8265 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8266 the init procedure will be "TOTOINIT" and the exported name of the final
8267 procedure will be "TOTOFINAL".
8270 @item ^-Mxyz^/RENAME_MAIN=xyz^
8271 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8272 Rename generated main program from main to xyz. This option is
8273 supported on cross environments only.
8275 @item ^-m^/ERROR_LIMIT=^@var{n}
8276 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8277 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8278 in the range 1..999999. The default value if no switch is
8279 given is 9999. If the number of warnings reaches this limit, then a
8280 message is output and further warnings are suppressed, the bind
8281 continues in this case. If the number of errors reaches this
8282 limit, then a message is output and the bind is abandoned.
8283 A value of zero means that no limit is enforced. The equal
8287 Furthermore, under Windows, the sources pointed to by the libraries path
8288 set in the registry are not searched for.
8292 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8296 @cindex @option{-nostdinc} (@command{gnatbind})
8297 Do not look for sources in the system default directory.
8300 @cindex @option{-nostdlib} (@command{gnatbind})
8301 Do not look for library files in the system default directory.
8303 @item --RTS=@var{rts-path}
8304 @cindex @option{--RTS} (@code{gnatbind})
8305 Specifies the default location of the runtime library. Same meaning as the
8306 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8308 @item ^-o ^/OUTPUT=^@var{file}
8309 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8310 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8311 Note that if this option is used, then linking must be done manually,
8312 gnatlink cannot be used.
8314 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8315 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8316 Output object list (to standard output or to the named file).
8318 @item ^-p^/PESSIMISTIC_ELABORATION^
8319 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8320 Pessimistic (worst-case) elaboration order
8323 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8324 Generate binder file suitable for CodePeer.
8327 @cindex @option{^-R^-R^} (@command{gnatbind})
8328 Output closure source list.
8330 @item ^-s^/READ_SOURCES=ALL^
8331 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8332 Require all source files to be present.
8334 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8335 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8336 Specifies the value to be used when detecting uninitialized scalar
8337 objects with pragma Initialize_Scalars.
8338 The @var{xxx} ^string specified with the switch^option^ may be either
8340 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8341 @item ``@option{^lo^LOW^}'' for the lowest possible value
8342 @item ``@option{^hi^HIGH^}'' for the highest possible value
8343 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8344 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8347 In addition, you can specify @option{-Sev} to indicate that the value is
8348 to be set at run time. In this case, the program will look for an environment
8349 @cindex GNAT_INIT_SCALARS
8350 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8351 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8352 If no environment variable is found, or if it does not have a valid value,
8353 then the default is @option{in} (invalid values).
8357 @cindex @option{-static} (@code{gnatbind})
8358 Link against a static GNAT run time.
8361 @cindex @option{-shared} (@code{gnatbind})
8362 Link against a shared GNAT run time when available.
8365 @item ^-t^/NOTIME_STAMP_CHECK^
8366 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8367 Tolerate time stamp and other consistency errors
8369 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8370 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8371 Set the time slice value to @var{n} milliseconds. If the system supports
8372 the specification of a specific time slice value, then the indicated value
8373 is used. If the system does not support specific time slice values, but
8374 does support some general notion of round-robin scheduling, then any
8375 nonzero value will activate round-robin scheduling.
8377 A value of zero is treated specially. It turns off time
8378 slicing, and in addition, indicates to the tasking run time that the
8379 semantics should match as closely as possible the Annex D
8380 requirements of the Ada RM, and in particular sets the default
8381 scheduling policy to @code{FIFO_Within_Priorities}.
8383 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8384 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8385 Enable dynamic stack usage, with @var{n} results stored and displayed
8386 at program termination. A result is generated when a task
8387 terminates. Results that can't be stored are displayed on the fly, at
8388 task termination. This option is currently not supported on Itanium
8389 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8391 @item ^-v^/REPORT_ERRORS=VERBOSE^
8392 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8393 Verbose mode. Write error messages, header, summary output to
8398 @cindex @option{-w} (@code{gnatbind})
8399 Warning mode (@var{x}=s/e for suppress/treat as error)
8403 @item /WARNINGS=NORMAL
8404 @cindex @option{/WARNINGS} (@code{gnatbind})
8405 Normal warnings mode. Warnings are issued but ignored
8407 @item /WARNINGS=SUPPRESS
8408 @cindex @option{/WARNINGS} (@code{gnatbind})
8409 All warning messages are suppressed
8411 @item /WARNINGS=ERROR
8412 @cindex @option{/WARNINGS} (@code{gnatbind})
8413 Warning messages are treated as fatal errors
8416 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8417 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8418 Override default wide character encoding for standard Text_IO files.
8420 @item ^-x^/READ_SOURCES=NONE^
8421 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8422 Exclude source files (check object consistency only).
8425 @item /READ_SOURCES=AVAILABLE
8426 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8427 Default mode, in which sources are checked for consistency only if
8431 @item ^-y^/ENABLE_LEAP_SECONDS^
8432 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8433 Enable leap seconds support in @code{Ada.Calendar} and its children.
8435 @item ^-z^/ZERO_MAIN^
8436 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8442 You may obtain this listing of switches by running @code{gnatbind} with
8446 @node Consistency-Checking Modes
8447 @subsection Consistency-Checking Modes
8450 As described earlier, by default @code{gnatbind} checks
8451 that object files are consistent with one another and are consistent
8452 with any source files it can locate. The following switches control binder
8457 @item ^-s^/READ_SOURCES=ALL^
8458 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8459 Require source files to be present. In this mode, the binder must be
8460 able to locate all source files that are referenced, in order to check
8461 their consistency. In normal mode, if a source file cannot be located it
8462 is simply ignored. If you specify this switch, a missing source
8465 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8466 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8467 Override default wide character encoding for standard Text_IO files.
8468 Normally the default wide character encoding method used for standard
8469 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8470 the main source input (see description of switch
8471 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8472 use of this switch for the binder (which has the same set of
8473 possible arguments) overrides this default as specified.
8475 @item ^-x^/READ_SOURCES=NONE^
8476 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8477 Exclude source files. In this mode, the binder only checks that ALI
8478 files are consistent with one another. Source files are not accessed.
8479 The binder runs faster in this mode, and there is still a guarantee that
8480 the resulting program is self-consistent.
8481 If a source file has been edited since it was last compiled, and you
8482 specify this switch, the binder will not detect that the object
8483 file is out of date with respect to the source file. Note that this is the
8484 mode that is automatically used by @command{gnatmake} because in this
8485 case the checking against sources has already been performed by
8486 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8489 @item /READ_SOURCES=AVAILABLE
8490 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8491 This is the default mode in which source files are checked if they are
8492 available, and ignored if they are not available.
8496 @node Binder Error Message Control
8497 @subsection Binder Error Message Control
8500 The following switches provide control over the generation of error
8501 messages from the binder:
8505 @item ^-v^/REPORT_ERRORS=VERBOSE^
8506 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8507 Verbose mode. In the normal mode, brief error messages are generated to
8508 @file{stderr}. If this switch is present, a header is written
8509 to @file{stdout} and any error messages are directed to @file{stdout}.
8510 All that is written to @file{stderr} is a brief summary message.
8512 @item ^-b^/REPORT_ERRORS=BRIEF^
8513 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8514 Generate brief error messages to @file{stderr} even if verbose mode is
8515 specified. This is relevant only when used with the
8516 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8520 @cindex @option{-m} (@code{gnatbind})
8521 Limits the number of error messages to @var{n}, a decimal integer in the
8522 range 1-999. The binder terminates immediately if this limit is reached.
8525 @cindex @option{-M} (@code{gnatbind})
8526 Renames the generated main program from @code{main} to @code{xxx}.
8527 This is useful in the case of some cross-building environments, where
8528 the actual main program is separate from the one generated
8532 @item ^-ws^/WARNINGS=SUPPRESS^
8533 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8535 Suppress all warning messages.
8537 @item ^-we^/WARNINGS=ERROR^
8538 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8539 Treat any warning messages as fatal errors.
8542 @item /WARNINGS=NORMAL
8543 Standard mode with warnings generated, but warnings do not get treated
8547 @item ^-t^/NOTIME_STAMP_CHECK^
8548 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8549 @cindex Time stamp checks, in binder
8550 @cindex Binder consistency checks
8551 @cindex Consistency checks, in binder
8552 The binder performs a number of consistency checks including:
8556 Check that time stamps of a given source unit are consistent
8558 Check that checksums of a given source unit are consistent
8560 Check that consistent versions of @code{GNAT} were used for compilation
8562 Check consistency of configuration pragmas as required
8566 Normally failure of such checks, in accordance with the consistency
8567 requirements of the Ada Reference Manual, causes error messages to be
8568 generated which abort the binder and prevent the output of a binder
8569 file and subsequent link to obtain an executable.
8571 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8572 into warnings, so that
8573 binding and linking can continue to completion even in the presence of such
8574 errors. The result may be a failed link (due to missing symbols), or a
8575 non-functional executable which has undefined semantics.
8576 @emph{This means that
8577 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8581 @node Elaboration Control
8582 @subsection Elaboration Control
8585 The following switches provide additional control over the elaboration
8586 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8589 @item ^-p^/PESSIMISTIC_ELABORATION^
8590 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8591 Normally the binder attempts to choose an elaboration order that is
8592 likely to minimize the likelihood of an elaboration order error resulting
8593 in raising a @code{Program_Error} exception. This switch reverses the
8594 action of the binder, and requests that it deliberately choose an order
8595 that is likely to maximize the likelihood of an elaboration error.
8596 This is useful in ensuring portability and avoiding dependence on
8597 accidental fortuitous elaboration ordering.
8599 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8601 elaboration checking is used (@option{-gnatE} switch used for compilation).
8602 This is because in the default static elaboration mode, all necessary
8603 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8604 These implicit pragmas are still respected by the binder in
8605 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8606 safe elaboration order is assured.
8609 @node Output Control
8610 @subsection Output Control
8613 The following switches allow additional control over the output
8614 generated by the binder.
8619 @item ^-c^/NOOUTPUT^
8620 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8621 Check only. Do not generate the binder output file. In this mode the
8622 binder performs all error checks but does not generate an output file.
8624 @item ^-e^/ELABORATION_DEPENDENCIES^
8625 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8626 Output complete list of elaboration-order dependencies, showing the
8627 reason for each dependency. This output can be rather extensive but may
8628 be useful in diagnosing problems with elaboration order. The output is
8629 written to @file{stdout}.
8632 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8633 Output usage information. The output is written to @file{stdout}.
8635 @item ^-K^/LINKER_OPTION_LIST^
8636 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8637 Output linker options to @file{stdout}. Includes library search paths,
8638 contents of pragmas Ident and Linker_Options, and libraries added
8641 @item ^-l^/ORDER_OF_ELABORATION^
8642 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8643 Output chosen elaboration order. The output is written to @file{stdout}.
8645 @item ^-O^/OBJECT_LIST^
8646 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8647 Output full names of all the object files that must be linked to provide
8648 the Ada component of the program. The output is written to @file{stdout}.
8649 This list includes the files explicitly supplied and referenced by the user
8650 as well as implicitly referenced run-time unit files. The latter are
8651 omitted if the corresponding units reside in shared libraries. The
8652 directory names for the run-time units depend on the system configuration.
8654 @item ^-o ^/OUTPUT=^@var{file}
8655 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8656 Set name of output file to @var{file} instead of the normal
8657 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8658 binder generated body filename.
8659 Note that if this option is used, then linking must be done manually.
8660 It is not possible to use gnatlink in this case, since it cannot locate
8663 @item ^-r^/RESTRICTION_LIST^
8664 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8665 Generate list of @code{pragma Restrictions} that could be applied to
8666 the current unit. This is useful for code audit purposes, and also may
8667 be used to improve code generation in some cases.
8671 @node Dynamic Allocation Control
8672 @subsection Dynamic Allocation Control
8675 The heap control switches -- @option{-H32} and @option{-H64} --
8676 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8677 They only affect compiler-generated allocations via @code{__gnat_malloc};
8678 explicit calls to @code{malloc} and related functions from the C
8679 run-time library are unaffected.
8683 Allocate memory on 32-bit heap
8686 Allocate memory on 64-bit heap. This is the default
8687 unless explicitly overridden by a @code{'Size} clause on the access type.
8692 See also @ref{Access types and 32/64-bit allocation}.
8696 These switches are only effective on VMS platforms.
8700 @node Binding with Non-Ada Main Programs
8701 @subsection Binding with Non-Ada Main Programs
8704 In our description so far we have assumed that the main
8705 program is in Ada, and that the task of the binder is to generate a
8706 corresponding function @code{main} that invokes this Ada main
8707 program. GNAT also supports the building of executable programs where
8708 the main program is not in Ada, but some of the called routines are
8709 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8710 The following switch is used in this situation:
8714 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8715 No main program. The main program is not in Ada.
8719 In this case, most of the functions of the binder are still required,
8720 but instead of generating a main program, the binder generates a file
8721 containing the following callable routines:
8726 You must call this routine to initialize the Ada part of the program by
8727 calling the necessary elaboration routines. A call to @code{adainit} is
8728 required before the first call to an Ada subprogram.
8730 Note that it is assumed that the basic execution environment must be setup
8731 to be appropriate for Ada execution at the point where the first Ada
8732 subprogram is called. In particular, if the Ada code will do any
8733 floating-point operations, then the FPU must be setup in an appropriate
8734 manner. For the case of the x86, for example, full precision mode is
8735 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8736 that the FPU is in the right state.
8740 You must call this routine to perform any library-level finalization
8741 required by the Ada subprograms. A call to @code{adafinal} is required
8742 after the last call to an Ada subprogram, and before the program
8747 If the @option{^-n^/NOMAIN^} switch
8748 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8749 @cindex Binder, multiple input files
8750 is given, more than one ALI file may appear on
8751 the command line for @code{gnatbind}. The normal @dfn{closure}
8752 calculation is performed for each of the specified units. Calculating
8753 the closure means finding out the set of units involved by tracing
8754 @code{with} references. The reason it is necessary to be able to
8755 specify more than one ALI file is that a given program may invoke two or
8756 more quite separate groups of Ada units.
8758 The binder takes the name of its output file from the last specified ALI
8759 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8760 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8761 The output is an Ada unit in source form that can be compiled with GNAT.
8762 This compilation occurs automatically as part of the @command{gnatlink}
8765 Currently the GNAT run time requires a FPU using 80 bits mode
8766 precision. Under targets where this is not the default it is required to
8767 call GNAT.Float_Control.Reset before using floating point numbers (this
8768 include float computation, float input and output) in the Ada code. A
8769 side effect is that this could be the wrong mode for the foreign code
8770 where floating point computation could be broken after this call.
8772 @node Binding Programs with No Main Subprogram
8773 @subsection Binding Programs with No Main Subprogram
8776 It is possible to have an Ada program which does not have a main
8777 subprogram. This program will call the elaboration routines of all the
8778 packages, then the finalization routines.
8780 The following switch is used to bind programs organized in this manner:
8783 @item ^-z^/ZERO_MAIN^
8784 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8785 Normally the binder checks that the unit name given on the command line
8786 corresponds to a suitable main subprogram. When this switch is used,
8787 a list of ALI files can be given, and the execution of the program
8788 consists of elaboration of these units in an appropriate order. Note
8789 that the default wide character encoding method for standard Text_IO
8790 files is always set to Brackets if this switch is set (you can use
8792 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8795 @node Command-Line Access
8796 @section Command-Line Access
8799 The package @code{Ada.Command_Line} provides access to the command-line
8800 arguments and program name. In order for this interface to operate
8801 correctly, the two variables
8813 are declared in one of the GNAT library routines. These variables must
8814 be set from the actual @code{argc} and @code{argv} values passed to the
8815 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8816 generates the C main program to automatically set these variables.
8817 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8818 set these variables. If they are not set, the procedures in
8819 @code{Ada.Command_Line} will not be available, and any attempt to use
8820 them will raise @code{Constraint_Error}. If command line access is
8821 required, your main program must set @code{gnat_argc} and
8822 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8825 @node Search Paths for gnatbind
8826 @section Search Paths for @code{gnatbind}
8829 The binder takes the name of an ALI file as its argument and needs to
8830 locate source files as well as other ALI files to verify object consistency.
8832 For source files, it follows exactly the same search rules as @command{gcc}
8833 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8834 directories searched are:
8838 The directory containing the ALI file named in the command line, unless
8839 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8842 All directories specified by @option{^-I^/SEARCH^}
8843 switches on the @code{gnatbind}
8844 command line, in the order given.
8847 @findex ADA_PRJ_OBJECTS_FILE
8848 Each of the directories listed in the text file whose name is given
8849 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8852 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8853 driver when project files are used. It should not normally be set
8857 @findex ADA_OBJECTS_PATH
8858 Each of the directories listed in the value of the
8859 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8861 Construct this value
8862 exactly as the @env{PATH} environment variable: a list of directory
8863 names separated by colons (semicolons when working with the NT version
8867 Normally, define this value as a logical name containing a comma separated
8868 list of directory names.
8870 This variable can also be defined by means of an environment string
8871 (an argument to the HP C exec* set of functions).
8875 DEFINE ANOTHER_PATH FOO:[BAG]
8876 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8879 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8880 first, followed by the standard Ada
8881 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8882 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8883 (Text_IO, Sequential_IO, etc)
8884 instead of the standard Ada packages. Thus, in order to get the standard Ada
8885 packages by default, ADA_OBJECTS_PATH must be redefined.
8889 The content of the @file{ada_object_path} file which is part of the GNAT
8890 installation tree and is used to store standard libraries such as the
8891 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8894 @ref{Installing a library}
8899 In the binder the switch @option{^-I^/SEARCH^}
8900 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8901 is used to specify both source and
8902 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8903 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8904 instead if you want to specify
8905 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8906 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8907 if you want to specify library paths
8908 only. This means that for the binder
8909 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8910 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8911 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8912 The binder generates the bind file (a C language source file) in the
8913 current working directory.
8919 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8920 children make up the GNAT Run-Time Library, together with the package
8921 GNAT and its children, which contain a set of useful additional
8922 library functions provided by GNAT. The sources for these units are
8923 needed by the compiler and are kept together in one directory. The ALI
8924 files and object files generated by compiling the RTL are needed by the
8925 binder and the linker and are kept together in one directory, typically
8926 different from the directory containing the sources. In a normal
8927 installation, you need not specify these directory names when compiling
8928 or binding. Either the environment variables or the built-in defaults
8929 cause these files to be found.
8931 Besides simplifying access to the RTL, a major use of search paths is
8932 in compiling sources from multiple directories. This can make
8933 development environments much more flexible.
8935 @node Examples of gnatbind Usage
8936 @section Examples of @code{gnatbind} Usage
8939 This section contains a number of examples of using the GNAT binding
8940 utility @code{gnatbind}.
8943 @item gnatbind hello
8944 The main program @code{Hello} (source program in @file{hello.adb}) is
8945 bound using the standard switch settings. The generated main program is
8946 @file{b~hello.adb}. This is the normal, default use of the binder.
8949 @item gnatbind hello -o mainprog.adb
8952 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8954 The main program @code{Hello} (source program in @file{hello.adb}) is
8955 bound using the standard switch settings. The generated main program is
8956 @file{mainprog.adb} with the associated spec in
8957 @file{mainprog.ads}. Note that you must specify the body here not the
8958 spec. Note that if this option is used, then linking must be done manually,
8959 since gnatlink will not be able to find the generated file.
8962 @c ------------------------------------
8963 @node Linking Using gnatlink
8964 @chapter Linking Using @command{gnatlink}
8965 @c ------------------------------------
8969 This chapter discusses @command{gnatlink}, a tool that links
8970 an Ada program and builds an executable file. This utility
8971 invokes the system linker ^(via the @command{gcc} command)^^
8972 with a correct list of object files and library references.
8973 @command{gnatlink} automatically determines the list of files and
8974 references for the Ada part of a program. It uses the binder file
8975 generated by the @command{gnatbind} to determine this list.
8977 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8978 driver (see @ref{The GNAT Driver and Project Files}).
8981 * Running gnatlink::
8982 * Switches for gnatlink::
8985 @node Running gnatlink
8986 @section Running @command{gnatlink}
8989 The form of the @command{gnatlink} command is
8992 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8993 @c @ovar{non-Ada objects} @ovar{linker options}
8994 @c Expanding @ovar macro inline (explanation in macro def comments)
8995 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8996 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9001 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9003 or linker options) may be in any order, provided that no non-Ada object may
9004 be mistaken for a main @file{ALI} file.
9005 Any file name @file{F} without the @file{.ali}
9006 extension will be taken as the main @file{ALI} file if a file exists
9007 whose name is the concatenation of @file{F} and @file{.ali}.
9010 @file{@var{mainprog}.ali} references the ALI file of the main program.
9011 The @file{.ali} extension of this file can be omitted. From this
9012 reference, @command{gnatlink} locates the corresponding binder file
9013 @file{b~@var{mainprog}.adb} and, using the information in this file along
9014 with the list of non-Ada objects and linker options, constructs a
9015 linker command file to create the executable.
9017 The arguments other than the @command{gnatlink} switches and the main
9018 @file{ALI} file are passed to the linker uninterpreted.
9019 They typically include the names of
9020 object files for units written in other languages than Ada and any library
9021 references required to resolve references in any of these foreign language
9022 units, or in @code{Import} pragmas in any Ada units.
9024 @var{linker options} is an optional list of linker specific
9026 The default linker called by gnatlink is @command{gcc} which in
9027 turn calls the appropriate system linker.
9029 One useful option for the linker is @option{-s}: it reduces the size of the
9030 executable by removing all symbol table and relocation information from the
9033 Standard options for the linker such as @option{-lmy_lib} or
9034 @option{-Ldir} can be added as is.
9035 For options that are not recognized by
9036 @command{gcc} as linker options, use the @command{gcc} switches
9037 @option{-Xlinker} or @option{-Wl,}.
9039 Refer to the GCC documentation for
9042 Here is an example showing how to generate a linker map:
9045 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9048 Using @var{linker options} it is possible to set the program stack and
9051 See @ref{Setting Stack Size from gnatlink} and
9052 @ref{Setting Heap Size from gnatlink}.
9055 @command{gnatlink} determines the list of objects required by the Ada
9056 program and prepends them to the list of objects passed to the linker.
9057 @command{gnatlink} also gathers any arguments set by the use of
9058 @code{pragma Linker_Options} and adds them to the list of arguments
9059 presented to the linker.
9062 @command{gnatlink} accepts the following types of extra files on the command
9063 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9064 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9065 handled according to their extension.
9068 @node Switches for gnatlink
9069 @section Switches for @command{gnatlink}
9072 The following switches are available with the @command{gnatlink} utility:
9078 @cindex @option{--version} @command{gnatlink}
9079 Display Copyright and version, then exit disregarding all other options.
9082 @cindex @option{--help} @command{gnatlink}
9083 If @option{--version} was not used, display usage, then exit disregarding
9086 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9087 @cindex Command line length
9088 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9089 On some targets, the command line length is limited, and @command{gnatlink}
9090 will generate a separate file for the linker if the list of object files
9092 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9093 to be generated even if
9094 the limit is not exceeded. This is useful in some cases to deal with
9095 special situations where the command line length is exceeded.
9098 @cindex Debugging information, including
9099 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9100 The option to include debugging information causes the Ada bind file (in
9101 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9102 @option{^-g^/DEBUG^}.
9103 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9104 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9105 Without @option{^-g^/DEBUG^}, the binder removes these files by
9106 default. The same procedure apply if a C bind file was generated using
9107 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9108 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9110 @item ^-n^/NOCOMPILE^
9111 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9112 Do not compile the file generated by the binder. This may be used when
9113 a link is rerun with different options, but there is no need to recompile
9117 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9118 Causes additional information to be output, including a full list of the
9119 included object files. This switch option is most useful when you want
9120 to see what set of object files are being used in the link step.
9122 @item ^-v -v^/VERBOSE/VERBOSE^
9123 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9124 Very verbose mode. Requests that the compiler operate in verbose mode when
9125 it compiles the binder file, and that the system linker run in verbose mode.
9127 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9128 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9129 @var{exec-name} specifies an alternate name for the generated
9130 executable program. If this switch is omitted, the executable has the same
9131 name as the main unit. For example, @code{gnatlink try.ali} creates
9132 an executable called @file{^try^TRY.EXE^}.
9135 @item -b @var{target}
9136 @cindex @option{-b} (@command{gnatlink})
9137 Compile your program to run on @var{target}, which is the name of a
9138 system configuration. You must have a GNAT cross-compiler built if
9139 @var{target} is not the same as your host system.
9142 @cindex @option{-B} (@command{gnatlink})
9143 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9144 from @var{dir} instead of the default location. Only use this switch
9145 when multiple versions of the GNAT compiler are available.
9146 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9147 for further details. You would normally use the @option{-b} or
9148 @option{-V} switch instead.
9151 When linking an executable, create a map file. The name of the map file
9152 has the same name as the executable with extension ".map".
9155 When linking an executable, create a map file. The name of the map file is
9158 @item --GCC=@var{compiler_name}
9159 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9160 Program used for compiling the binder file. The default is
9161 @command{gcc}. You need to use quotes around @var{compiler_name} if
9162 @code{compiler_name} contains spaces or other separator characters.
9163 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9164 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9165 inserted after your command name. Thus in the above example the compiler
9166 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9167 A limitation of this syntax is that the name and path name of the executable
9168 itself must not include any embedded spaces. If the compiler executable is
9169 different from the default one (gcc or <prefix>-gcc), then the back-end
9170 switches in the ALI file are not used to compile the binder generated source.
9171 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9172 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9173 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9174 is taken into account. However, all the additional switches are also taken
9176 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9177 @option{--GCC="bar -x -y -z -t"}.
9179 @item --LINK=@var{name}
9180 @cindex @option{--LINK=} (@command{gnatlink})
9181 @var{name} is the name of the linker to be invoked. This is especially
9182 useful in mixed language programs since languages such as C++ require
9183 their own linker to be used. When this switch is omitted, the default
9184 name for the linker is @command{gcc}. When this switch is used, the
9185 specified linker is called instead of @command{gcc} with exactly the same
9186 parameters that would have been passed to @command{gcc} so if the desired
9187 linker requires different parameters it is necessary to use a wrapper
9188 script that massages the parameters before invoking the real linker. It
9189 may be useful to control the exact invocation by using the verbose
9195 @item /DEBUG=TRACEBACK
9196 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9197 This qualifier causes sufficient information to be included in the
9198 executable file to allow a traceback, but does not include the full
9199 symbol information needed by the debugger.
9201 @item /IDENTIFICATION="<string>"
9202 @code{"<string>"} specifies the string to be stored in the image file
9203 identification field in the image header.
9204 It overrides any pragma @code{Ident} specified string.
9206 @item /NOINHIBIT-EXEC
9207 Generate the executable file even if there are linker warnings.
9209 @item /NOSTART_FILES
9210 Don't link in the object file containing the ``main'' transfer address.
9211 Used when linking with a foreign language main program compiled with an
9215 Prefer linking with object libraries over sharable images, even without
9221 @node The GNAT Make Program gnatmake
9222 @chapter The GNAT Make Program @command{gnatmake}
9226 * Running gnatmake::
9227 * Switches for gnatmake::
9228 * Mode Switches for gnatmake::
9229 * Notes on the Command Line::
9230 * How gnatmake Works::
9231 * Examples of gnatmake Usage::
9234 A typical development cycle when working on an Ada program consists of
9235 the following steps:
9239 Edit some sources to fix bugs.
9245 Compile all sources affected.
9255 The third step can be tricky, because not only do the modified files
9256 @cindex Dependency rules
9257 have to be compiled, but any files depending on these files must also be
9258 recompiled. The dependency rules in Ada can be quite complex, especially
9259 in the presence of overloading, @code{use} clauses, generics and inlined
9262 @command{gnatmake} automatically takes care of the third and fourth steps
9263 of this process. It determines which sources need to be compiled,
9264 compiles them, and binds and links the resulting object files.
9266 Unlike some other Ada make programs, the dependencies are always
9267 accurately recomputed from the new sources. The source based approach of
9268 the GNAT compilation model makes this possible. This means that if
9269 changes to the source program cause corresponding changes in
9270 dependencies, they will always be tracked exactly correctly by
9273 @node Running gnatmake
9274 @section Running @command{gnatmake}
9277 The usual form of the @command{gnatmake} command is
9280 @c $ gnatmake @ovar{switches} @var{file_name}
9281 @c @ovar{file_names} @ovar{mode_switches}
9282 @c Expanding @ovar macro inline (explanation in macro def comments)
9283 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9284 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9288 The only required argument is one @var{file_name}, which specifies
9289 a compilation unit that is a main program. Several @var{file_names} can be
9290 specified: this will result in several executables being built.
9291 If @code{switches} are present, they can be placed before the first
9292 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9293 If @var{mode_switches} are present, they must always be placed after
9294 the last @var{file_name} and all @code{switches}.
9296 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9297 extension may be omitted from the @var{file_name} arguments. However, if
9298 you are using non-standard extensions, then it is required that the
9299 extension be given. A relative or absolute directory path can be
9300 specified in a @var{file_name}, in which case, the input source file will
9301 be searched for in the specified directory only. Otherwise, the input
9302 source file will first be searched in the directory where
9303 @command{gnatmake} was invoked and if it is not found, it will be search on
9304 the source path of the compiler as described in
9305 @ref{Search Paths and the Run-Time Library (RTL)}.
9307 All @command{gnatmake} output (except when you specify
9308 @option{^-M^/DEPENDENCIES_LIST^}) is to
9309 @file{stderr}. The output produced by the
9310 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9313 @node Switches for gnatmake
9314 @section Switches for @command{gnatmake}
9317 You may specify any of the following switches to @command{gnatmake}:
9323 @cindex @option{--version} @command{gnatmake}
9324 Display Copyright and version, then exit disregarding all other options.
9327 @cindex @option{--help} @command{gnatmake}
9328 If @option{--version} was not used, display usage, then exit disregarding
9332 @item --GCC=@var{compiler_name}
9333 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9334 Program used for compiling. The default is `@command{gcc}'. You need to use
9335 quotes around @var{compiler_name} if @code{compiler_name} contains
9336 spaces or other separator characters. As an example @option{--GCC="foo -x
9337 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9338 compiler. A limitation of this syntax is that the name and path name of
9339 the executable itself must not include any embedded spaces. Note that
9340 switch @option{-c} is always inserted after your command name. Thus in the
9341 above example the compiler command that will be used by @command{gnatmake}
9342 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9343 used, only the last @var{compiler_name} is taken into account. However,
9344 all the additional switches are also taken into account. Thus,
9345 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9346 @option{--GCC="bar -x -y -z -t"}.
9348 @item --GNATBIND=@var{binder_name}
9349 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9350 Program used for binding. The default is `@code{gnatbind}'. You need to
9351 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9352 or other separator characters. As an example @option{--GNATBIND="bar -x
9353 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9354 binder. Binder switches that are normally appended by @command{gnatmake}
9355 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9356 A limitation of this syntax is that the name and path name of the executable
9357 itself must not include any embedded spaces.
9359 @item --GNATLINK=@var{linker_name}
9360 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9361 Program used for linking. The default is `@command{gnatlink}'. You need to
9362 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9363 or other separator characters. As an example @option{--GNATLINK="lan -x
9364 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9365 linker. Linker switches that are normally appended by @command{gnatmake} to
9366 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9367 A limitation of this syntax is that the name and path name of the executable
9368 itself must not include any embedded spaces.
9372 @item ^--subdirs^/SUBDIRS^=subdir
9373 Actual object directory of each project file is the subdirectory subdir of the
9374 object directory specified or defaulted in the project file.
9376 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9377 Disallow simultaneous compilations in the same object directory when
9378 project files are used.
9380 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9381 By default, shared library projects are not allowed to import static library
9382 projects. When this switch is used on the command line, this restriction is
9385 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9386 Specify a source info file. This switch is active only when project files
9387 are used. If the source info file is specified as a relative path, then it is
9388 relative to the object directory of the main project. If the source info file
9389 does not exist, then after the Project Manager has successfully parsed and
9390 processed the project files and found the sources, it creates the source info
9391 file. If the source info file already exists and can be read successfully,
9392 then the Project Manager will get all the needed information about the sources
9393 from the source info file and will not look for them. This reduces the time
9394 to process the project files, especially when looking for sources that take a
9395 long time. If the source info file exists but cannot be parsed successfully,
9396 the Project Manager will attempt to recreate it. If the Project Manager fails
9397 to create the source info file, a message is issued, but gnatmake does not
9398 fail. @command{gnatmake} "trusts" the source info file. This means that
9399 if the source files have changed (addition, deletion, moving to a different
9400 source directory), then the source info file need to be deleted and recreated.
9403 @item --create-map-file
9404 When linking an executable, create a map file. The name of the map file
9405 has the same name as the executable with extension ".map".
9407 @item --create-map-file=mapfile
9408 When linking an executable, create a map file. The name of the map file is
9413 @item ^-a^/ALL_FILES^
9414 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9415 Consider all files in the make process, even the GNAT internal system
9416 files (for example, the predefined Ada library files), as well as any
9417 locked files. Locked files are files whose ALI file is write-protected.
9419 @command{gnatmake} does not check these files,
9420 because the assumption is that the GNAT internal files are properly up
9421 to date, and also that any write protected ALI files have been properly
9422 installed. Note that if there is an installation problem, such that one
9423 of these files is not up to date, it will be properly caught by the
9425 You may have to specify this switch if you are working on GNAT
9426 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9427 in conjunction with @option{^-f^/FORCE_COMPILE^}
9428 if you need to recompile an entire application,
9429 including run-time files, using special configuration pragmas,
9430 such as a @code{Normalize_Scalars} pragma.
9433 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9436 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9439 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9442 @item ^-b^/ACTIONS=BIND^
9443 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9444 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9445 compilation and binding, but no link.
9446 Can be combined with @option{^-l^/ACTIONS=LINK^}
9447 to do binding and linking. When not combined with
9448 @option{^-c^/ACTIONS=COMPILE^}
9449 all the units in the closure of the main program must have been previously
9450 compiled and must be up to date. The root unit specified by @var{file_name}
9451 may be given without extension, with the source extension or, if no GNAT
9452 Project File is specified, with the ALI file extension.
9454 @item ^-c^/ACTIONS=COMPILE^
9455 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9456 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9457 is also specified. Do not perform linking, except if both
9458 @option{^-b^/ACTIONS=BIND^} and
9459 @option{^-l^/ACTIONS=LINK^} are also specified.
9460 If the root unit specified by @var{file_name} is not a main unit, this is the
9461 default. Otherwise @command{gnatmake} will attempt binding and linking
9462 unless all objects are up to date and the executable is more recent than
9466 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9467 Use a temporary mapping file. A mapping file is a way to communicate
9468 to the compiler two mappings: from unit names to file names (without
9469 any directory information) and from file names to path names (with
9470 full directory information). A mapping file can make the compiler's
9471 file searches faster, especially if there are many source directories,
9472 or the sources are read over a slow network connection. If
9473 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9474 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9475 is initially populated based on the project file. If
9476 @option{^-C^/MAPPING^} is used without
9477 @option{^-P^/PROJECT_FILE^},
9478 the mapping file is initially empty. Each invocation of the compiler
9479 will add any newly accessed sources to the mapping file.
9481 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9482 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9483 Use a specific mapping file. The file, specified as a path name (absolute or
9484 relative) by this switch, should already exist, otherwise the switch is
9485 ineffective. The specified mapping file will be communicated to the compiler.
9486 This switch is not compatible with a project file
9487 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9488 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9490 @item ^-d^/DISPLAY_PROGRESS^
9491 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9492 Display progress for each source, up to date or not, as a single line
9495 completed x out of y (zz%)
9498 If the file needs to be compiled this is displayed after the invocation of
9499 the compiler. These lines are displayed even in quiet output mode.
9501 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9502 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9503 Put all object files and ALI file in directory @var{dir}.
9504 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9505 and ALI files go in the current working directory.
9507 This switch cannot be used when using a project file.
9510 @cindex @option{-eI} (@command{gnatmake})
9511 Indicates that the main source is a multi-unit source and the rank of the unit
9512 in the source file is nnn. nnn needs to be a positive number and a valid
9513 index in the source. This switch cannot be used when @command{gnatmake} is
9514 invoked for several mains.
9518 @cindex @option{-eL} (@command{gnatmake})
9519 @cindex symbolic links
9520 Follow all symbolic links when processing project files.
9521 This should be used if your project uses symbolic links for files or
9522 directories, but is not needed in other cases.
9524 @cindex naming scheme
9525 This also assumes that no directory matches the naming scheme for files (for
9526 instance that you do not have a directory called "sources.ads" when using the
9527 default GNAT naming scheme).
9529 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9530 save a lot of system calls (several per source file and object file), which
9531 can result in a significant speed up to load and manipulate a project file,
9532 especially when using source files from a remote system.
9536 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9537 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9538 Output the commands for the compiler, the binder and the linker
9539 on ^standard output^SYS$OUTPUT^,
9540 instead of ^standard error^SYS$ERROR^.
9542 @item ^-f^/FORCE_COMPILE^
9543 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9544 Force recompilations. Recompile all sources, even though some object
9545 files may be up to date, but don't recompile predefined or GNAT internal
9546 files or locked files (files with a write-protected ALI file),
9547 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9549 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9550 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9551 When using project files, if some errors or warnings are detected during
9552 parsing and verbose mode is not in effect (no use of switch
9553 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9554 file, rather than its simple file name.
9557 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9558 Enable debugging. This switch is simply passed to the compiler and to the
9561 @item ^-i^/IN_PLACE^
9562 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9563 In normal mode, @command{gnatmake} compiles all object files and ALI files
9564 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9565 then instead object files and ALI files that already exist are overwritten
9566 in place. This means that once a large project is organized into separate
9567 directories in the desired manner, then @command{gnatmake} will automatically
9568 maintain and update this organization. If no ALI files are found on the
9569 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9570 the new object and ALI files are created in the
9571 directory containing the source being compiled. If another organization
9572 is desired, where objects and sources are kept in different directories,
9573 a useful technique is to create dummy ALI files in the desired directories.
9574 When detecting such a dummy file, @command{gnatmake} will be forced to
9575 recompile the corresponding source file, and it will be put the resulting
9576 object and ALI files in the directory where it found the dummy file.
9578 @item ^-j^/PROCESSES=^@var{n}
9579 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9580 @cindex Parallel make
9581 Use @var{n} processes to carry out the (re)compilations. On a
9582 multiprocessor machine compilations will occur in parallel. In the
9583 event of compilation errors, messages from various compilations might
9584 get interspersed (but @command{gnatmake} will give you the full ordered
9585 list of failing compiles at the end). If this is problematic, rerun
9586 the make process with n set to 1 to get a clean list of messages.
9588 @item ^-k^/CONTINUE_ON_ERROR^
9589 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9590 Keep going. Continue as much as possible after a compilation error. To
9591 ease the programmer's task in case of compilation errors, the list of
9592 sources for which the compile fails is given when @command{gnatmake}
9595 If @command{gnatmake} is invoked with several @file{file_names} and with this
9596 switch, if there are compilation errors when building an executable,
9597 @command{gnatmake} will not attempt to build the following executables.
9599 @item ^-l^/ACTIONS=LINK^
9600 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9601 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9602 and linking. Linking will not be performed if combined with
9603 @option{^-c^/ACTIONS=COMPILE^}
9604 but not with @option{^-b^/ACTIONS=BIND^}.
9605 When not combined with @option{^-b^/ACTIONS=BIND^}
9606 all the units in the closure of the main program must have been previously
9607 compiled and must be up to date, and the main program needs to have been bound.
9608 The root unit specified by @var{file_name}
9609 may be given without extension, with the source extension or, if no GNAT
9610 Project File is specified, with the ALI file extension.
9612 @item ^-m^/MINIMAL_RECOMPILATION^
9613 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9614 Specify that the minimum necessary amount of recompilations
9615 be performed. In this mode @command{gnatmake} ignores time
9616 stamp differences when the only
9617 modifications to a source file consist in adding/removing comments,
9618 empty lines, spaces or tabs. This means that if you have changed the
9619 comments in a source file or have simply reformatted it, using this
9620 switch will tell @command{gnatmake} not to recompile files that depend on it
9621 (provided other sources on which these files depend have undergone no
9622 semantic modifications). Note that the debugging information may be
9623 out of date with respect to the sources if the @option{-m} switch causes
9624 a compilation to be switched, so the use of this switch represents a
9625 trade-off between compilation time and accurate debugging information.
9627 @item ^-M^/DEPENDENCIES_LIST^
9628 @cindex Dependencies, producing list
9629 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9630 Check if all objects are up to date. If they are, output the object
9631 dependences to @file{stdout} in a form that can be directly exploited in
9632 a @file{Makefile}. By default, each source file is prefixed with its
9633 (relative or absolute) directory name. This name is whatever you
9634 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9635 and @option{^-I^/SEARCH^} switches. If you use
9636 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9637 @option{^-q^/QUIET^}
9638 (see below), only the source file names,
9639 without relative paths, are output. If you just specify the
9640 @option{^-M^/DEPENDENCIES_LIST^}
9641 switch, dependencies of the GNAT internal system files are omitted. This
9642 is typically what you want. If you also specify
9643 the @option{^-a^/ALL_FILES^} switch,
9644 dependencies of the GNAT internal files are also listed. Note that
9645 dependencies of the objects in external Ada libraries (see switch
9646 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9649 @item ^-n^/DO_OBJECT_CHECK^
9650 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9651 Don't compile, bind, or link. Checks if all objects are up to date.
9652 If they are not, the full name of the first file that needs to be
9653 recompiled is printed.
9654 Repeated use of this option, followed by compiling the indicated source
9655 file, will eventually result in recompiling all required units.
9657 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9658 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9659 Output executable name. The name of the final executable program will be
9660 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9661 name for the executable will be the name of the input file in appropriate form
9662 for an executable file on the host system.
9664 This switch cannot be used when invoking @command{gnatmake} with several
9667 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9668 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9669 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9670 automatically missing object directories, library directories and exec
9673 @item ^-P^/PROJECT_FILE=^@var{project}
9674 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9675 Use project file @var{project}. Only one such switch can be used.
9676 @xref{gnatmake and Project Files}.
9679 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9680 Quiet. When this flag is not set, the commands carried out by
9681 @command{gnatmake} are displayed.
9683 @item ^-s^/SWITCH_CHECK/^
9684 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9685 Recompile if compiler switches have changed since last compilation.
9686 All compiler switches but -I and -o are taken into account in the
9688 orders between different ``first letter'' switches are ignored, but
9689 orders between same switches are taken into account. For example,
9690 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9691 is equivalent to @option{-O -g}.
9693 This switch is recommended when Integrated Preprocessing is used.
9696 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9697 Unique. Recompile at most the main files. It implies -c. Combined with
9698 -f, it is equivalent to calling the compiler directly. Note that using
9699 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9700 (@pxref{Project Files and Main Subprograms}).
9702 @item ^-U^/ALL_PROJECTS^
9703 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9704 When used without a project file or with one or several mains on the command
9705 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9706 on the command line, all sources of all project files are checked and compiled
9707 if not up to date, and libraries are rebuilt, if necessary.
9710 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9711 Verbose. Display the reason for all recompilations @command{gnatmake}
9712 decides are necessary, with the highest verbosity level.
9714 @item ^-vl^/LOW_VERBOSITY^
9715 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9716 Verbosity level Low. Display fewer lines than in verbosity Medium.
9718 @item ^-vm^/MEDIUM_VERBOSITY^
9719 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9720 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9722 @item ^-vh^/HIGH_VERBOSITY^
9723 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9724 Verbosity level High. Equivalent to ^-v^/REASONS^.
9726 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9727 Indicate the verbosity of the parsing of GNAT project files.
9728 @xref{Switches Related to Project Files}.
9730 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9731 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9732 Indicate that sources that are not part of any Project File may be compiled.
9733 Normally, when using Project Files, only sources that are part of a Project
9734 File may be compile. When this switch is used, a source outside of all Project
9735 Files may be compiled. The ALI file and the object file will be put in the
9736 object directory of the main Project. The compilation switches used will only
9737 be those specified on the command line. Even when
9738 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9739 command line need to be sources of a project file.
9741 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9742 Indicate that external variable @var{name} has the value @var{value}.
9743 The Project Manager will use this value for occurrences of
9744 @code{external(name)} when parsing the project file.
9745 @xref{Switches Related to Project Files}.
9748 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9749 No main subprogram. Bind and link the program even if the unit name
9750 given on the command line is a package name. The resulting executable
9751 will execute the elaboration routines of the package and its closure,
9752 then the finalization routines.
9757 @item @command{gcc} @asis{switches}
9759 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9760 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9763 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9764 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9765 automatically treated as a compiler switch, and passed on to all
9766 compilations that are carried out.
9771 Source and library search path switches:
9775 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9776 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9777 When looking for source files also look in directory @var{dir}.
9778 The order in which source files search is undertaken is
9779 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9781 @item ^-aL^/SKIP_MISSING=^@var{dir}
9782 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9783 Consider @var{dir} as being an externally provided Ada library.
9784 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9785 files have been located in directory @var{dir}. This allows you to have
9786 missing bodies for the units in @var{dir} and to ignore out of date bodies
9787 for the same units. You still need to specify
9788 the location of the specs for these units by using the switches
9789 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9790 or @option{^-I^/SEARCH=^@var{dir}}.
9791 Note: this switch is provided for compatibility with previous versions
9792 of @command{gnatmake}. The easier method of causing standard libraries
9793 to be excluded from consideration is to write-protect the corresponding
9796 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9797 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9798 When searching for library and object files, look in directory
9799 @var{dir}. The order in which library files are searched is described in
9800 @ref{Search Paths for gnatbind}.
9802 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9803 @cindex Search paths, for @command{gnatmake}
9804 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9805 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9806 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9808 @item ^-I^/SEARCH=^@var{dir}
9809 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9810 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9811 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9813 @item ^-I-^/NOCURRENT_DIRECTORY^
9814 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9815 @cindex Source files, suppressing search
9816 Do not look for source files in the directory containing the source
9817 file named in the command line.
9818 Do not look for ALI or object files in the directory
9819 where @command{gnatmake} was invoked.
9821 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9822 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9823 @cindex Linker libraries
9824 Add directory @var{dir} to the list of directories in which the linker
9825 will search for libraries. This is equivalent to
9826 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9828 Furthermore, under Windows, the sources pointed to by the libraries path
9829 set in the registry are not searched for.
9833 @cindex @option{-nostdinc} (@command{gnatmake})
9834 Do not look for source files in the system default directory.
9837 @cindex @option{-nostdlib} (@command{gnatmake})
9838 Do not look for library files in the system default directory.
9840 @item --RTS=@var{rts-path}
9841 @cindex @option{--RTS} (@command{gnatmake})
9842 Specifies the default location of the runtime library. GNAT looks for the
9844 in the following directories, and stops as soon as a valid runtime is found
9845 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9846 @file{ada_object_path} present):
9849 @item <current directory>/$rts_path
9851 @item <default-search-dir>/$rts_path
9853 @item <default-search-dir>/rts-$rts_path
9857 The selected path is handled like a normal RTS path.
9861 @node Mode Switches for gnatmake
9862 @section Mode Switches for @command{gnatmake}
9865 The mode switches (referred to as @code{mode_switches}) allow the
9866 inclusion of switches that are to be passed to the compiler itself, the
9867 binder or the linker. The effect of a mode switch is to cause all
9868 subsequent switches up to the end of the switch list, or up to the next
9869 mode switch, to be interpreted as switches to be passed on to the
9870 designated component of GNAT.
9874 @item -cargs @var{switches}
9875 @cindex @option{-cargs} (@command{gnatmake})
9876 Compiler switches. Here @var{switches} is a list of switches
9877 that are valid switches for @command{gcc}. They will be passed on to
9878 all compile steps performed by @command{gnatmake}.
9880 @item -bargs @var{switches}
9881 @cindex @option{-bargs} (@command{gnatmake})
9882 Binder switches. Here @var{switches} is a list of switches
9883 that are valid switches for @code{gnatbind}. They will be passed on to
9884 all bind steps performed by @command{gnatmake}.
9886 @item -largs @var{switches}
9887 @cindex @option{-largs} (@command{gnatmake})
9888 Linker switches. Here @var{switches} is a list of switches
9889 that are valid switches for @command{gnatlink}. They will be passed on to
9890 all link steps performed by @command{gnatmake}.
9892 @item -margs @var{switches}
9893 @cindex @option{-margs} (@command{gnatmake})
9894 Make switches. The switches are directly interpreted by @command{gnatmake},
9895 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9899 @node Notes on the Command Line
9900 @section Notes on the Command Line
9903 This section contains some additional useful notes on the operation
9904 of the @command{gnatmake} command.
9908 @cindex Recompilation, by @command{gnatmake}
9909 If @command{gnatmake} finds no ALI files, it recompiles the main program
9910 and all other units required by the main program.
9911 This means that @command{gnatmake}
9912 can be used for the initial compile, as well as during subsequent steps of
9913 the development cycle.
9916 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9917 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9918 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9922 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9923 is used to specify both source and
9924 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9925 instead if you just want to specify
9926 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9927 if you want to specify library paths
9931 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9932 This may conveniently be used to exclude standard libraries from
9933 consideration and in particular it means that the use of the
9934 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9935 unless @option{^-a^/ALL_FILES^} is also specified.
9938 @command{gnatmake} has been designed to make the use of Ada libraries
9939 particularly convenient. Assume you have an Ada library organized
9940 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9941 of your Ada compilation units,
9942 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9943 specs of these units, but no bodies. Then to compile a unit
9944 stored in @code{main.adb}, which uses this Ada library you would just type
9948 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9951 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9952 /SKIP_MISSING=@i{[OBJ_DIR]} main
9957 Using @command{gnatmake} along with the
9958 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9959 switch provides a mechanism for avoiding unnecessary recompilations. Using
9961 you can update the comments/format of your
9962 source files without having to recompile everything. Note, however, that
9963 adding or deleting lines in a source files may render its debugging
9964 info obsolete. If the file in question is a spec, the impact is rather
9965 limited, as that debugging info will only be useful during the
9966 elaboration phase of your program. For bodies the impact can be more
9967 significant. In all events, your debugger will warn you if a source file
9968 is more recent than the corresponding object, and alert you to the fact
9969 that the debugging information may be out of date.
9972 @node How gnatmake Works
9973 @section How @command{gnatmake} Works
9976 Generally @command{gnatmake} automatically performs all necessary
9977 recompilations and you don't need to worry about how it works. However,
9978 it may be useful to have some basic understanding of the @command{gnatmake}
9979 approach and in particular to understand how it uses the results of
9980 previous compilations without incorrectly depending on them.
9982 First a definition: an object file is considered @dfn{up to date} if the
9983 corresponding ALI file exists and if all the source files listed in the
9984 dependency section of this ALI file have time stamps matching those in
9985 the ALI file. This means that neither the source file itself nor any
9986 files that it depends on have been modified, and hence there is no need
9987 to recompile this file.
9989 @command{gnatmake} works by first checking if the specified main unit is up
9990 to date. If so, no compilations are required for the main unit. If not,
9991 @command{gnatmake} compiles the main program to build a new ALI file that
9992 reflects the latest sources. Then the ALI file of the main unit is
9993 examined to find all the source files on which the main program depends,
9994 and @command{gnatmake} recursively applies the above procedure on all these
9997 This process ensures that @command{gnatmake} only trusts the dependencies
9998 in an existing ALI file if they are known to be correct. Otherwise it
9999 always recompiles to determine a new, guaranteed accurate set of
10000 dependencies. As a result the program is compiled ``upside down'' from what may
10001 be more familiar as the required order of compilation in some other Ada
10002 systems. In particular, clients are compiled before the units on which
10003 they depend. The ability of GNAT to compile in any order is critical in
10004 allowing an order of compilation to be chosen that guarantees that
10005 @command{gnatmake} will recompute a correct set of new dependencies if
10008 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10009 imported by several of the executables, it will be recompiled at most once.
10011 Note: when using non-standard naming conventions
10012 (@pxref{Using Other File Names}), changing through a configuration pragmas
10013 file the version of a source and invoking @command{gnatmake} to recompile may
10014 have no effect, if the previous version of the source is still accessible
10015 by @command{gnatmake}. It may be necessary to use the switch
10016 ^-f^/FORCE_COMPILE^.
10018 @node Examples of gnatmake Usage
10019 @section Examples of @command{gnatmake} Usage
10022 @item gnatmake hello.adb
10023 Compile all files necessary to bind and link the main program
10024 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10025 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10027 @item gnatmake main1 main2 main3
10028 Compile all files necessary to bind and link the main programs
10029 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10030 (containing unit @code{Main2}) and @file{main3.adb}
10031 (containing unit @code{Main3}) and bind and link the resulting object files
10032 to generate three executable files @file{^main1^MAIN1.EXE^},
10033 @file{^main2^MAIN2.EXE^}
10034 and @file{^main3^MAIN3.EXE^}.
10037 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10041 @item gnatmake Main_Unit /QUIET
10042 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10043 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10045 Compile all files necessary to bind and link the main program unit
10046 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10047 be done with optimization level 2 and the order of elaboration will be
10048 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10049 displaying commands it is executing.
10052 @c *************************
10053 @node Improving Performance
10054 @chapter Improving Performance
10055 @cindex Improving performance
10058 This chapter presents several topics related to program performance.
10059 It first describes some of the tradeoffs that need to be considered
10060 and some of the techniques for making your program run faster.
10061 It then documents the @command{gnatelim} tool and unused subprogram/data
10062 elimination feature, which can reduce the size of program executables.
10064 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
10065 driver (see @ref{The GNAT Driver and Project Files}).
10069 * Performance Considerations::
10070 * Text_IO Suggestions::
10071 * Reducing Size of Ada Executables with gnatelim::
10072 * Reducing Size of Executables with unused subprogram/data elimination::
10076 @c *****************************
10077 @node Performance Considerations
10078 @section Performance Considerations
10081 The GNAT system provides a number of options that allow a trade-off
10086 performance of the generated code
10089 speed of compilation
10092 minimization of dependences and recompilation
10095 the degree of run-time checking.
10099 The defaults (if no options are selected) aim at improving the speed
10100 of compilation and minimizing dependences, at the expense of performance
10101 of the generated code:
10108 no inlining of subprogram calls
10111 all run-time checks enabled except overflow and elaboration checks
10115 These options are suitable for most program development purposes. This
10116 chapter describes how you can modify these choices, and also provides
10117 some guidelines on debugging optimized code.
10120 * Controlling Run-Time Checks::
10121 * Use of Restrictions::
10122 * Optimization Levels::
10123 * Debugging Optimized Code::
10124 * Inlining of Subprograms::
10125 * Other Optimization Switches::
10126 * Optimization and Strict Aliasing::
10129 * Coverage Analysis::
10133 @node Controlling Run-Time Checks
10134 @subsection Controlling Run-Time Checks
10137 By default, GNAT generates all run-time checks, except integer overflow
10138 checks, stack overflow checks, and checks for access before elaboration on
10139 subprogram calls. The latter are not required in default mode, because all
10140 necessary checking is done at compile time.
10141 @cindex @option{-gnatp} (@command{gcc})
10142 @cindex @option{-gnato} (@command{gcc})
10143 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10144 be modified. @xref{Run-Time Checks}.
10146 Our experience is that the default is suitable for most development
10149 We treat integer overflow specially because these
10150 are quite expensive and in our experience are not as important as other
10151 run-time checks in the development process. Note that division by zero
10152 is not considered an overflow check, and divide by zero checks are
10153 generated where required by default.
10155 Elaboration checks are off by default, and also not needed by default, since
10156 GNAT uses a static elaboration analysis approach that avoids the need for
10157 run-time checking. This manual contains a full chapter discussing the issue
10158 of elaboration checks, and if the default is not satisfactory for your use,
10159 you should read this chapter.
10161 For validity checks, the minimal checks required by the Ada Reference
10162 Manual (for case statements and assignments to array elements) are on
10163 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10164 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10165 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10166 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10167 are also suppressed entirely if @option{-gnatp} is used.
10169 @cindex Overflow checks
10170 @cindex Checks, overflow
10173 @cindex pragma Suppress
10174 @cindex pragma Unsuppress
10175 Note that the setting of the switches controls the default setting of
10176 the checks. They may be modified using either @code{pragma Suppress} (to
10177 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10178 checks) in the program source.
10180 @node Use of Restrictions
10181 @subsection Use of Restrictions
10184 The use of pragma Restrictions allows you to control which features are
10185 permitted in your program. Apart from the obvious point that if you avoid
10186 relatively expensive features like finalization (enforceable by the use
10187 of pragma Restrictions (No_Finalization), the use of this pragma does not
10188 affect the generated code in most cases.
10190 One notable exception to this rule is that the possibility of task abort
10191 results in some distributed overhead, particularly if finalization or
10192 exception handlers are used. The reason is that certain sections of code
10193 have to be marked as non-abortable.
10195 If you use neither the @code{abort} statement, nor asynchronous transfer
10196 of control (@code{select @dots{} then abort}), then this distributed overhead
10197 is removed, which may have a general positive effect in improving
10198 overall performance. Especially code involving frequent use of tasking
10199 constructs and controlled types will show much improved performance.
10200 The relevant restrictions pragmas are
10202 @smallexample @c ada
10203 pragma Restrictions (No_Abort_Statements);
10204 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10208 It is recommended that these restriction pragmas be used if possible. Note
10209 that this also means that you can write code without worrying about the
10210 possibility of an immediate abort at any point.
10212 @node Optimization Levels
10213 @subsection Optimization Levels
10214 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10217 Without any optimization ^option,^qualifier,^
10218 the compiler's goal is to reduce the cost of
10219 compilation and to make debugging produce the expected results.
10220 Statements are independent: if you stop the program with a breakpoint between
10221 statements, you can then assign a new value to any variable or change
10222 the program counter to any other statement in the subprogram and get exactly
10223 the results you would expect from the source code.
10225 Turning on optimization makes the compiler attempt to improve the
10226 performance and/or code size at the expense of compilation time and
10227 possibly the ability to debug the program.
10229 If you use multiple
10230 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10231 the last such option is the one that is effective.
10234 The default is optimization off. This results in the fastest compile
10235 times, but GNAT makes absolutely no attempt to optimize, and the
10236 generated programs are considerably larger and slower than when
10237 optimization is enabled. You can use the
10239 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10240 @option{-O2}, @option{-O3}, and @option{-Os})
10243 @code{OPTIMIZE} qualifier
10245 to @command{gcc} to control the optimization level:
10248 @item ^-O0^/OPTIMIZE=NONE^
10249 No optimization (the default);
10250 generates unoptimized code but has
10251 the fastest compilation time.
10253 Note that many other compilers do fairly extensive optimization
10254 even if ``no optimization'' is specified. With gcc, it is
10255 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10256 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10257 really does mean no optimization at all. This difference between
10258 gcc and other compilers should be kept in mind when doing
10259 performance comparisons.
10261 @item ^-O1^/OPTIMIZE=SOME^
10262 Moderate optimization;
10263 optimizes reasonably well but does not
10264 degrade compilation time significantly.
10266 @item ^-O2^/OPTIMIZE=ALL^
10268 @itemx /OPTIMIZE=DEVELOPMENT
10271 generates highly optimized code and has
10272 the slowest compilation time.
10274 @item ^-O3^/OPTIMIZE=INLINING^
10275 Full optimization as in @option{-O2};
10276 also uses more aggressive automatic inlining of subprograms within a unit
10277 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10279 @item ^-Os^/OPTIMIZE=SPACE^
10280 Optimize space usage (code and data) of resulting program.
10284 Higher optimization levels perform more global transformations on the
10285 program and apply more expensive analysis algorithms in order to generate
10286 faster and more compact code. The price in compilation time, and the
10287 resulting improvement in execution time,
10288 both depend on the particular application and the hardware environment.
10289 You should experiment to find the best level for your application.
10291 Since the precise set of optimizations done at each level will vary from
10292 release to release (and sometime from target to target), it is best to think
10293 of the optimization settings in general terms.
10294 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10295 the GNU Compiler Collection (GCC)}, for details about
10296 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10297 individually enable or disable specific optimizations.
10299 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10300 been tested extensively at all optimization levels. There are some bugs
10301 which appear only with optimization turned on, but there have also been
10302 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10303 level of optimization does not improve the reliability of the code
10304 generator, which in practice is highly reliable at all optimization
10307 Note regarding the use of @option{-O3}: The use of this optimization level
10308 is generally discouraged with GNAT, since it often results in larger
10309 executables which may run more slowly. See further discussion of this point
10310 in @ref{Inlining of Subprograms}.
10312 @node Debugging Optimized Code
10313 @subsection Debugging Optimized Code
10314 @cindex Debugging optimized code
10315 @cindex Optimization and debugging
10318 Although it is possible to do a reasonable amount of debugging at
10320 nonzero optimization levels,
10321 the higher the level the more likely that
10324 @option{/OPTIMIZE} settings other than @code{NONE},
10325 such settings will make it more likely that
10327 source-level constructs will have been eliminated by optimization.
10328 For example, if a loop is strength-reduced, the loop
10329 control variable may be completely eliminated and thus cannot be
10330 displayed in the debugger.
10331 This can only happen at @option{-O2} or @option{-O3}.
10332 Explicit temporary variables that you code might be eliminated at
10333 ^level^setting^ @option{-O1} or higher.
10335 The use of the @option{^-g^/DEBUG^} switch,
10336 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10337 which is needed for source-level debugging,
10338 affects the size of the program executable on disk,
10339 and indeed the debugging information can be quite large.
10340 However, it has no effect on the generated code (and thus does not
10341 degrade performance)
10343 Since the compiler generates debugging tables for a compilation unit before
10344 it performs optimizations, the optimizing transformations may invalidate some
10345 of the debugging data. You therefore need to anticipate certain
10346 anomalous situations that may arise while debugging optimized code.
10347 These are the most common cases:
10351 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10353 the PC bouncing back and forth in the code. This may result from any of
10354 the following optimizations:
10358 @i{Common subexpression elimination:} using a single instance of code for a
10359 quantity that the source computes several times. As a result you
10360 may not be able to stop on what looks like a statement.
10363 @i{Invariant code motion:} moving an expression that does not change within a
10364 loop, to the beginning of the loop.
10367 @i{Instruction scheduling:} moving instructions so as to
10368 overlap loads and stores (typically) with other code, or in
10369 general to move computations of values closer to their uses. Often
10370 this causes you to pass an assignment statement without the assignment
10371 happening and then later bounce back to the statement when the
10372 value is actually needed. Placing a breakpoint on a line of code
10373 and then stepping over it may, therefore, not always cause all the
10374 expected side-effects.
10378 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10379 two identical pieces of code are merged and the program counter suddenly
10380 jumps to a statement that is not supposed to be executed, simply because
10381 it (and the code following) translates to the same thing as the code
10382 that @emph{was} supposed to be executed. This effect is typically seen in
10383 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10384 a @code{break} in a C @code{^switch^switch^} statement.
10387 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10388 There are various reasons for this effect:
10392 In a subprogram prologue, a parameter may not yet have been moved to its
10396 A variable may be dead, and its register re-used. This is
10397 probably the most common cause.
10400 As mentioned above, the assignment of a value to a variable may
10404 A variable may be eliminated entirely by value propagation or
10405 other means. In this case, GCC may incorrectly generate debugging
10406 information for the variable
10410 In general, when an unexpected value appears for a local variable or parameter
10411 you should first ascertain if that value was actually computed by
10412 your program, as opposed to being incorrectly reported by the debugger.
10414 array elements in an object designated by an access value
10415 are generally less of a problem, once you have ascertained that the access
10417 Typically, this means checking variables in the preceding code and in the
10418 calling subprogram to verify that the value observed is explainable from other
10419 values (one must apply the procedure recursively to those
10420 other values); or re-running the code and stopping a little earlier
10421 (perhaps before the call) and stepping to better see how the variable obtained
10422 the value in question; or continuing to step @emph{from} the point of the
10423 strange value to see if code motion had simply moved the variable's
10428 In light of such anomalies, a recommended technique is to use @option{-O0}
10429 early in the software development cycle, when extensive debugging capabilities
10430 are most needed, and then move to @option{-O1} and later @option{-O2} as
10431 the debugger becomes less critical.
10432 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10433 a release management issue.
10435 Note that if you use @option{-g} you can then use the @command{strip} program
10436 on the resulting executable,
10437 which removes both debugging information and global symbols.
10440 @node Inlining of Subprograms
10441 @subsection Inlining of Subprograms
10444 A call to a subprogram in the current unit is inlined if all the
10445 following conditions are met:
10449 The optimization level is at least @option{-O1}.
10452 The called subprogram is suitable for inlining: It must be small enough
10453 and not contain something that @command{gcc} cannot support in inlined
10457 @cindex pragma Inline
10459 Any one of the following applies: @code{pragma Inline} is applied to the
10460 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10461 subprogram is local to the unit and called once from within it; the
10462 subprogram is small and optimization level @option{-O2} is specified;
10463 optimization level @option{-O3}) is specified.
10467 Calls to subprograms in @code{with}'ed units are normally not inlined.
10468 To achieve actual inlining (that is, replacement of the call by the code
10469 in the body of the subprogram), the following conditions must all be true.
10473 The optimization level is at least @option{-O1}.
10476 The called subprogram is suitable for inlining: It must be small enough
10477 and not contain something that @command{gcc} cannot support in inlined
10481 The call appears in a body (not in a package spec).
10484 There is a @code{pragma Inline} for the subprogram.
10487 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10490 Even if all these conditions are met, it may not be possible for
10491 the compiler to inline the call, due to the length of the body,
10492 or features in the body that make it impossible for the compiler
10493 to do the inlining.
10495 Note that specifying the @option{-gnatn} switch causes additional
10496 compilation dependencies. Consider the following:
10498 @smallexample @c ada
10518 With the default behavior (no @option{-gnatn} switch specified), the
10519 compilation of the @code{Main} procedure depends only on its own source,
10520 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10521 means that editing the body of @code{R} does not require recompiling
10524 On the other hand, the call @code{R.Q} is not inlined under these
10525 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10526 is compiled, the call will be inlined if the body of @code{Q} is small
10527 enough, but now @code{Main} depends on the body of @code{R} in
10528 @file{r.adb} as well as on the spec. This means that if this body is edited,
10529 the main program must be recompiled. Note that this extra dependency
10530 occurs whether or not the call is in fact inlined by @command{gcc}.
10532 The use of front end inlining with @option{-gnatN} generates similar
10533 additional dependencies.
10535 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10536 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10537 can be used to prevent
10538 all inlining. This switch overrides all other conditions and ensures
10539 that no inlining occurs. The extra dependences resulting from
10540 @option{-gnatn} will still be active, even if
10541 this switch is used to suppress the resulting inlining actions.
10543 @cindex @option{-fno-inline-functions} (@command{gcc})
10544 Note: The @option{-fno-inline-functions} switch can be used to prevent
10545 automatic inlining of subprograms if @option{-O3} is used.
10547 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10548 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10549 automatic inlining of small subprograms if @option{-O2} is used.
10551 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10552 Note: The @option{-fno-inline-functions-called-once} switch
10553 can be used to prevent inlining of subprograms local to the unit
10554 and called once from within it if @option{-O1} is used.
10556 Note regarding the use of @option{-O3}: There is no difference in inlining
10557 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10558 pragma @code{Inline} assuming the use of @option{-gnatn}
10559 or @option{-gnatN} (the switches that activate inlining). If you have used
10560 pragma @code{Inline} in appropriate cases, then it is usually much better
10561 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10562 in this case only has the effect of inlining subprograms you did not
10563 think should be inlined. We often find that the use of @option{-O3} slows
10564 down code by performing excessive inlining, leading to increased instruction
10565 cache pressure from the increased code size. So the bottom line here is
10566 that you should not automatically assume that @option{-O3} is better than
10567 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10568 it actually improves performance.
10570 @node Other Optimization Switches
10571 @subsection Other Optimization Switches
10572 @cindex Optimization Switches
10574 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10575 @command{gcc} optimization switches are potentially usable. These switches
10576 have not been extensively tested with GNAT but can generally be expected
10577 to work. Examples of switches in this category are
10578 @option{-funroll-loops} and
10579 the various target-specific @option{-m} options (in particular, it has been
10580 observed that @option{-march=pentium4} can significantly improve performance
10581 on appropriate machines). For full details of these switches, see
10582 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10583 the GNU Compiler Collection (GCC)}.
10585 @node Optimization and Strict Aliasing
10586 @subsection Optimization and Strict Aliasing
10588 @cindex Strict Aliasing
10589 @cindex No_Strict_Aliasing
10592 The strong typing capabilities of Ada allow an optimizer to generate
10593 efficient code in situations where other languages would be forced to
10594 make worst case assumptions preventing such optimizations. Consider
10595 the following example:
10597 @smallexample @c ada
10600 type Int1 is new Integer;
10601 type Int2 is new Integer;
10602 type Int1A is access Int1;
10603 type Int2A is access Int2;
10610 for J in Data'Range loop
10611 if Data (J) = Int1V.all then
10612 Int2V.all := Int2V.all + 1;
10621 In this example, since the variable @code{Int1V} can only access objects
10622 of type @code{Int1}, and @code{Int2V} can only access objects of type
10623 @code{Int2}, there is no possibility that the assignment to
10624 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10625 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10626 for all iterations of the loop and avoid the extra memory reference
10627 required to dereference it each time through the loop.
10629 This kind of optimization, called strict aliasing analysis, is
10630 triggered by specifying an optimization level of @option{-O2} or
10631 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10632 when access values are involved.
10634 However, although this optimization is always correct in terms of
10635 the formal semantics of the Ada Reference Manual, difficulties can
10636 arise if features like @code{Unchecked_Conversion} are used to break
10637 the typing system. Consider the following complete program example:
10639 @smallexample @c ada
10642 type int1 is new integer;
10643 type int2 is new integer;
10644 type a1 is access int1;
10645 type a2 is access int2;
10650 function to_a2 (Input : a1) return a2;
10653 with Unchecked_Conversion;
10655 function to_a2 (Input : a1) return a2 is
10657 new Unchecked_Conversion (a1, a2);
10659 return to_a2u (Input);
10665 with Text_IO; use Text_IO;
10667 v1 : a1 := new int1;
10668 v2 : a2 := to_a2 (v1);
10672 put_line (int1'image (v1.all));
10678 This program prints out 0 in @option{-O0} or @option{-O1}
10679 mode, but it prints out 1 in @option{-O2} mode. That's
10680 because in strict aliasing mode, the compiler can and
10681 does assume that the assignment to @code{v2.all} could not
10682 affect the value of @code{v1.all}, since different types
10685 This behavior is not a case of non-conformance with the standard, since
10686 the Ada RM specifies that an unchecked conversion where the resulting
10687 bit pattern is not a correct value of the target type can result in an
10688 abnormal value and attempting to reference an abnormal value makes the
10689 execution of a program erroneous. That's the case here since the result
10690 does not point to an object of type @code{int2}. This means that the
10691 effect is entirely unpredictable.
10693 However, although that explanation may satisfy a language
10694 lawyer, in practice an applications programmer expects an
10695 unchecked conversion involving pointers to create true
10696 aliases and the behavior of printing 1 seems plain wrong.
10697 In this case, the strict aliasing optimization is unwelcome.
10699 Indeed the compiler recognizes this possibility, and the
10700 unchecked conversion generates a warning:
10703 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10704 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10705 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10709 Unfortunately the problem is recognized when compiling the body of
10710 package @code{p2}, but the actual "bad" code is generated while
10711 compiling the body of @code{m} and this latter compilation does not see
10712 the suspicious @code{Unchecked_Conversion}.
10714 As implied by the warning message, there are approaches you can use to
10715 avoid the unwanted strict aliasing optimization in a case like this.
10717 One possibility is to simply avoid the use of @option{-O2}, but
10718 that is a bit drastic, since it throws away a number of useful
10719 optimizations that do not involve strict aliasing assumptions.
10721 A less drastic approach is to compile the program using the
10722 option @option{-fno-strict-aliasing}. Actually it is only the
10723 unit containing the dereferencing of the suspicious pointer
10724 that needs to be compiled. So in this case, if we compile
10725 unit @code{m} with this switch, then we get the expected
10726 value of zero printed. Analyzing which units might need
10727 the switch can be painful, so a more reasonable approach
10728 is to compile the entire program with options @option{-O2}
10729 and @option{-fno-strict-aliasing}. If the performance is
10730 satisfactory with this combination of options, then the
10731 advantage is that the entire issue of possible "wrong"
10732 optimization due to strict aliasing is avoided.
10734 To avoid the use of compiler switches, the configuration
10735 pragma @code{No_Strict_Aliasing} with no parameters may be
10736 used to specify that for all access types, the strict
10737 aliasing optimization should be suppressed.
10739 However, these approaches are still overkill, in that they causes
10740 all manipulations of all access values to be deoptimized. A more
10741 refined approach is to concentrate attention on the specific
10742 access type identified as problematic.
10744 First, if a careful analysis of uses of the pointer shows
10745 that there are no possible problematic references, then
10746 the warning can be suppressed by bracketing the
10747 instantiation of @code{Unchecked_Conversion} to turn
10750 @smallexample @c ada
10751 pragma Warnings (Off);
10753 new Unchecked_Conversion (a1, a2);
10754 pragma Warnings (On);
10758 Of course that approach is not appropriate for this particular
10759 example, since indeed there is a problematic reference. In this
10760 case we can take one of two other approaches.
10762 The first possibility is to move the instantiation of unchecked
10763 conversion to the unit in which the type is declared. In
10764 this example, we would move the instantiation of
10765 @code{Unchecked_Conversion} from the body of package
10766 @code{p2} to the spec of package @code{p1}. Now the
10767 warning disappears. That's because any use of the
10768 access type knows there is a suspicious unchecked
10769 conversion, and the strict aliasing optimization
10770 is automatically suppressed for the type.
10772 If it is not practical to move the unchecked conversion to the same unit
10773 in which the destination access type is declared (perhaps because the
10774 source type is not visible in that unit), you may use pragma
10775 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10776 same declarative sequence as the declaration of the access type:
10778 @smallexample @c ada
10779 type a2 is access int2;
10780 pragma No_Strict_Aliasing (a2);
10784 Here again, the compiler now knows that the strict aliasing optimization
10785 should be suppressed for any reference to type @code{a2} and the
10786 expected behavior is obtained.
10788 Finally, note that although the compiler can generate warnings for
10789 simple cases of unchecked conversions, there are tricker and more
10790 indirect ways of creating type incorrect aliases which the compiler
10791 cannot detect. Examples are the use of address overlays and unchecked
10792 conversions involving composite types containing access types as
10793 components. In such cases, no warnings are generated, but there can
10794 still be aliasing problems. One safe coding practice is to forbid the
10795 use of address clauses for type overlaying, and to allow unchecked
10796 conversion only for primitive types. This is not really a significant
10797 restriction since any possible desired effect can be achieved by
10798 unchecked conversion of access values.
10800 The aliasing analysis done in strict aliasing mode can certainly
10801 have significant benefits. We have seen cases of large scale
10802 application code where the time is increased by up to 5% by turning
10803 this optimization off. If you have code that includes significant
10804 usage of unchecked conversion, you might want to just stick with
10805 @option{-O1} and avoid the entire issue. If you get adequate
10806 performance at this level of optimization level, that's probably
10807 the safest approach. If tests show that you really need higher
10808 levels of optimization, then you can experiment with @option{-O2}
10809 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10810 has on size and speed of the code. If you really need to use
10811 @option{-O2} with strict aliasing in effect, then you should
10812 review any uses of unchecked conversion of access types,
10813 particularly if you are getting the warnings described above.
10816 @node Coverage Analysis
10817 @subsection Coverage Analysis
10820 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10821 the user to determine the distribution of execution time across a program,
10822 @pxref{Profiling} for details of usage.
10826 @node Text_IO Suggestions
10827 @section @code{Text_IO} Suggestions
10828 @cindex @code{Text_IO} and performance
10831 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10832 the requirement of maintaining page and line counts. If performance
10833 is critical, a recommendation is to use @code{Stream_IO} instead of
10834 @code{Text_IO} for volume output, since this package has less overhead.
10836 If @code{Text_IO} must be used, note that by default output to the standard
10837 output and standard error files is unbuffered (this provides better
10838 behavior when output statements are used for debugging, or if the
10839 progress of a program is observed by tracking the output, e.g. by
10840 using the Unix @command{tail -f} command to watch redirected output.
10842 If you are generating large volumes of output with @code{Text_IO} and
10843 performance is an important factor, use a designated file instead
10844 of the standard output file, or change the standard output file to
10845 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10849 @node Reducing Size of Ada Executables with gnatelim
10850 @section Reducing Size of Ada Executables with @code{gnatelim}
10854 This section describes @command{gnatelim}, a tool which detects unused
10855 subprograms and helps the compiler to create a smaller executable for your
10860 * Running gnatelim::
10861 * Processing Precompiled Libraries::
10862 * Correcting the List of Eliminate Pragmas::
10863 * Making Your Executables Smaller::
10864 * Summary of the gnatelim Usage Cycle::
10867 @node About gnatelim
10868 @subsection About @code{gnatelim}
10871 When a program shares a set of Ada
10872 packages with other programs, it may happen that this program uses
10873 only a fraction of the subprograms defined in these packages. The code
10874 created for these unused subprograms increases the size of the executable.
10876 @code{gnatelim} tracks unused subprograms in an Ada program and
10877 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10878 subprograms that are declared but never called. By placing the list of
10879 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10880 recompiling your program, you may decrease the size of its executable,
10881 because the compiler will not generate the code for 'eliminated' subprograms.
10882 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10883 information about this pragma.
10885 @code{gnatelim} needs as its input data the name of the main subprogram.
10887 If a set of source files is specified as @code{gnatelim} arguments, it
10888 treats these files as a complete set of sources making up a program to
10889 analyse, and analyses only these sources.
10891 After a full successful build of the main subprogram @code{gnatelim} can be
10892 called without specifying sources to analyse, in this case it computes
10893 the source closure of the main unit from the @file{ALI} files.
10895 The following command will create the set of @file{ALI} files needed for
10899 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10902 Note that @code{gnatelim} does not need object files.
10904 @node Running gnatelim
10905 @subsection Running @code{gnatelim}
10908 @code{gnatelim} has the following command-line interface:
10911 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10915 @var{main_unit_name} should be a name of a source file that contains the main
10916 subprogram of a program (partition).
10918 Each @var{filename} is the name (including the extension) of a source
10919 file to process. ``Wildcards'' are allowed, and
10920 the file name may contain path information.
10922 @samp{@var{gcc_switches}} is a list of switches for
10923 @command{gcc}. They will be passed on to all compiler invocations made by
10924 @command{gnatelim} to generate the ASIS trees. Here you can provide
10925 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10926 use the @option{-gnatec} switch to set the configuration file,
10927 use the @option{-gnat05} switch if sources should be compiled in
10930 @code{gnatelim} has the following switches:
10934 @item ^-files^/FILES^=@var{filename}
10935 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10936 Take the argument source files from the specified file. This file should be an
10937 ordinary text file containing file names separated by spaces or
10938 line breaks. You can use this switch more than once in the same call to
10939 @command{gnatelim}. You also can combine this switch with
10940 an explicit list of files.
10943 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10944 Duplicate all the output sent to @file{stderr} into a log file. The log file
10945 is named @file{gnatelim.log} and is located in the current directory.
10947 @item ^-log^/LOGFILE^=@var{filename}
10948 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10949 Duplicate all the output sent to @file{stderr} into a specified log file.
10951 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10952 @item ^--no-elim-dispatch^/NO_DISPATCH^
10953 Do not generate pragmas for dispatching operations.
10955 @item ^--ignore^/IGNORE^=@var{filename}
10956 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
10957 Do not generate pragmas for subprograms declared in the sources
10958 listed in a specified file
10960 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10961 @item ^-o^/OUTPUT^=@var{report_file}
10962 Put @command{gnatelim} output into a specified file. If this file already exists,
10963 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10967 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10968 Quiet mode: by default @code{gnatelim} outputs to the standard error
10969 stream the number of program units left to be processed. This option turns
10972 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10974 Print out execution time.
10976 @item ^-v^/VERBOSE^
10977 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10978 Verbose mode: @code{gnatelim} version information is printed as Ada
10979 comments to the standard output stream. Also, in addition to the number of
10980 program units left @code{gnatelim} will output the name of the current unit
10983 @item ^-wq^/WARNINGS=QUIET^
10984 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10985 Quiet warning mode - some warnings are suppressed. In particular warnings that
10986 indicate that the analysed set of sources is incomplete to make up a
10987 partition and that some subprogram bodies are missing are not generated.
10990 @node Processing Precompiled Libraries
10991 @subsection Processing Precompiled Libraries
10994 If some program uses a precompiled Ada library, it can be processed by
10995 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10996 Eliminate pragma for a subprogram if the body of this subprogram has not
10997 been analysed, this is a typical case for subprograms from precompiled
10998 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10999 warnings about missing source files and non-analyzed subprogram bodies
11000 that can be generated when processing precompiled Ada libraries.
11002 @node Correcting the List of Eliminate Pragmas
11003 @subsection Correcting the List of Eliminate Pragmas
11006 In some rare cases @code{gnatelim} may try to eliminate
11007 subprograms that are actually called in the program. In this case, the
11008 compiler will generate an error message of the form:
11011 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11015 You will need to manually remove the wrong @code{Eliminate} pragmas from
11016 the configuration file indicated in the error message. You should recompile
11017 your program from scratch after that, because you need a consistent
11018 configuration file(s) during the entire compilation.
11020 @node Making Your Executables Smaller
11021 @subsection Making Your Executables Smaller
11024 In order to get a smaller executable for your program you now have to
11025 recompile the program completely with the configuration file containing
11026 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11027 @file{gnat.adc} file located in your current directory, just do:
11030 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11034 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11035 recompile everything
11036 with the set of pragmas @code{Eliminate} that you have obtained with
11037 @command{gnatelim}).
11039 Be aware that the set of @code{Eliminate} pragmas is specific to each
11040 program. It is not recommended to merge sets of @code{Eliminate}
11041 pragmas created for different programs in one configuration file.
11043 @node Summary of the gnatelim Usage Cycle
11044 @subsection Summary of the @code{gnatelim} Usage Cycle
11047 Here is a quick summary of the steps to be taken in order to reduce
11048 the size of your executables with @code{gnatelim}. You may use
11049 other GNAT options to control the optimization level,
11050 to produce the debugging information, to set search path, etc.
11054 Create a complete set of @file{ALI} files (if the program has not been
11058 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11062 Generate a list of @code{Eliminate} pragmas in default configuration file
11063 @file{gnat.adc} in the current directory
11066 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11069 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11074 Recompile the application
11077 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11082 @node Reducing Size of Executables with unused subprogram/data elimination
11083 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11084 @findex unused subprogram/data elimination
11087 This section describes how you can eliminate unused subprograms and data from
11088 your executable just by setting options at compilation time.
11091 * About unused subprogram/data elimination::
11092 * Compilation options::
11093 * Example of unused subprogram/data elimination::
11096 @node About unused subprogram/data elimination
11097 @subsection About unused subprogram/data elimination
11100 By default, an executable contains all code and data of its composing objects
11101 (directly linked or coming from statically linked libraries), even data or code
11102 never used by this executable.
11104 This feature will allow you to eliminate such unused code from your
11105 executable, making it smaller (in disk and in memory).
11107 This functionality is available on all Linux platforms except for the IA-64
11108 architecture and on all cross platforms using the ELF binary file format.
11109 In both cases GNU binutils version 2.16 or later are required to enable it.
11111 @node Compilation options
11112 @subsection Compilation options
11115 The operation of eliminating the unused code and data from the final executable
11116 is directly performed by the linker.
11118 In order to do this, it has to work with objects compiled with the
11120 @option{-ffunction-sections} @option{-fdata-sections}.
11121 @cindex @option{-ffunction-sections} (@command{gcc})
11122 @cindex @option{-fdata-sections} (@command{gcc})
11123 These options are usable with C and Ada files.
11124 They will place respectively each
11125 function or data in a separate section in the resulting object file.
11127 Once the objects and static libraries are created with these options, the
11128 linker can perform the dead code elimination. You can do this by setting
11129 the @option{-Wl,--gc-sections} option to gcc command or in the
11130 @option{-largs} section of @command{gnatmake}. This will perform a
11131 garbage collection of code and data never referenced.
11133 If the linker performs a partial link (@option{-r} ld linker option), then you
11134 will need to provide one or several entry point using the
11135 @option{-e} / @option{--entry} ld option.
11137 Note that objects compiled without the @option{-ffunction-sections} and
11138 @option{-fdata-sections} options can still be linked with the executable.
11139 However, no dead code elimination will be performed on those objects (they will
11142 The GNAT static library is now compiled with -ffunction-sections and
11143 -fdata-sections on some platforms. This allows you to eliminate the unused code
11144 and data of the GNAT library from your executable.
11146 @node Example of unused subprogram/data elimination
11147 @subsection Example of unused subprogram/data elimination
11150 Here is a simple example:
11152 @smallexample @c ada
11161 Used_Data : Integer;
11162 Unused_Data : Integer;
11164 procedure Used (Data : Integer);
11165 procedure Unused (Data : Integer);
11168 package body Aux is
11169 procedure Used (Data : Integer) is
11174 procedure Unused (Data : Integer) is
11176 Unused_Data := Data;
11182 @code{Unused} and @code{Unused_Data} are never referenced in this code
11183 excerpt, and hence they may be safely removed from the final executable.
11188 $ nm test | grep used
11189 020015f0 T aux__unused
11190 02005d88 B aux__unused_data
11191 020015cc T aux__used
11192 02005d84 B aux__used_data
11194 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11195 -largs -Wl,--gc-sections
11197 $ nm test | grep used
11198 02005350 T aux__used
11199 0201ffe0 B aux__used_data
11203 It can be observed that the procedure @code{Unused} and the object
11204 @code{Unused_Data} are removed by the linker when using the
11205 appropriate options.
11207 @c ********************************
11208 @node Renaming Files Using gnatchop
11209 @chapter Renaming Files Using @code{gnatchop}
11213 This chapter discusses how to handle files with multiple units by using
11214 the @code{gnatchop} utility. This utility is also useful in renaming
11215 files to meet the standard GNAT default file naming conventions.
11218 * Handling Files with Multiple Units::
11219 * Operating gnatchop in Compilation Mode::
11220 * Command Line for gnatchop::
11221 * Switches for gnatchop::
11222 * Examples of gnatchop Usage::
11225 @node Handling Files with Multiple Units
11226 @section Handling Files with Multiple Units
11229 The basic compilation model of GNAT requires that a file submitted to the
11230 compiler have only one unit and there be a strict correspondence
11231 between the file name and the unit name.
11233 The @code{gnatchop} utility allows both of these rules to be relaxed,
11234 allowing GNAT to process files which contain multiple compilation units
11235 and files with arbitrary file names. @code{gnatchop}
11236 reads the specified file and generates one or more output files,
11237 containing one unit per file. The unit and the file name correspond,
11238 as required by GNAT.
11240 If you want to permanently restructure a set of ``foreign'' files so that
11241 they match the GNAT rules, and do the remaining development using the
11242 GNAT structure, you can simply use @command{gnatchop} once, generate the
11243 new set of files and work with them from that point on.
11245 Alternatively, if you want to keep your files in the ``foreign'' format,
11246 perhaps to maintain compatibility with some other Ada compilation
11247 system, you can set up a procedure where you use @command{gnatchop} each
11248 time you compile, regarding the source files that it writes as temporary
11249 files that you throw away.
11251 Note that if your file containing multiple units starts with a byte order
11252 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11253 will each start with a copy of this BOM, meaning that they can be compiled
11254 automatically in UTF-8 mode without needing to specify an explicit encoding.
11256 @node Operating gnatchop in Compilation Mode
11257 @section Operating gnatchop in Compilation Mode
11260 The basic function of @code{gnatchop} is to take a file with multiple units
11261 and split it into separate files. The boundary between files is reasonably
11262 clear, except for the issue of comments and pragmas. In default mode, the
11263 rule is that any pragmas between units belong to the previous unit, except
11264 that configuration pragmas always belong to the following unit. Any comments
11265 belong to the following unit. These rules
11266 almost always result in the right choice of
11267 the split point without needing to mark it explicitly and most users will
11268 find this default to be what they want. In this default mode it is incorrect to
11269 submit a file containing only configuration pragmas, or one that ends in
11270 configuration pragmas, to @code{gnatchop}.
11272 However, using a special option to activate ``compilation mode'',
11274 can perform another function, which is to provide exactly the semantics
11275 required by the RM for handling of configuration pragmas in a compilation.
11276 In the absence of configuration pragmas (at the main file level), this
11277 option has no effect, but it causes such configuration pragmas to be handled
11278 in a quite different manner.
11280 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11281 only configuration pragmas, then this file is appended to the
11282 @file{gnat.adc} file in the current directory. This behavior provides
11283 the required behavior described in the RM for the actions to be taken
11284 on submitting such a file to the compiler, namely that these pragmas
11285 should apply to all subsequent compilations in the same compilation
11286 environment. Using GNAT, the current directory, possibly containing a
11287 @file{gnat.adc} file is the representation
11288 of a compilation environment. For more information on the
11289 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11291 Second, in compilation mode, if @code{gnatchop}
11292 is given a file that starts with
11293 configuration pragmas, and contains one or more units, then these
11294 configuration pragmas are prepended to each of the chopped files. This
11295 behavior provides the required behavior described in the RM for the
11296 actions to be taken on compiling such a file, namely that the pragmas
11297 apply to all units in the compilation, but not to subsequently compiled
11300 Finally, if configuration pragmas appear between units, they are appended
11301 to the previous unit. This results in the previous unit being illegal,
11302 since the compiler does not accept configuration pragmas that follow
11303 a unit. This provides the required RM behavior that forbids configuration
11304 pragmas other than those preceding the first compilation unit of a
11307 For most purposes, @code{gnatchop} will be used in default mode. The
11308 compilation mode described above is used only if you need exactly
11309 accurate behavior with respect to compilations, and you have files
11310 that contain multiple units and configuration pragmas. In this
11311 circumstance the use of @code{gnatchop} with the compilation mode
11312 switch provides the required behavior, and is for example the mode
11313 in which GNAT processes the ACVC tests.
11315 @node Command Line for gnatchop
11316 @section Command Line for @code{gnatchop}
11319 The @code{gnatchop} command has the form:
11322 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11323 @c @ovar{directory}
11324 @c Expanding @ovar macro inline (explanation in macro def comments)
11325 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11326 @r{[}@var{directory}@r{]}
11330 The only required argument is the file name of the file to be chopped.
11331 There are no restrictions on the form of this file name. The file itself
11332 contains one or more Ada units, in normal GNAT format, concatenated
11333 together. As shown, more than one file may be presented to be chopped.
11335 When run in default mode, @code{gnatchop} generates one output file in
11336 the current directory for each unit in each of the files.
11338 @var{directory}, if specified, gives the name of the directory to which
11339 the output files will be written. If it is not specified, all files are
11340 written to the current directory.
11342 For example, given a
11343 file called @file{hellofiles} containing
11345 @smallexample @c ada
11350 with Text_IO; use Text_IO;
11353 Put_Line ("Hello");
11363 $ gnatchop ^hellofiles^HELLOFILES.^
11367 generates two files in the current directory, one called
11368 @file{hello.ads} containing the single line that is the procedure spec,
11369 and the other called @file{hello.adb} containing the remaining text. The
11370 original file is not affected. The generated files can be compiled in
11374 When gnatchop is invoked on a file that is empty or that contains only empty
11375 lines and/or comments, gnatchop will not fail, but will not produce any
11378 For example, given a
11379 file called @file{toto.txt} containing
11381 @smallexample @c ada
11393 $ gnatchop ^toto.txt^TOT.TXT^
11397 will not produce any new file and will result in the following warnings:
11400 toto.txt:1:01: warning: empty file, contains no compilation units
11401 no compilation units found
11402 no source files written
11405 @node Switches for gnatchop
11406 @section Switches for @code{gnatchop}
11409 @command{gnatchop} recognizes the following switches:
11415 @cindex @option{--version} @command{gnatchop}
11416 Display Copyright and version, then exit disregarding all other options.
11419 @cindex @option{--help} @command{gnatchop}
11420 If @option{--version} was not used, display usage, then exit disregarding
11423 @item ^-c^/COMPILATION^
11424 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11425 Causes @code{gnatchop} to operate in compilation mode, in which
11426 configuration pragmas are handled according to strict RM rules. See
11427 previous section for a full description of this mode.
11430 @item -gnat@var{xxx}
11431 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11432 used to parse the given file. Not all @var{xxx} options make sense,
11433 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11434 process a source file that uses Latin-2 coding for identifiers.
11438 Causes @code{gnatchop} to generate a brief help summary to the standard
11439 output file showing usage information.
11441 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11442 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11443 Limit generated file names to the specified number @code{mm}
11445 This is useful if the
11446 resulting set of files is required to be interoperable with systems
11447 which limit the length of file names.
11449 If no value is given, or
11450 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11451 a default of 39, suitable for OpenVMS Alpha
11452 Systems, is assumed
11455 No space is allowed between the @option{-k} and the numeric value. The numeric
11456 value may be omitted in which case a default of @option{-k8},
11458 with DOS-like file systems, is used. If no @option{-k} switch
11460 there is no limit on the length of file names.
11463 @item ^-p^/PRESERVE^
11464 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11465 Causes the file ^modification^creation^ time stamp of the input file to be
11466 preserved and used for the time stamp of the output file(s). This may be
11467 useful for preserving coherency of time stamps in an environment where
11468 @code{gnatchop} is used as part of a standard build process.
11471 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11472 Causes output of informational messages indicating the set of generated
11473 files to be suppressed. Warnings and error messages are unaffected.
11475 @item ^-r^/REFERENCE^
11476 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11477 @findex Source_Reference
11478 Generate @code{Source_Reference} pragmas. Use this switch if the output
11479 files are regarded as temporary and development is to be done in terms
11480 of the original unchopped file. This switch causes
11481 @code{Source_Reference} pragmas to be inserted into each of the
11482 generated files to refers back to the original file name and line number.
11483 The result is that all error messages refer back to the original
11485 In addition, the debugging information placed into the object file (when
11486 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11488 also refers back to this original file so that tools like profilers and
11489 debuggers will give information in terms of the original unchopped file.
11491 If the original file to be chopped itself contains
11492 a @code{Source_Reference}
11493 pragma referencing a third file, then gnatchop respects
11494 this pragma, and the generated @code{Source_Reference} pragmas
11495 in the chopped file refer to the original file, with appropriate
11496 line numbers. This is particularly useful when @code{gnatchop}
11497 is used in conjunction with @code{gnatprep} to compile files that
11498 contain preprocessing statements and multiple units.
11500 @item ^-v^/VERBOSE^
11501 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11502 Causes @code{gnatchop} to operate in verbose mode. The version
11503 number and copyright notice are output, as well as exact copies of
11504 the gnat1 commands spawned to obtain the chop control information.
11506 @item ^-w^/OVERWRITE^
11507 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11508 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11509 fatal error if there is already a file with the same name as a
11510 file it would otherwise output, in other words if the files to be
11511 chopped contain duplicated units. This switch bypasses this
11512 check, and causes all but the last instance of such duplicated
11513 units to be skipped.
11516 @item --GCC=@var{xxxx}
11517 @cindex @option{--GCC=} (@code{gnatchop})
11518 Specify the path of the GNAT parser to be used. When this switch is used,
11519 no attempt is made to add the prefix to the GNAT parser executable.
11523 @node Examples of gnatchop Usage
11524 @section Examples of @code{gnatchop} Usage
11528 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11531 @item gnatchop -w hello_s.ada prerelease/files
11534 Chops the source file @file{hello_s.ada}. The output files will be
11535 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11537 files with matching names in that directory (no files in the current
11538 directory are modified).
11540 @item gnatchop ^archive^ARCHIVE.^
11541 Chops the source file @file{^archive^ARCHIVE.^}
11542 into the current directory. One
11543 useful application of @code{gnatchop} is in sending sets of sources
11544 around, for example in email messages. The required sources are simply
11545 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11547 @command{gnatchop} is used at the other end to reconstitute the original
11550 @item gnatchop file1 file2 file3 direc
11551 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11552 the resulting files in the directory @file{direc}. Note that if any units
11553 occur more than once anywhere within this set of files, an error message
11554 is generated, and no files are written. To override this check, use the
11555 @option{^-w^/OVERWRITE^} switch,
11556 in which case the last occurrence in the last file will
11557 be the one that is output, and earlier duplicate occurrences for a given
11558 unit will be skipped.
11561 @node Configuration Pragmas
11562 @chapter Configuration Pragmas
11563 @cindex Configuration pragmas
11564 @cindex Pragmas, configuration
11567 Configuration pragmas include those pragmas described as
11568 such in the Ada Reference Manual, as well as
11569 implementation-dependent pragmas that are configuration pragmas.
11570 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11571 for details on these additional GNAT-specific configuration pragmas.
11572 Most notably, the pragma @code{Source_File_Name}, which allows
11573 specifying non-default names for source files, is a configuration
11574 pragma. The following is a complete list of configuration pragmas
11575 recognized by GNAT:
11585 Assume_No_Invalid_Values
11590 Compile_Time_Warning
11592 Component_Alignment
11593 Convention_Identifier
11596 Default_Storage_Pool
11602 External_Name_Casing
11605 Float_Representation
11618 Priority_Specific_Dispatching
11621 Propagate_Exceptions
11624 Restricted_Run_Time
11626 Restrictions_Warnings
11628 Short_Circuit_And_Or
11630 Source_File_Name_Project
11633 Suppress_Exception_Locations
11634 Task_Dispatching_Policy
11640 Wide_Character_Encoding
11645 * Handling of Configuration Pragmas::
11646 * The Configuration Pragmas Files::
11649 @node Handling of Configuration Pragmas
11650 @section Handling of Configuration Pragmas
11652 Configuration pragmas may either appear at the start of a compilation
11653 unit, in which case they apply only to that unit, or they may apply to
11654 all compilations performed in a given compilation environment.
11656 GNAT also provides the @code{gnatchop} utility to provide an automatic
11657 way to handle configuration pragmas following the semantics for
11658 compilations (that is, files with multiple units), described in the RM.
11659 See @ref{Operating gnatchop in Compilation Mode} for details.
11660 However, for most purposes, it will be more convenient to edit the
11661 @file{gnat.adc} file that contains configuration pragmas directly,
11662 as described in the following section.
11664 @node The Configuration Pragmas Files
11665 @section The Configuration Pragmas Files
11666 @cindex @file{gnat.adc}
11669 In GNAT a compilation environment is defined by the current
11670 directory at the time that a compile command is given. This current
11671 directory is searched for a file whose name is @file{gnat.adc}. If
11672 this file is present, it is expected to contain one or more
11673 configuration pragmas that will be applied to the current compilation.
11674 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11677 Configuration pragmas may be entered into the @file{gnat.adc} file
11678 either by running @code{gnatchop} on a source file that consists only of
11679 configuration pragmas, or more conveniently by
11680 direct editing of the @file{gnat.adc} file, which is a standard format
11683 In addition to @file{gnat.adc}, additional files containing configuration
11684 pragmas may be applied to the current compilation using the switch
11685 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11686 contains only configuration pragmas. These configuration pragmas are
11687 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11688 is present and switch @option{-gnatA} is not used).
11690 It is allowed to specify several switches @option{-gnatec}, all of which
11691 will be taken into account.
11693 If you are using project file, a separate mechanism is provided using
11694 project attributes, see @ref{Specifying Configuration Pragmas} for more
11698 Of special interest to GNAT OpenVMS Alpha is the following
11699 configuration pragma:
11701 @smallexample @c ada
11703 pragma Extend_System (Aux_DEC);
11708 In the presence of this pragma, GNAT adds to the definition of the
11709 predefined package SYSTEM all the additional types and subprograms that are
11710 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11713 @node Handling Arbitrary File Naming Conventions Using gnatname
11714 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11715 @cindex Arbitrary File Naming Conventions
11718 * Arbitrary File Naming Conventions::
11719 * Running gnatname::
11720 * Switches for gnatname::
11721 * Examples of gnatname Usage::
11724 @node Arbitrary File Naming Conventions
11725 @section Arbitrary File Naming Conventions
11728 The GNAT compiler must be able to know the source file name of a compilation
11729 unit. When using the standard GNAT default file naming conventions
11730 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11731 does not need additional information.
11734 When the source file names do not follow the standard GNAT default file naming
11735 conventions, the GNAT compiler must be given additional information through
11736 a configuration pragmas file (@pxref{Configuration Pragmas})
11738 When the non-standard file naming conventions are well-defined,
11739 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11740 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11741 if the file naming conventions are irregular or arbitrary, a number
11742 of pragma @code{Source_File_Name} for individual compilation units
11744 To help maintain the correspondence between compilation unit names and
11745 source file names within the compiler,
11746 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11749 @node Running gnatname
11750 @section Running @code{gnatname}
11753 The usual form of the @code{gnatname} command is
11756 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11757 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11758 @c Expanding @ovar macro inline (explanation in macro def comments)
11759 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11760 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11764 All of the arguments are optional. If invoked without any argument,
11765 @code{gnatname} will display its usage.
11768 When used with at least one naming pattern, @code{gnatname} will attempt to
11769 find all the compilation units in files that follow at least one of the
11770 naming patterns. To find these compilation units,
11771 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11775 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11776 Each Naming Pattern is enclosed between double quotes (or single
11777 quotes on Windows).
11778 A Naming Pattern is a regular expression similar to the wildcard patterns
11779 used in file names by the Unix shells or the DOS prompt.
11782 @code{gnatname} may be called with several sections of directories/patterns.
11783 Sections are separated by switch @code{--and}. In each section, there must be
11784 at least one pattern. If no directory is specified in a section, the current
11785 directory (or the project directory is @code{-P} is used) is implied.
11786 The options other that the directory switches and the patterns apply globally
11787 even if they are in different sections.
11790 Examples of Naming Patterns are
11799 For a more complete description of the syntax of Naming Patterns,
11800 see the second kind of regular expressions described in @file{g-regexp.ads}
11801 (the ``Glob'' regular expressions).
11804 When invoked with no switch @code{-P}, @code{gnatname} will create a
11805 configuration pragmas file @file{gnat.adc} in the current working directory,
11806 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11809 @node Switches for gnatname
11810 @section Switches for @code{gnatname}
11813 Switches for @code{gnatname} must precede any specified Naming Pattern.
11816 You may specify any of the following switches to @code{gnatname}:
11822 @cindex @option{--version} @command{gnatname}
11823 Display Copyright and version, then exit disregarding all other options.
11826 @cindex @option{--help} @command{gnatname}
11827 If @option{--version} was not used, display usage, then exit disregarding
11831 Start another section of directories/patterns.
11833 @item ^-c^/CONFIG_FILE=^@file{file}
11834 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11835 Create a configuration pragmas file @file{file} (instead of the default
11838 There may be zero, one or more space between @option{-c} and
11841 @file{file} may include directory information. @file{file} must be
11842 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11843 When a switch @option{^-c^/CONFIG_FILE^} is
11844 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11846 @item ^-d^/SOURCE_DIRS=^@file{dir}
11847 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11848 Look for source files in directory @file{dir}. There may be zero, one or more
11849 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11850 When a switch @option{^-d^/SOURCE_DIRS^}
11851 is specified, the current working directory will not be searched for source
11852 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11853 or @option{^-D^/DIR_FILES^} switch.
11854 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11855 If @file{dir} is a relative path, it is relative to the directory of
11856 the configuration pragmas file specified with switch
11857 @option{^-c^/CONFIG_FILE^},
11858 or to the directory of the project file specified with switch
11859 @option{^-P^/PROJECT_FILE^} or,
11860 if neither switch @option{^-c^/CONFIG_FILE^}
11861 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11862 current working directory. The directory
11863 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11865 @item ^-D^/DIRS_FILE=^@file{file}
11866 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11867 Look for source files in all directories listed in text file @file{file}.
11868 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11870 @file{file} must be an existing, readable text file.
11871 Each nonempty line in @file{file} must be a directory.
11872 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11873 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11876 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11877 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11878 Foreign patterns. Using this switch, it is possible to add sources of languages
11879 other than Ada to the list of sources of a project file.
11880 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11883 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11886 will look for Ada units in all files with the @file{.ada} extension,
11887 and will add to the list of file for project @file{prj.gpr} the C files
11888 with extension @file{.^c^C^}.
11891 @cindex @option{^-h^/HELP^} (@code{gnatname})
11892 Output usage (help) information. The output is written to @file{stdout}.
11894 @item ^-P^/PROJECT_FILE=^@file{proj}
11895 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11896 Create or update project file @file{proj}. There may be zero, one or more space
11897 between @option{-P} and @file{proj}. @file{proj} may include directory
11898 information. @file{proj} must be writable.
11899 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11900 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11901 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11903 @item ^-v^/VERBOSE^
11904 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11905 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11906 This includes name of the file written, the name of the directories to search
11907 and, for each file in those directories whose name matches at least one of
11908 the Naming Patterns, an indication of whether the file contains a unit,
11909 and if so the name of the unit.
11911 @item ^-v -v^/VERBOSE /VERBOSE^
11912 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11913 Very Verbose mode. In addition to the output produced in verbose mode,
11914 for each file in the searched directories whose name matches none of
11915 the Naming Patterns, an indication is given that there is no match.
11917 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11918 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11919 Excluded patterns. Using this switch, it is possible to exclude some files
11920 that would match the name patterns. For example,
11922 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11925 will look for Ada units in all files with the @file{.ada} extension,
11926 except those whose names end with @file{_nt.ada}.
11930 @node Examples of gnatname Usage
11931 @section Examples of @code{gnatname} Usage
11935 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11941 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11946 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11947 and be writable. In addition, the directory
11948 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11949 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11952 Note the optional spaces after @option{-c} and @option{-d}.
11957 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11958 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11961 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11962 /EXCLUDED_PATTERN=*_nt_body.ada
11963 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11964 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11968 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11969 even in conjunction with one or several switches
11970 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11971 are used in this example.
11973 @c *****************************************
11974 @c * G N A T P r o j e c t M a n a g e r *
11975 @c *****************************************
11977 @c ------ macros for projects.texi
11978 @c These macros are needed when building the gprbuild documentation, but
11979 @c should have no effect in the gnat user's guide
11981 @macro CODESAMPLE{TXT}
11989 @macro PROJECTFILE{TXT}
11993 @c simulates a newline when in a @CODESAMPLE
12004 @macro TIPHTML{TXT}
12008 @macro IMPORTANT{TXT}
12023 @include projects.texi
12025 @c *****************************************
12026 @c * Cross-referencing tools
12027 @c *****************************************
12029 @node The Cross-Referencing Tools gnatxref and gnatfind
12030 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12035 The compiler generates cross-referencing information (unless
12036 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12037 This information indicates where in the source each entity is declared and
12038 referenced. Note that entities in package Standard are not included, but
12039 entities in all other predefined units are included in the output.
12041 Before using any of these two tools, you need to compile successfully your
12042 application, so that GNAT gets a chance to generate the cross-referencing
12045 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12046 information to provide the user with the capability to easily locate the
12047 declaration and references to an entity. These tools are quite similar,
12048 the difference being that @code{gnatfind} is intended for locating
12049 definitions and/or references to a specified entity or entities, whereas
12050 @code{gnatxref} is oriented to generating a full report of all
12053 To use these tools, you must not compile your application using the
12054 @option{-gnatx} switch on the @command{gnatmake} command line
12055 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12056 information will not be generated.
12058 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12059 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12062 * Switches for gnatxref::
12063 * Switches for gnatfind::
12064 * Project Files for gnatxref and gnatfind::
12065 * Regular Expressions in gnatfind and gnatxref::
12066 * Examples of gnatxref Usage::
12067 * Examples of gnatfind Usage::
12070 @node Switches for gnatxref
12071 @section @code{gnatxref} Switches
12074 The command invocation for @code{gnatxref} is:
12076 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12077 @c Expanding @ovar macro inline (explanation in macro def comments)
12078 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12087 identifies the source files for which a report is to be generated. The
12088 ``with''ed units will be processed too. You must provide at least one file.
12090 These file names are considered to be regular expressions, so for instance
12091 specifying @file{source*.adb} is the same as giving every file in the current
12092 directory whose name starts with @file{source} and whose extension is
12095 You shouldn't specify any directory name, just base names. @command{gnatxref}
12096 and @command{gnatfind} will be able to locate these files by themselves using
12097 the source path. If you specify directories, no result is produced.
12102 The switches can be:
12106 @cindex @option{--version} @command{gnatxref}
12107 Display Copyright and version, then exit disregarding all other options.
12110 @cindex @option{--help} @command{gnatxref}
12111 If @option{--version} was not used, display usage, then exit disregarding
12114 @item ^-a^/ALL_FILES^
12115 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12116 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12117 the read-only files found in the library search path. Otherwise, these files
12118 will be ignored. This option can be used to protect Gnat sources or your own
12119 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12120 much faster, and their output much smaller. Read-only here refers to access
12121 or permissions status in the file system for the current user.
12124 @cindex @option{-aIDIR} (@command{gnatxref})
12125 When looking for source files also look in directory DIR. The order in which
12126 source file search is undertaken is the same as for @command{gnatmake}.
12129 @cindex @option{-aODIR} (@command{gnatxref})
12130 When searching for library and object files, look in directory
12131 DIR. The order in which library files are searched is the same as for
12132 @command{gnatmake}.
12135 @cindex @option{-nostdinc} (@command{gnatxref})
12136 Do not look for sources in the system default directory.
12139 @cindex @option{-nostdlib} (@command{gnatxref})
12140 Do not look for library files in the system default directory.
12142 @item --ext=@var{extension}
12143 @cindex @option{--ext} (@command{gnatxref})
12144 Specify an alternate ali file extension. The default is @code{ali} and other
12145 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12146 switch. Note that if this switch overrides the default, which means that only
12147 the new extension will be considered.
12149 @item --RTS=@var{rts-path}
12150 @cindex @option{--RTS} (@command{gnatxref})
12151 Specifies the default location of the runtime library. Same meaning as the
12152 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12154 @item ^-d^/DERIVED_TYPES^
12155 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12156 If this switch is set @code{gnatxref} will output the parent type
12157 reference for each matching derived types.
12159 @item ^-f^/FULL_PATHNAME^
12160 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12161 If this switch is set, the output file names will be preceded by their
12162 directory (if the file was found in the search path). If this switch is
12163 not set, the directory will not be printed.
12165 @item ^-g^/IGNORE_LOCALS^
12166 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12167 If this switch is set, information is output only for library-level
12168 entities, ignoring local entities. The use of this switch may accelerate
12169 @code{gnatfind} and @code{gnatxref}.
12172 @cindex @option{-IDIR} (@command{gnatxref})
12173 Equivalent to @samp{-aODIR -aIDIR}.
12176 @cindex @option{-pFILE} (@command{gnatxref})
12177 Specify a project file to use @xref{GNAT Project Manager}.
12178 If you need to use the @file{.gpr}
12179 project files, you should use gnatxref through the GNAT driver
12180 (@command{gnat xref -Pproject}).
12182 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12183 project file in the current directory.
12185 If a project file is either specified or found by the tools, then the content
12186 of the source directory and object directory lines are added as if they
12187 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12188 and @samp{^-aO^OBJECT_SEARCH^}.
12190 Output only unused symbols. This may be really useful if you give your
12191 main compilation unit on the command line, as @code{gnatxref} will then
12192 display every unused entity and 'with'ed package.
12196 Instead of producing the default output, @code{gnatxref} will generate a
12197 @file{tags} file that can be used by vi. For examples how to use this
12198 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12199 to the standard output, thus you will have to redirect it to a file.
12205 All these switches may be in any order on the command line, and may even
12206 appear after the file names. They need not be separated by spaces, thus
12207 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12208 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12210 @node Switches for gnatfind
12211 @section @code{gnatfind} Switches
12214 The command line for @code{gnatfind} is:
12217 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12218 @c @r{[}@var{file1} @var{file2} @dots{}]
12219 @c Expanding @ovar macro inline (explanation in macro def comments)
12220 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12221 @r{[}@var{file1} @var{file2} @dots{}@r{]}
12229 An entity will be output only if it matches the regular expression found
12230 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12232 Omitting the pattern is equivalent to specifying @samp{*}, which
12233 will match any entity. Note that if you do not provide a pattern, you
12234 have to provide both a sourcefile and a line.
12236 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12237 for matching purposes. At the current time there is no support for
12238 8-bit codes other than Latin-1, or for wide characters in identifiers.
12241 @code{gnatfind} will look for references, bodies or declarations
12242 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12243 and column @var{column}. See @ref{Examples of gnatfind Usage}
12244 for syntax examples.
12247 is a decimal integer identifying the line number containing
12248 the reference to the entity (or entities) to be located.
12251 is a decimal integer identifying the exact location on the
12252 line of the first character of the identifier for the
12253 entity reference. Columns are numbered from 1.
12255 @item file1 file2 @dots{}
12256 The search will be restricted to these source files. If none are given, then
12257 the search will be done for every library file in the search path.
12258 These file must appear only after the pattern or sourcefile.
12260 These file names are considered to be regular expressions, so for instance
12261 specifying @file{source*.adb} is the same as giving every file in the current
12262 directory whose name starts with @file{source} and whose extension is
12265 The location of the spec of the entity will always be displayed, even if it
12266 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
12267 occurrences of the entity in the separate units of the ones given on the
12268 command line will also be displayed.
12270 Note that if you specify at least one file in this part, @code{gnatfind} may
12271 sometimes not be able to find the body of the subprograms.
12276 At least one of 'sourcefile' or 'pattern' has to be present on
12279 The following switches are available:
12283 @cindex @option{--version} @command{gnatfind}
12284 Display Copyright and version, then exit disregarding all other options.
12287 @cindex @option{--help} @command{gnatfind}
12288 If @option{--version} was not used, display usage, then exit disregarding
12291 @item ^-a^/ALL_FILES^
12292 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12293 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12294 the read-only files found in the library search path. Otherwise, these files
12295 will be ignored. This option can be used to protect Gnat sources or your own
12296 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12297 much faster, and their output much smaller. Read-only here refers to access
12298 or permission status in the file system for the current user.
12301 @cindex @option{-aIDIR} (@command{gnatfind})
12302 When looking for source files also look in directory DIR. The order in which
12303 source file search is undertaken is the same as for @command{gnatmake}.
12306 @cindex @option{-aODIR} (@command{gnatfind})
12307 When searching for library and object files, look in directory
12308 DIR. The order in which library files are searched is the same as for
12309 @command{gnatmake}.
12312 @cindex @option{-nostdinc} (@command{gnatfind})
12313 Do not look for sources in the system default directory.
12316 @cindex @option{-nostdlib} (@command{gnatfind})
12317 Do not look for library files in the system default directory.
12319 @item --ext=@var{extension}
12320 @cindex @option{--ext} (@command{gnatfind})
12321 Specify an alternate ali file extension. The default is @code{ali} and other
12322 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12323 switch. Note that if this switch overrides the default, which means that only
12324 the new extension will be considered.
12326 @item --RTS=@var{rts-path}
12327 @cindex @option{--RTS} (@command{gnatfind})
12328 Specifies the default location of the runtime library. Same meaning as the
12329 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12331 @item ^-d^/DERIVED_TYPE_INFORMATION^
12332 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12333 If this switch is set, then @code{gnatfind} will output the parent type
12334 reference for each matching derived types.
12336 @item ^-e^/EXPRESSIONS^
12337 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12338 By default, @code{gnatfind} accept the simple regular expression set for
12339 @samp{pattern}. If this switch is set, then the pattern will be
12340 considered as full Unix-style regular expression.
12342 @item ^-f^/FULL_PATHNAME^
12343 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12344 If this switch is set, the output file names will be preceded by their
12345 directory (if the file was found in the search path). If this switch is
12346 not set, the directory will not be printed.
12348 @item ^-g^/IGNORE_LOCALS^
12349 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12350 If this switch is set, information is output only for library-level
12351 entities, ignoring local entities. The use of this switch may accelerate
12352 @code{gnatfind} and @code{gnatxref}.
12355 @cindex @option{-IDIR} (@command{gnatfind})
12356 Equivalent to @samp{-aODIR -aIDIR}.
12359 @cindex @option{-pFILE} (@command{gnatfind})
12360 Specify a project file (@pxref{GNAT Project Manager}) to use.
12361 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12362 project file in the current directory.
12364 If a project file is either specified or found by the tools, then the content
12365 of the source directory and object directory lines are added as if they
12366 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12367 @samp{^-aO^/OBJECT_SEARCH^}.
12369 @item ^-r^/REFERENCES^
12370 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12371 By default, @code{gnatfind} will output only the information about the
12372 declaration, body or type completion of the entities. If this switch is
12373 set, the @code{gnatfind} will locate every reference to the entities in
12374 the files specified on the command line (or in every file in the search
12375 path if no file is given on the command line).
12377 @item ^-s^/PRINT_LINES^
12378 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12379 If this switch is set, then @code{gnatfind} will output the content
12380 of the Ada source file lines were the entity was found.
12382 @item ^-t^/TYPE_HIERARCHY^
12383 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12384 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12385 the specified type. It act like -d option but recursively from parent
12386 type to parent type. When this switch is set it is not possible to
12387 specify more than one file.
12392 All these switches may be in any order on the command line, and may even
12393 appear after the file names. They need not be separated by spaces, thus
12394 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12395 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12397 As stated previously, gnatfind will search in every directory in the
12398 search path. You can force it to look only in the current directory if
12399 you specify @code{*} at the end of the command line.
12401 @node Project Files for gnatxref and gnatfind
12402 @section Project Files for @command{gnatxref} and @command{gnatfind}
12405 Project files allow a programmer to specify how to compile its
12406 application, where to find sources, etc. These files are used
12408 primarily by GPS, but they can also be used
12411 @code{gnatxref} and @code{gnatfind}.
12413 A project file name must end with @file{.gpr}. If a single one is
12414 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12415 extract the information from it. If multiple project files are found, none of
12416 them is read, and you have to use the @samp{-p} switch to specify the one
12419 The following lines can be included, even though most of them have default
12420 values which can be used in most cases.
12421 The lines can be entered in any order in the file.
12422 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12423 each line. If you have multiple instances, only the last one is taken into
12428 [default: @code{"^./^[]^"}]
12429 specifies a directory where to look for source files. Multiple @code{src_dir}
12430 lines can be specified and they will be searched in the order they
12434 [default: @code{"^./^[]^"}]
12435 specifies a directory where to look for object and library files. Multiple
12436 @code{obj_dir} lines can be specified, and they will be searched in the order
12439 @item comp_opt=SWITCHES
12440 [default: @code{""}]
12441 creates a variable which can be referred to subsequently by using
12442 the @code{$@{comp_opt@}} notation. This is intended to store the default
12443 switches given to @command{gnatmake} and @command{gcc}.
12445 @item bind_opt=SWITCHES
12446 [default: @code{""}]
12447 creates a variable which can be referred to subsequently by using
12448 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12449 switches given to @command{gnatbind}.
12451 @item link_opt=SWITCHES
12452 [default: @code{""}]
12453 creates a variable which can be referred to subsequently by using
12454 the @samp{$@{link_opt@}} notation. This is intended to store the default
12455 switches given to @command{gnatlink}.
12457 @item main=EXECUTABLE
12458 [default: @code{""}]
12459 specifies the name of the executable for the application. This variable can
12460 be referred to in the following lines by using the @samp{$@{main@}} notation.
12463 @item comp_cmd=COMMAND
12464 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12467 @item comp_cmd=COMMAND
12468 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12470 specifies the command used to compile a single file in the application.
12473 @item make_cmd=COMMAND
12474 [default: @code{"GNAT MAKE $@{main@}
12475 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12476 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12477 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12480 @item make_cmd=COMMAND
12481 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12482 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12483 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12485 specifies the command used to recompile the whole application.
12487 @item run_cmd=COMMAND
12488 [default: @code{"$@{main@}"}]
12489 specifies the command used to run the application.
12491 @item debug_cmd=COMMAND
12492 [default: @code{"gdb $@{main@}"}]
12493 specifies the command used to debug the application
12498 @command{gnatxref} and @command{gnatfind} only take into account the
12499 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12501 @node Regular Expressions in gnatfind and gnatxref
12502 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12505 As specified in the section about @command{gnatfind}, the pattern can be a
12506 regular expression. Actually, there are to set of regular expressions
12507 which are recognized by the program:
12510 @item globbing patterns
12511 These are the most usual regular expression. They are the same that you
12512 generally used in a Unix shell command line, or in a DOS session.
12514 Here is a more formal grammar:
12521 term ::= elmt -- matches elmt
12522 term ::= elmt elmt -- concatenation (elmt then elmt)
12523 term ::= * -- any string of 0 or more characters
12524 term ::= ? -- matches any character
12525 term ::= [char @{char@}] -- matches any character listed
12526 term ::= [char - char] -- matches any character in range
12530 @item full regular expression
12531 The second set of regular expressions is much more powerful. This is the
12532 type of regular expressions recognized by utilities such a @file{grep}.
12534 The following is the form of a regular expression, expressed in Ada
12535 reference manual style BNF is as follows
12542 regexp ::= term @{| term@} -- alternation (term or term @dots{})
12544 term ::= item @{item@} -- concatenation (item then item)
12546 item ::= elmt -- match elmt
12547 item ::= elmt * -- zero or more elmt's
12548 item ::= elmt + -- one or more elmt's
12549 item ::= elmt ? -- matches elmt or nothing
12552 elmt ::= nschar -- matches given character
12553 elmt ::= [nschar @{nschar@}] -- matches any character listed
12554 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12555 elmt ::= [char - char] -- matches chars in given range
12556 elmt ::= \ char -- matches given character
12557 elmt ::= . -- matches any single character
12558 elmt ::= ( regexp ) -- parens used for grouping
12560 char ::= any character, including special characters
12561 nschar ::= any character except ()[].*+?^^^
12565 Following are a few examples:
12569 will match any of the two strings @samp{abcde} and @samp{fghi},
12572 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12573 @samp{abcccd}, and so on,
12576 will match any string which has only lowercase characters in it (and at
12577 least one character.
12582 @node Examples of gnatxref Usage
12583 @section Examples of @code{gnatxref} Usage
12585 @subsection General Usage
12588 For the following examples, we will consider the following units:
12590 @smallexample @c ada
12596 3: procedure Foo (B : in Integer);
12603 1: package body Main is
12604 2: procedure Foo (B : in Integer) is
12615 2: procedure Print (B : Integer);
12624 The first thing to do is to recompile your application (for instance, in
12625 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12626 the cross-referencing information.
12627 You can then issue any of the following commands:
12629 @item gnatxref main.adb
12630 @code{gnatxref} generates cross-reference information for main.adb
12631 and every unit 'with'ed by main.adb.
12633 The output would be:
12641 Decl: main.ads 3:20
12642 Body: main.adb 2:20
12643 Ref: main.adb 4:13 5:13 6:19
12646 Ref: main.adb 6:8 7:8
12656 Decl: main.ads 3:15
12657 Body: main.adb 2:15
12660 Body: main.adb 1:14
12663 Ref: main.adb 6:12 7:12
12667 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12668 its body is in main.adb, line 1, column 14 and is not referenced any where.
12670 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12671 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12673 @item gnatxref package1.adb package2.ads
12674 @code{gnatxref} will generates cross-reference information for
12675 package1.adb, package2.ads and any other package 'with'ed by any
12681 @subsection Using gnatxref with vi
12683 @code{gnatxref} can generate a tags file output, which can be used
12684 directly from @command{vi}. Note that the standard version of @command{vi}
12685 will not work properly with overloaded symbols. Consider using another
12686 free implementation of @command{vi}, such as @command{vim}.
12689 $ gnatxref -v gnatfind.adb > tags
12693 will generate the tags file for @code{gnatfind} itself (if the sources
12694 are in the search path!).
12696 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12697 (replacing @var{entity} by whatever you are looking for), and vi will
12698 display a new file with the corresponding declaration of entity.
12701 @node Examples of gnatfind Usage
12702 @section Examples of @code{gnatfind} Usage
12706 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12707 Find declarations for all entities xyz referenced at least once in
12708 main.adb. The references are search in every library file in the search
12711 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12714 The output will look like:
12716 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12717 ^directory/^[directory]^main.adb:24:10: xyz <= body
12718 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12722 that is to say, one of the entities xyz found in main.adb is declared at
12723 line 12 of main.ads (and its body is in main.adb), and another one is
12724 declared at line 45 of foo.ads
12726 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12727 This is the same command as the previous one, instead @code{gnatfind} will
12728 display the content of the Ada source file lines.
12730 The output will look like:
12733 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12735 ^directory/^[directory]^main.adb:24:10: xyz <= body
12737 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12742 This can make it easier to find exactly the location your are looking
12745 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12746 Find references to all entities containing an x that are
12747 referenced on line 123 of main.ads.
12748 The references will be searched only in main.ads and foo.adb.
12750 @item gnatfind main.ads:123
12751 Find declarations and bodies for all entities that are referenced on
12752 line 123 of main.ads.
12754 This is the same as @code{gnatfind "*":main.adb:123}.
12756 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12757 Find the declaration for the entity referenced at column 45 in
12758 line 123 of file main.adb in directory mydir. Note that it
12759 is usual to omit the identifier name when the column is given,
12760 since the column position identifies a unique reference.
12762 The column has to be the beginning of the identifier, and should not
12763 point to any character in the middle of the identifier.
12767 @c *********************************
12768 @node The GNAT Pretty-Printer gnatpp
12769 @chapter The GNAT Pretty-Printer @command{gnatpp}
12771 @cindex Pretty-Printer
12774 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12775 for source reformatting / pretty-printing.
12776 It takes an Ada source file as input and generates a reformatted
12778 You can specify various style directives via switches; e.g.,
12779 identifier case conventions, rules of indentation, and comment layout.
12781 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12782 tree for the input source and thus requires the input to be syntactically and
12783 semantically legal.
12784 If this condition is not met, @command{gnatpp} will terminate with an
12785 error message; no output file will be generated.
12787 If the source files presented to @command{gnatpp} contain
12788 preprocessing directives, then the output file will
12789 correspond to the generated source after all
12790 preprocessing is carried out. There is no way
12791 using @command{gnatpp} to obtain pretty printed files that
12792 include the preprocessing directives.
12794 If the compilation unit
12795 contained in the input source depends semantically upon units located
12796 outside the current directory, you have to provide the source search path
12797 when invoking @command{gnatpp}, if these units are contained in files with
12798 names that do not follow the GNAT file naming rules, you have to provide
12799 the configuration file describing the corresponding naming scheme;
12800 see the description of the @command{gnatpp}
12801 switches below. Another possibility is to use a project file and to
12802 call @command{gnatpp} through the @command{gnat} driver
12804 The @command{gnatpp} command has the form
12807 @c $ gnatpp @ovar{switches} @var{filename}
12808 @c Expanding @ovar macro inline (explanation in macro def comments)
12809 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12816 @var{switches} is an optional sequence of switches defining such properties as
12817 the formatting rules, the source search path, and the destination for the
12821 @var{filename} is the name (including the extension) of the source file to
12822 reformat; ``wildcards'' or several file names on the same gnatpp command are
12823 allowed. The file name may contain path information; it does not have to
12824 follow the GNAT file naming rules
12827 @samp{@var{gcc_switches}} is a list of switches for
12828 @command{gcc}. They will be passed on to all compiler invocations made by
12829 @command{gnatelim} to generate the ASIS trees. Here you can provide
12830 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12831 use the @option{-gnatec} switch to set the configuration file,
12832 use the @option{-gnat05} switch if sources should be compiled in
12837 * Switches for gnatpp::
12838 * Formatting Rules::
12841 @node Switches for gnatpp
12842 @section Switches for @command{gnatpp}
12845 The following subsections describe the various switches accepted by
12846 @command{gnatpp}, organized by category.
12849 You specify a switch by supplying a name and generally also a value.
12850 In many cases the values for a switch with a given name are incompatible with
12852 (for example the switch that controls the casing of a reserved word may have
12853 exactly one value: upper case, lower case, or
12854 mixed case) and thus exactly one such switch can be in effect for an
12855 invocation of @command{gnatpp}.
12856 If more than one is supplied, the last one is used.
12857 However, some values for the same switch are mutually compatible.
12858 You may supply several such switches to @command{gnatpp}, but then
12859 each must be specified in full, with both the name and the value.
12860 Abbreviated forms (the name appearing once, followed by each value) are
12862 For example, to set
12863 the alignment of the assignment delimiter both in declarations and in
12864 assignment statements, you must write @option{-A2A3}
12865 (or @option{-A2 -A3}), but not @option{-A23}.
12869 In many cases the set of options for a given qualifier are incompatible with
12870 each other (for example the qualifier that controls the casing of a reserved
12871 word may have exactly one option, which specifies either upper case, lower
12872 case, or mixed case), and thus exactly one such option can be in effect for
12873 an invocation of @command{gnatpp}.
12874 If more than one is supplied, the last one is used.
12875 However, some qualifiers have options that are mutually compatible,
12876 and then you may then supply several such options when invoking
12880 In most cases, it is obvious whether or not the
12881 ^values for a switch with a given name^options for a given qualifier^
12882 are compatible with each other.
12883 When the semantics might not be evident, the summaries below explicitly
12884 indicate the effect.
12887 * Alignment Control::
12889 * Construct Layout Control::
12890 * General Text Layout Control::
12891 * Other Formatting Options::
12892 * Setting the Source Search Path::
12893 * Output File Control::
12894 * Other gnatpp Switches::
12897 @node Alignment Control
12898 @subsection Alignment Control
12899 @cindex Alignment control in @command{gnatpp}
12902 Programs can be easier to read if certain constructs are vertically aligned.
12903 By default all alignments are set ON.
12904 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12905 OFF, and then use one or more of the other
12906 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12907 to activate alignment for specific constructs.
12910 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12914 Set all alignments to ON
12917 @item ^-A0^/ALIGN=OFF^
12918 Set all alignments to OFF
12920 @item ^-A1^/ALIGN=COLONS^
12921 Align @code{:} in declarations
12923 @item ^-A2^/ALIGN=DECLARATIONS^
12924 Align @code{:=} in initializations in declarations
12926 @item ^-A3^/ALIGN=STATEMENTS^
12927 Align @code{:=} in assignment statements
12929 @item ^-A4^/ALIGN=ARROWS^
12930 Align @code{=>} in associations
12932 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12933 Align @code{at} keywords in the component clauses in record
12934 representation clauses
12938 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12941 @node Casing Control
12942 @subsection Casing Control
12943 @cindex Casing control in @command{gnatpp}
12946 @command{gnatpp} allows you to specify the casing for reserved words,
12947 pragma names, attribute designators and identifiers.
12948 For identifiers you may define a
12949 general rule for name casing but also override this rule
12950 via a set of dictionary files.
12952 Three types of casing are supported: lower case, upper case, and mixed case.
12953 Lower and upper case are self-explanatory (but since some letters in
12954 Latin1 and other GNAT-supported character sets
12955 exist only in lower-case form, an upper case conversion will have no
12957 ``Mixed case'' means that the first letter, and also each letter immediately
12958 following an underscore, are converted to their uppercase forms;
12959 all the other letters are converted to their lowercase forms.
12962 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12963 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12964 Attribute designators are lower case
12966 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12967 Attribute designators are upper case
12969 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12970 Attribute designators are mixed case (this is the default)
12972 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12973 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12974 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12975 lower case (this is the default)
12977 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12978 Keywords are upper case
12980 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12981 @item ^-nD^/NAME_CASING=AS_DECLARED^
12982 Name casing for defining occurrences are as they appear in the source file
12983 (this is the default)
12985 @item ^-nU^/NAME_CASING=UPPER_CASE^
12986 Names are in upper case
12988 @item ^-nL^/NAME_CASING=LOWER_CASE^
12989 Names are in lower case
12991 @item ^-nM^/NAME_CASING=MIXED_CASE^
12992 Names are in mixed case
12994 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12995 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12996 Pragma names are lower case
12998 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12999 Pragma names are upper case
13001 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13002 Pragma names are mixed case (this is the default)
13004 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13005 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13006 Use @var{file} as a @emph{dictionary file} that defines
13007 the casing for a set of specified names,
13008 thereby overriding the effect on these names by
13009 any explicit or implicit
13010 ^-n^/NAME_CASING^ switch.
13011 To supply more than one dictionary file,
13012 use ^several @option{-D} switches^a list of files as options^.
13015 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13016 to define the casing for the Ada predefined names and
13017 the names declared in the GNAT libraries.
13019 @item ^-D-^/SPECIFIC_CASING^
13020 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13021 Do not use the default dictionary file;
13022 instead, use the casing
13023 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13028 The structure of a dictionary file, and details on the conventions
13029 used in the default dictionary file, are defined in @ref{Name Casing}.
13031 The @option{^-D-^/SPECIFIC_CASING^} and
13032 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13035 @node Construct Layout Control
13036 @subsection Construct Layout Control
13037 @cindex Layout control in @command{gnatpp}
13040 This group of @command{gnatpp} switches controls the layout of comments and
13041 complex syntactic constructs. See @ref{Formatting Comments} for details
13045 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13046 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13047 All the comments remain unchanged
13049 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13050 GNAT-style comment line indentation (this is the default).
13052 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13053 Reference-manual comment line indentation.
13055 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13056 GNAT-style comment beginning
13058 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13059 Reformat comment blocks
13061 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13062 Keep unchanged special form comments
13064 Reformat comment blocks
13066 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13067 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13068 GNAT-style layout (this is the default)
13070 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13073 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13076 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13078 All the VT characters are removed from the comment text. All the HT characters
13079 are expanded with the sequences of space characters to get to the next tab
13082 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13083 @item ^--no-separate-is^/NO_SEPARATE_IS^
13084 Do not place the keyword @code{is} on a separate line in a subprogram body in
13085 case if the spec occupies more then one line.
13087 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13088 @item ^--separate-label^/SEPARATE_LABEL^
13089 Place statement label(s) on a separate line, with the following statement
13092 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13093 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13094 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13095 keyword @code{then} in IF statements on a separate line.
13097 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13098 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13099 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13100 keyword @code{then} in IF statements on a separate line. This option is
13101 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13103 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13104 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13105 Start each USE clause in a context clause from a separate line.
13107 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13108 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13109 Use a separate line for a loop or block statement name, but do not use an extra
13110 indentation level for the statement itself.
13116 The @option{-c1} and @option{-c2} switches are incompatible.
13117 The @option{-c3} and @option{-c4} switches are compatible with each other and
13118 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13119 the other comment formatting switches.
13121 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13126 For the @option{/COMMENTS_LAYOUT} qualifier:
13129 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13131 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13132 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13136 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13137 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13140 @node General Text Layout Control
13141 @subsection General Text Layout Control
13144 These switches allow control over line length and indentation.
13147 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13148 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13149 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13151 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13152 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13153 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13155 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13156 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13157 Indentation level for continuation lines (relative to the line being
13158 continued), @var{nnn} from 1@dots{}9.
13160 value is one less then the (normal) indentation level, unless the
13161 indentation is set to 1 (in which case the default value for continuation
13162 line indentation is also 1)
13165 @node Other Formatting Options
13166 @subsection Other Formatting Options
13169 These switches control the inclusion of missing end/exit labels, and
13170 the indentation level in @b{case} statements.
13173 @item ^-e^/NO_MISSED_LABELS^
13174 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13175 Do not insert missing end/exit labels. An end label is the name of
13176 a construct that may optionally be repeated at the end of the
13177 construct's declaration;
13178 e.g., the names of packages, subprograms, and tasks.
13179 An exit label is the name of a loop that may appear as target
13180 of an exit statement within the loop.
13181 By default, @command{gnatpp} inserts these end/exit labels when
13182 they are absent from the original source. This option suppresses such
13183 insertion, so that the formatted source reflects the original.
13185 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13186 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13187 Insert a Form Feed character after a pragma Page.
13189 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13190 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13191 Do not use an additional indentation level for @b{case} alternatives
13192 and variants if there are @var{nnn} or more (the default
13194 If @var{nnn} is 0, an additional indentation level is
13195 used for @b{case} alternatives and variants regardless of their number.
13198 @node Setting the Source Search Path
13199 @subsection Setting the Source Search Path
13202 To define the search path for the input source file, @command{gnatpp}
13203 uses the same switches as the GNAT compiler, with the same effects.
13206 @item ^-I^/SEARCH=^@var{dir}
13207 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13208 The same as the corresponding gcc switch
13210 @item ^-I-^/NOCURRENT_DIRECTORY^
13211 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13212 The same as the corresponding gcc switch
13214 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13215 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13216 The same as the corresponding gcc switch
13218 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13219 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13220 The same as the corresponding gcc switch
13224 @node Output File Control
13225 @subsection Output File Control
13228 By default the output is sent to the file whose name is obtained by appending
13229 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13230 (if the file with this name already exists, it is unconditionally overwritten).
13231 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13232 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13234 The output may be redirected by the following switches:
13237 @item ^-pipe^/STANDARD_OUTPUT^
13238 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13239 Send the output to @code{Standard_Output}
13241 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13242 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13243 Write the output into @var{output_file}.
13244 If @var{output_file} already exists, @command{gnatpp} terminates without
13245 reading or processing the input file.
13247 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13248 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13249 Write the output into @var{output_file}, overwriting the existing file
13250 (if one is present).
13252 @item ^-r^/REPLACE^
13253 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13254 Replace the input source file with the reformatted output, and copy the
13255 original input source into the file whose name is obtained by appending the
13256 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13257 If a file with this name already exists, @command{gnatpp} terminates without
13258 reading or processing the input file.
13260 @item ^-rf^/OVERRIDING_REPLACE^
13261 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13262 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13263 already exists, it is overwritten.
13265 @item ^-rnb^/REPLACE_NO_BACKUP^
13266 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13267 Replace the input source file with the reformatted output without
13268 creating any backup copy of the input source.
13270 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13271 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13272 Specifies the format of the reformatted output file. The @var{xxx}
13273 ^string specified with the switch^option^ may be either
13275 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13276 @item ``@option{^crlf^CRLF^}''
13277 the same as @option{^crlf^CRLF^}
13278 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13279 @item ``@option{^lf^LF^}''
13280 the same as @option{^unix^UNIX^}
13283 @item ^-W^/RESULT_ENCODING=^@var{e}
13284 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13285 Specify the wide character encoding method used to write the code in the
13287 @var{e} is one of the following:
13295 Upper half encoding
13297 @item ^s^SHIFT_JIS^
13307 Brackets encoding (default value)
13313 Options @option{^-pipe^/STANDARD_OUTPUT^},
13314 @option{^-o^/OUTPUT^} and
13315 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13316 contains only one file to reformat.
13318 @option{^--eol^/END_OF_LINE^}
13320 @option{^-W^/RESULT_ENCODING^}
13321 cannot be used together
13322 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13324 @node Other gnatpp Switches
13325 @subsection Other @code{gnatpp} Switches
13328 The additional @command{gnatpp} switches are defined in this subsection.
13331 @item ^-files @var{filename}^/FILES=@var{filename}^
13332 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13333 Take the argument source files from the specified file. This file should be an
13334 ordinary text file containing file names separated by spaces or
13335 line breaks. You can use this switch more than once in the same call to
13336 @command{gnatpp}. You also can combine this switch with an explicit list of
13339 @item ^-v^/VERBOSE^
13340 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13342 @command{gnatpp} generates version information and then
13343 a trace of the actions it takes to produce or obtain the ASIS tree.
13345 @item ^-w^/WARNINGS^
13346 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13348 @command{gnatpp} generates a warning whenever it cannot provide
13349 a required layout in the result source.
13352 @node Formatting Rules
13353 @section Formatting Rules
13356 The following subsections show how @command{gnatpp} treats ``white space'',
13357 comments, program layout, and name casing.
13358 They provide the detailed descriptions of the switches shown above.
13361 * White Space and Empty Lines::
13362 * Formatting Comments::
13363 * Construct Layout::
13367 @node White Space and Empty Lines
13368 @subsection White Space and Empty Lines
13371 @command{gnatpp} does not have an option to control space characters.
13372 It will add or remove spaces according to the style illustrated by the
13373 examples in the @cite{Ada Reference Manual}.
13375 The only format effectors
13376 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13377 that will appear in the output file are platform-specific line breaks,
13378 and also format effectors within (but not at the end of) comments.
13379 In particular, each horizontal tab character that is not inside
13380 a comment will be treated as a space and thus will appear in the
13381 output file as zero or more spaces depending on
13382 the reformatting of the line in which it appears.
13383 The only exception is a Form Feed character, which is inserted after a
13384 pragma @code{Page} when @option{-ff} is set.
13386 The output file will contain no lines with trailing ``white space'' (spaces,
13389 Empty lines in the original source are preserved
13390 only if they separate declarations or statements.
13391 In such contexts, a
13392 sequence of two or more empty lines is replaced by exactly one empty line.
13393 Note that a blank line will be removed if it separates two ``comment blocks''
13394 (a comment block is a sequence of whole-line comments).
13395 In order to preserve a visual separation between comment blocks, use an
13396 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13397 Likewise, if for some reason you wish to have a sequence of empty lines,
13398 use a sequence of empty comments instead.
13400 @node Formatting Comments
13401 @subsection Formatting Comments
13404 Comments in Ada code are of two kinds:
13407 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13408 ``white space'') on a line
13411 an @emph{end-of-line comment}, which follows some other Ada lexical element
13416 The indentation of a whole-line comment is that of either
13417 the preceding or following line in
13418 the formatted source, depending on switch settings as will be described below.
13420 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13421 between the end of the preceding Ada lexical element and the beginning
13422 of the comment as appear in the original source,
13423 unless either the comment has to be split to
13424 satisfy the line length limitation, or else the next line contains a
13425 whole line comment that is considered a continuation of this end-of-line
13426 comment (because it starts at the same position).
13428 cases, the start of the end-of-line comment is moved right to the nearest
13429 multiple of the indentation level.
13430 This may result in a ``line overflow'' (the right-shifted comment extending
13431 beyond the maximum line length), in which case the comment is split as
13434 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13435 (GNAT-style comment line indentation)
13436 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13437 (reference-manual comment line indentation).
13438 With reference-manual style, a whole-line comment is indented as if it
13439 were a declaration or statement at the same place
13440 (i.e., according to the indentation of the preceding line(s)).
13441 With GNAT style, a whole-line comment that is immediately followed by an
13442 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13443 word @b{begin}, is indented based on the construct that follows it.
13446 @smallexample @c ada
13458 Reference-manual indentation produces:
13460 @smallexample @c ada
13472 while GNAT-style indentation produces:
13474 @smallexample @c ada
13486 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13487 (GNAT style comment beginning) has the following
13492 For each whole-line comment that does not end with two hyphens,
13493 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13494 to ensure that there are at least two spaces between these hyphens and the
13495 first non-blank character of the comment.
13499 For an end-of-line comment, if in the original source the next line is a
13500 whole-line comment that starts at the same position
13501 as the end-of-line comment,
13502 then the whole-line comment (and all whole-line comments
13503 that follow it and that start at the same position)
13504 will start at this position in the output file.
13507 That is, if in the original source we have:
13509 @smallexample @c ada
13512 A := B + C; -- B must be in the range Low1..High1
13513 -- C must be in the range Low2..High2
13514 --B+C will be in the range Low1+Low2..High1+High2
13520 Then in the formatted source we get
13522 @smallexample @c ada
13525 A := B + C; -- B must be in the range Low1..High1
13526 -- C must be in the range Low2..High2
13527 -- B+C will be in the range Low1+Low2..High1+High2
13533 A comment that exceeds the line length limit will be split.
13535 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13536 the line belongs to a reformattable block, splitting the line generates a
13537 @command{gnatpp} warning.
13538 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13539 comments may be reformatted in typical
13540 word processor style (that is, moving words between lines and putting as
13541 many words in a line as possible).
13544 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13545 that has a special format (that is, a character that is neither a letter nor digit
13546 not white space nor line break immediately following the leading @code{--} of
13547 the comment) should be without any change moved from the argument source
13548 into reformatted source. This switch allows to preserve comments that are used
13549 as a special marks in the code (e.g.@: SPARK annotation).
13551 @node Construct Layout
13552 @subsection Construct Layout
13555 In several cases the suggested layout in the Ada Reference Manual includes
13556 an extra level of indentation that many programmers prefer to avoid. The
13557 affected cases include:
13561 @item Record type declaration (RM 3.8)
13563 @item Record representation clause (RM 13.5.1)
13565 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13567 @item Block statement in case if a block has a statement identifier (RM 5.6)
13571 In compact mode (when GNAT style layout or compact layout is set),
13572 the pretty printer uses one level of indentation instead
13573 of two. This is achieved in the record definition and record representation
13574 clause cases by putting the @code{record} keyword on the same line as the
13575 start of the declaration or representation clause, and in the block and loop
13576 case by putting the block or loop header on the same line as the statement
13580 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13581 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13582 layout on the one hand, and uncompact layout
13583 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13584 can be illustrated by the following examples:
13588 @multitable @columnfractions .5 .5
13589 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13592 @smallexample @c ada
13599 @smallexample @c ada
13608 @smallexample @c ada
13610 a at 0 range 0 .. 31;
13611 b at 4 range 0 .. 31;
13615 @smallexample @c ada
13618 a at 0 range 0 .. 31;
13619 b at 4 range 0 .. 31;
13624 @smallexample @c ada
13632 @smallexample @c ada
13642 @smallexample @c ada
13643 Clear : for J in 1 .. 10 loop
13648 @smallexample @c ada
13650 for J in 1 .. 10 loop
13661 GNAT style, compact layout Uncompact layout
13663 type q is record type q is
13664 a : integer; record
13665 b : integer; a : integer;
13666 end record; b : integer;
13669 for q use record for q use
13670 a at 0 range 0 .. 31; record
13671 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
13672 end record; b at 4 range 0 .. 31;
13675 Block : declare Block :
13676 A : Integer := 3; declare
13677 begin A : Integer := 3;
13679 end Block; Proc (A, A);
13682 Clear : for J in 1 .. 10 loop Clear :
13683 A (J) := 0; for J in 1 .. 10 loop
13684 end loop Clear; A (J) := 0;
13691 A further difference between GNAT style layout and compact layout is that
13692 GNAT style layout inserts empty lines as separation for
13693 compound statements, return statements and bodies.
13695 Note that the layout specified by
13696 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13697 for named block and loop statements overrides the layout defined by these
13698 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13699 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13700 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13703 @subsection Name Casing
13706 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13707 the same casing as the corresponding defining identifier.
13709 You control the casing for defining occurrences via the
13710 @option{^-n^/NAME_CASING^} switch.
13712 With @option{-nD} (``as declared'', which is the default),
13715 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13717 defining occurrences appear exactly as in the source file
13718 where they are declared.
13719 The other ^values for this switch^options for this qualifier^ ---
13720 @option{^-nU^UPPER_CASE^},
13721 @option{^-nL^LOWER_CASE^},
13722 @option{^-nM^MIXED_CASE^} ---
13724 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13725 If @command{gnatpp} changes the casing of a defining
13726 occurrence, it analogously changes the casing of all the
13727 usage occurrences of this name.
13729 If the defining occurrence of a name is not in the source compilation unit
13730 currently being processed by @command{gnatpp}, the casing of each reference to
13731 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13732 switch (subject to the dictionary file mechanism described below).
13733 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13735 casing for the defining occurrence of the name.
13737 Some names may need to be spelled with casing conventions that are not
13738 covered by the upper-, lower-, and mixed-case transformations.
13739 You can arrange correct casing by placing such names in a
13740 @emph{dictionary file},
13741 and then supplying a @option{^-D^/DICTIONARY^} switch.
13742 The casing of names from dictionary files overrides
13743 any @option{^-n^/NAME_CASING^} switch.
13745 To handle the casing of Ada predefined names and the names from GNAT libraries,
13746 @command{gnatpp} assumes a default dictionary file.
13747 The name of each predefined entity is spelled with the same casing as is used
13748 for the entity in the @cite{Ada Reference Manual}.
13749 The name of each entity in the GNAT libraries is spelled with the same casing
13750 as is used in the declaration of that entity.
13752 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13753 default dictionary file.
13754 Instead, the casing for predefined and GNAT-defined names will be established
13755 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13756 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13757 will appear as just shown,
13758 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13759 To ensure that even such names are rendered in uppercase,
13760 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13761 (or else, less conveniently, place these names in upper case in a dictionary
13764 A dictionary file is
13765 a plain text file; each line in this file can be either a blank line
13766 (containing only space characters and ASCII.HT characters), an Ada comment
13767 line, or the specification of exactly one @emph{casing schema}.
13769 A casing schema is a string that has the following syntax:
13773 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13775 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13780 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13781 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13783 The casing schema string can be followed by white space and/or an Ada-style
13784 comment; any amount of white space is allowed before the string.
13786 If a dictionary file is passed as
13788 the value of a @option{-D@var{file}} switch
13791 an option to the @option{/DICTIONARY} qualifier
13794 simple name and every identifier, @command{gnatpp} checks if the dictionary
13795 defines the casing for the name or for some of its parts (the term ``subword''
13796 is used below to denote the part of a name which is delimited by ``_'' or by
13797 the beginning or end of the word and which does not contain any ``_'' inside):
13801 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13802 the casing defined by the dictionary; no subwords are checked for this word
13805 for every subword @command{gnatpp} checks if the dictionary contains the
13806 corresponding string of the form @code{*@var{simple_identifier}*},
13807 and if it does, the casing of this @var{simple_identifier} is used
13811 if the whole name does not contain any ``_'' inside, and if for this name
13812 the dictionary contains two entries - one of the form @var{identifier},
13813 and another - of the form *@var{simple_identifier}*, then the first one
13814 is applied to define the casing of this name
13817 if more than one dictionary file is passed as @command{gnatpp} switches, each
13818 dictionary adds new casing exceptions and overrides all the existing casing
13819 exceptions set by the previous dictionaries
13822 when @command{gnatpp} checks if the word or subword is in the dictionary,
13823 this check is not case sensitive
13827 For example, suppose we have the following source to reformat:
13829 @smallexample @c ada
13832 name1 : integer := 1;
13833 name4_name3_name2 : integer := 2;
13834 name2_name3_name4 : Boolean;
13837 name2_name3_name4 := name4_name3_name2 > name1;
13843 And suppose we have two dictionaries:
13860 If @command{gnatpp} is called with the following switches:
13864 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13867 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13872 then we will get the following name casing in the @command{gnatpp} output:
13874 @smallexample @c ada
13877 NAME1 : Integer := 1;
13878 Name4_NAME3_Name2 : Integer := 2;
13879 Name2_NAME3_Name4 : Boolean;
13882 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13887 @c *********************************
13888 @node The GNAT Metric Tool gnatmetric
13889 @chapter The GNAT Metric Tool @command{gnatmetric}
13891 @cindex Metric tool
13894 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13895 for computing various program metrics.
13896 It takes an Ada source file as input and generates a file containing the
13897 metrics data as output. Various switches control which
13898 metrics are computed and output.
13900 @command{gnatmetric} generates and uses the ASIS
13901 tree for the input source and thus requires the input to be syntactically and
13902 semantically legal.
13903 If this condition is not met, @command{gnatmetric} will generate
13904 an error message; no metric information for this file will be
13905 computed and reported.
13907 If the compilation unit contained in the input source depends semantically
13908 upon units in files located outside the current directory, you have to provide
13909 the source search path when invoking @command{gnatmetric}.
13910 If it depends semantically upon units that are contained
13911 in files with names that do not follow the GNAT file naming rules, you have to
13912 provide the configuration file describing the corresponding naming scheme (see
13913 the description of the @command{gnatmetric} switches below.)
13914 Alternatively, you may use a project file and invoke @command{gnatmetric}
13915 through the @command{gnat} driver.
13917 The @command{gnatmetric} command has the form
13920 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13921 @c Expanding @ovar macro inline (explanation in macro def comments)
13922 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13929 @var{switches} specify the metrics to compute and define the destination for
13933 Each @var{filename} is the name (including the extension) of a source
13934 file to process. ``Wildcards'' are allowed, and
13935 the file name may contain path information.
13936 If no @var{filename} is supplied, then the @var{switches} list must contain
13938 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13939 Including both a @option{-files} switch and one or more
13940 @var{filename} arguments is permitted.
13943 @samp{@var{gcc_switches}} is a list of switches for
13944 @command{gcc}. They will be passed on to all compiler invocations made by
13945 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13946 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13947 and use the @option{-gnatec} switch to set the configuration file,
13948 use the @option{-gnat05} switch if sources should be compiled in
13953 * Switches for gnatmetric::
13956 @node Switches for gnatmetric
13957 @section Switches for @command{gnatmetric}
13960 The following subsections describe the various switches accepted by
13961 @command{gnatmetric}, organized by category.
13964 * Output Files Control::
13965 * Disable Metrics For Local Units::
13966 * Specifying a set of metrics to compute::
13967 * Other gnatmetric Switches::
13968 * Generate project-wide metrics::
13971 @node Output Files Control
13972 @subsection Output File Control
13973 @cindex Output file control in @command{gnatmetric}
13976 @command{gnatmetric} has two output formats. It can generate a
13977 textual (human-readable) form, and also XML. By default only textual
13978 output is generated.
13980 When generating the output in textual form, @command{gnatmetric} creates
13981 for each Ada source file a corresponding text file
13982 containing the computed metrics, except for the case when the set of metrics
13983 specified by gnatmetric parameters consists only of metrics that are computed
13984 for the whole set of analyzed sources, but not for each Ada source.
13985 By default, this file is placed in the same directory as where the source
13986 file is located, and its name is obtained
13987 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13990 All the output information generated in XML format is placed in a single
13991 file. By default this file is placed in the current directory and has the
13992 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13994 Some of the computed metrics are summed over the units passed to
13995 @command{gnatmetric}; for example, the total number of lines of code.
13996 By default this information is sent to @file{stdout}, but a file
13997 can be specified with the @option{-og} switch.
13999 The following switches control the @command{gnatmetric} output:
14002 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14004 Generate the XML output
14006 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14008 Generate the XML output and the XML schema file that describes the structure
14009 of the XML metric report, this schema is assigned to the XML file. The schema
14010 file has the same name as the XML output file with @file{.xml} suffix replaced
14013 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14014 @item ^-nt^/NO_TEXT^
14015 Do not generate the output in text form (implies @option{^-x^/XML^})
14017 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14018 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14019 Put text files with detailed metrics into @var{output_dir}
14021 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14022 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14023 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14024 in the name of the output file.
14026 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14027 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14028 Put global metrics into @var{file_name}
14030 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14031 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14032 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14034 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14035 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14036 Use ``short'' source file names in the output. (The @command{gnatmetric}
14037 output includes the name(s) of the Ada source file(s) from which the metrics
14038 are computed. By default each name includes the absolute path. The
14039 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14040 to exclude all directory information from the file names that are output.)
14044 @node Disable Metrics For Local Units
14045 @subsection Disable Metrics For Local Units
14046 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14049 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14051 unit per one source file. It computes line metrics for the whole source
14052 file, and it also computes syntax
14053 and complexity metrics for the file's outermost unit.
14055 By default, @command{gnatmetric} will also compute all metrics for certain
14056 kinds of locally declared program units:
14060 subprogram (and generic subprogram) bodies;
14063 package (and generic package) specs and bodies;
14066 task object and type specifications and bodies;
14069 protected object and type specifications and bodies.
14073 These kinds of entities will be referred to as
14074 @emph{eligible local program units}, or simply @emph{eligible local units},
14075 @cindex Eligible local unit (for @command{gnatmetric})
14076 in the discussion below.
14078 Note that a subprogram declaration, generic instantiation,
14079 or renaming declaration only receives metrics
14080 computation when it appear as the outermost entity
14083 Suppression of metrics computation for eligible local units can be
14084 obtained via the following switch:
14087 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14088 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14089 Do not compute detailed metrics for eligible local program units
14093 @node Specifying a set of metrics to compute
14094 @subsection Specifying a set of metrics to compute
14097 By default all the metrics are computed and reported. The switches
14098 described in this subsection allow you to control, on an individual
14099 basis, whether metrics are computed and
14100 reported. If at least one positive metric
14101 switch is specified (that is, a switch that defines that a given
14102 metric or set of metrics is to be computed), then only
14103 explicitly specified metrics are reported.
14106 * Line Metrics Control::
14107 * Syntax Metrics Control::
14108 * Complexity Metrics Control::
14109 * Coupling Metrics Control::
14112 @node Line Metrics Control
14113 @subsubsection Line Metrics Control
14114 @cindex Line metrics control in @command{gnatmetric}
14117 For any (legal) source file, and for each of its
14118 eligible local program units, @command{gnatmetric} computes the following
14123 the total number of lines;
14126 the total number of code lines (i.e., non-blank lines that are not comments)
14129 the number of comment lines
14132 the number of code lines containing end-of-line comments;
14135 the comment percentage: the ratio between the number of lines that contain
14136 comments and the number of all non-blank lines, expressed as a percentage;
14139 the number of empty lines and lines containing only space characters and/or
14140 format effectors (blank lines)
14143 the average number of code lines in subprogram bodies, task bodies, entry
14144 bodies and statement sequences in package bodies (this metric is only computed
14145 across the whole set of the analyzed units)
14150 @command{gnatmetric} sums the values of the line metrics for all the
14151 files being processed and then generates the cumulative results. The tool
14152 also computes for all the files being processed the average number of code
14155 You can use the following switches to select the specific line metrics
14156 to be computed and reported.
14159 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14162 @cindex @option{--no-lines@var{x}}
14165 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14166 Report all the line metrics
14168 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14169 Do not report any of line metrics
14171 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14172 Report the number of all lines
14174 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14175 Do not report the number of all lines
14177 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14178 Report the number of code lines
14180 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14181 Do not report the number of code lines
14183 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14184 Report the number of comment lines
14186 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14187 Do not report the number of comment lines
14189 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14190 Report the number of code lines containing
14191 end-of-line comments
14193 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14194 Do not report the number of code lines containing
14195 end-of-line comments
14197 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14198 Report the comment percentage in the program text
14200 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14201 Do not report the comment percentage in the program text
14203 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14204 Report the number of blank lines
14206 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14207 Do not report the number of blank lines
14209 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14210 Report the average number of code lines in subprogram bodies, task bodies,
14211 entry bodies and statement sequences in package bodies. The metric is computed
14212 and reported for the whole set of processed Ada sources only.
14214 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14215 Do not report the average number of code lines in subprogram bodies,
14216 task bodies, entry bodies and statement sequences in package bodies.
14220 @node Syntax Metrics Control
14221 @subsubsection Syntax Metrics Control
14222 @cindex Syntax metrics control in @command{gnatmetric}
14225 @command{gnatmetric} computes various syntactic metrics for the
14226 outermost unit and for each eligible local unit:
14229 @item LSLOC (``Logical Source Lines Of Code'')
14230 The total number of declarations and the total number of statements
14232 @item Maximal static nesting level of inner program units
14234 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14235 package, a task unit, a protected unit, a
14236 protected entry, a generic unit, or an explicitly declared subprogram other
14237 than an enumeration literal.''
14239 @item Maximal nesting level of composite syntactic constructs
14240 This corresponds to the notion of the
14241 maximum nesting level in the GNAT built-in style checks
14242 (@pxref{Style Checking})
14246 For the outermost unit in the file, @command{gnatmetric} additionally computes
14247 the following metrics:
14250 @item Public subprograms
14251 This metric is computed for package specs. It is the
14252 number of subprograms and generic subprograms declared in the visible
14253 part (including the visible part of nested packages, protected objects, and
14256 @item All subprograms
14257 This metric is computed for bodies and subunits. The
14258 metric is equal to a total number of subprogram bodies in the compilation
14260 Neither generic instantiations nor renamings-as-a-body nor body stubs
14261 are counted. Any subprogram body is counted, independently of its nesting
14262 level and enclosing constructs. Generic bodies and bodies of protected
14263 subprograms are counted in the same way as ``usual'' subprogram bodies.
14266 This metric is computed for package specs and
14267 generic package declarations. It is the total number of types
14268 that can be referenced from outside this compilation unit, plus the
14269 number of types from all the visible parts of all the visible generic
14270 packages. Generic formal types are not counted. Only types, not subtypes,
14274 Along with the total number of public types, the following
14275 types are counted and reported separately:
14282 Root tagged types (abstract, non-abstract, private, non-private). Type
14283 extensions are @emph{not} counted
14286 Private types (including private extensions)
14297 This metric is computed for any compilation unit. It is equal to the total
14298 number of the declarations of different types given in the compilation unit.
14299 The private and the corresponding full type declaration are counted as one
14300 type declaration. Incomplete type declarations and generic formal types
14302 No distinction is made among different kinds of types (abstract,
14303 private etc.); the total number of types is computed and reported.
14308 By default, all the syntax metrics are computed and reported. You can use the
14309 following switches to select specific syntax metrics.
14313 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14316 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14319 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14320 Report all the syntax metrics
14322 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14323 Do not report any of syntax metrics
14325 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14326 Report the total number of declarations
14328 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14329 Do not report the total number of declarations
14331 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14332 Report the total number of statements
14334 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14335 Do not report the total number of statements
14337 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14338 Report the number of public subprograms in a compilation unit
14340 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14341 Do not report the number of public subprograms in a compilation unit
14343 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14344 Report the number of all the subprograms in a compilation unit
14346 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14347 Do not report the number of all the subprograms in a compilation unit
14349 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14350 Report the number of public types in a compilation unit
14352 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14353 Do not report the number of public types in a compilation unit
14355 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14356 Report the number of all the types in a compilation unit
14358 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14359 Do not report the number of all the types in a compilation unit
14361 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14362 Report the maximal program unit nesting level
14364 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14365 Do not report the maximal program unit nesting level
14367 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14368 Report the maximal construct nesting level
14370 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14371 Do not report the maximal construct nesting level
14375 @node Complexity Metrics Control
14376 @subsubsection Complexity Metrics Control
14377 @cindex Complexity metrics control in @command{gnatmetric}
14380 For a program unit that is an executable body (a subprogram body (including
14381 generic bodies), task body, entry body or a package body containing
14382 its own statement sequence) @command{gnatmetric} computes the following
14383 complexity metrics:
14387 McCabe cyclomatic complexity;
14390 McCabe essential complexity;
14393 maximal loop nesting level;
14396 extra exit points (for subprograms);
14400 The McCabe cyclomatic complexity metric is defined
14401 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14403 According to McCabe, both control statements and short-circuit control forms
14404 should be taken into account when computing cyclomatic complexity. For each
14405 body, we compute three metric values:
14409 the complexity introduced by control
14410 statements only, without taking into account short-circuit forms,
14413 the complexity introduced by short-circuit control forms only, and
14417 cyclomatic complexity, which is the sum of these two values.
14422 The origin of cyclomatic complexity metric is the need to estimate the number
14423 of independent paths in the control flow graph that in turn gives the number
14424 of tests needed to satisfy paths coverage testing completeness criterion.
14425 Considered from the testing point of view, a static Ada @code{loop} (that is,
14426 the @code{loop} statement having static subtype in loop parameter
14427 specification) does not add to cyclomatic complexity. By providing
14428 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14429 may specify that such loops should not be counted when computing the
14430 cyclomatic complexity metric
14432 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14433 counted for the code that is reduced by excluding all the pure structural Ada
14434 control statements. An compound statement is considered as a non-structural
14435 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14436 or if it contains a @code{goto} statement that transfers the control outside
14437 the operator. A selective accept statement with @code{terminate} alternative
14438 is considered as non-structural statement. When computing this metric,
14439 @code{exit} statements are treated in the same way as @code{goto}
14440 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14442 The Ada essential complexity metric defined here is intended to quantify
14443 the extent to which the software is unstructured. It is adapted from
14444 the McCabe essential complexity metric defined in
14445 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14446 suitable for typical Ada usage. For example, short circuit forms
14447 are not penalized as unstructured in the Ada essential complexity metric.
14449 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14450 the code in the exception handlers and in all the nested program units.
14452 By default, all the complexity metrics are computed and reported.
14453 For more fine-grained control you can use
14454 the following switches:
14457 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14460 @cindex @option{--no-complexity@var{x}}
14463 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14464 Report all the complexity metrics
14466 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14467 Do not report any of complexity metrics
14469 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14470 Report the McCabe Cyclomatic Complexity
14472 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14473 Do not report the McCabe Cyclomatic Complexity
14475 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14476 Report the Essential Complexity
14478 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14479 Do not report the Essential Complexity
14481 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14482 Report maximal loop nesting level
14484 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14485 Do not report maximal loop nesting level
14487 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14488 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14489 task bodies, entry bodies and statement sequences in package bodies.
14490 The metric is computed and reported for whole set of processed Ada sources
14493 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14494 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14495 bodies, task bodies, entry bodies and statement sequences in package bodies
14497 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14498 @item ^-ne^/NO_EXITS_AS_GOTOS^
14499 Do not consider @code{exit} statements as @code{goto}s when
14500 computing Essential Complexity
14502 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14503 @item ^--no-static-loop^/NO_STATIC_LOOP^
14504 Do not consider static loops when computing cyclomatic complexity
14506 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14507 Report the extra exit points for subprogram bodies. As an exit point, this
14508 metric counts @code{return} statements and raise statements in case when the
14509 raised exception is not handled in the same body. In case of a function this
14510 metric subtracts 1 from the number of exit points, because a function body
14511 must contain at least one @code{return} statement.
14513 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14514 Do not report the extra exit points for subprogram bodies
14518 @node Coupling Metrics Control
14519 @subsubsection Coupling Metrics Control
14520 @cindex Coupling metrics control in @command{gnatmetric}
14523 @cindex Coupling metrics (in in @command{gnatmetric})
14524 Coupling metrics measure the dependencies between a given entity and other
14525 entities the program consists of. The goal of these metrics is to estimate the
14526 stability of the whole program considered as the collection of entities
14527 (modules, classes etc.).
14529 Gnatmetric computes the following coupling metrics:
14534 @emph{object-oriented coupling} - for classes in traditional object-oriented
14538 emph{unit coupling} - for all the program units making up a program;
14541 emph{control coupling} - this metric counts dependencies between a unit and
14542 only those units that define subprograms;
14546 Two kinds of coupling metrics are computed:
14549 @item fan-out coupling (efferent coupling)
14550 @cindex fan-out coupling
14551 @cindex efferent coupling
14552 the number of entities the given entity depends upon. It
14553 estimates in what extent the given entity depends on the changes in
14556 @item fan-in coupling (afferent coupling)
14557 @cindex fan-in coupling
14558 @cindex afferent coupling
14559 the number of entities that depend on a given entity.
14560 It estimates in what extent the ``external world'' depends on the changes in a
14566 Object-oriented coupling metrics are metrics that measure the dependencies
14567 between a given class (or a group of classes) and the other classes in the
14568 program. In this subsection the term ``class'' is used in its traditional
14569 object-oriented programming sense (an instantiable module that contains data
14570 and/or method members). A @emph{category} (of classes) is a group of closely
14571 related classes that are reused and/or modified together.
14573 A class @code{K}'s fan-out coupling is the number of classes
14574 that @code{K} depends upon.
14575 A category's fan-out coupling is the number of classes outside the
14576 category that the classes inside the category depend upon.
14578 A class @code{K}'s fan-in coupling is the number of classes
14579 that depend upon @code{K}.
14580 A category's fan-in coupling is the number of classes outside the
14581 category that depend on classes belonging to the category.
14583 Ada's implementation of the object-oriented paradigm does not use the
14584 traditional class notion, so the definition of the coupling
14585 metrics for Ada maps the class and class category notions
14586 onto Ada constructs.
14588 For the coupling metrics, several kinds of modules -- a library package,
14589 a library generic package, and a library generic package instantiation --
14590 that define a tagged type or an interface type are
14591 considered to be a class. A category consists of a library package (or
14592 a library generic package) that defines a tagged or an interface type,
14593 together with all its descendant (generic) packages that define tagged
14594 or interface types. That is a
14595 category is an Ada hierarchy of library-level program units. So class coupling
14596 in case of Ada is called as tagged coupling, and category coupling - as
14597 hierarchy coupling.
14599 For any package counted as a class, its body and subunits (if any) are
14600 considered together with its spec when counting the dependencies, and coupling
14601 metrics are reported for spec units only. For dependencies between classes,
14602 the Ada semantic dependencies are considered. For object-oriented coupling
14603 metrics, only dependencies on units that are considered as classes, are
14606 For unit and control coupling also not compilation units but program units are
14607 counted. That is, for a package, its spec, its body and its subunits (if any)
14608 are considered as making up one unit, and the dependencies that are counted
14609 are the dependencies of all these compilation units collected together as
14610 the dependencies as a (whole) unit. And metrics are reported for spec
14611 compilation units only (or for a subprogram body unit in case if there is no
14612 separate spec for the given subprogram).
14614 For unit coupling, dependencies between all kinds of program units are
14615 considered. For control coupling, for each unit the dependencies of this unit
14616 upon units that define subprograms are counted, so control fan-out coupling
14617 is reported for all units, but control fan-in coupling - only for the units
14618 that define subprograms.
14625 When computing coupling metrics, @command{gnatmetric} counts only
14626 dependencies between units that are arguments of the gnatmetric call.
14627 Coupling metrics are program-wide (or project-wide) metrics, so to
14628 get a valid result, you should call @command{gnatmetric} for
14629 the whole set of sources that make up your program. It can be done
14630 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14631 option (see @ref{The GNAT Driver and Project Files} for details).
14633 By default, all the coupling metrics are disabled. You can use the following
14634 switches to specify the coupling metrics to be computed and reported:
14639 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14640 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14641 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14642 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14646 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14649 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14650 Report all the coupling metrics
14652 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14653 Report tagged (class) fan-out coupling
14655 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14656 Report tagged (class) fan-in coupling
14658 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14659 Report hierarchy (category) fan-out coupling
14661 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14662 Report hierarchy (category) fan-in coupling
14664 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14665 Report unit fan-out coupling
14667 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14668 Report unit fan-in coupling
14670 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14671 Report control fan-out coupling
14673 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14674 Report control fan-in coupling
14677 @node Other gnatmetric Switches
14678 @subsection Other @code{gnatmetric} Switches
14681 Additional @command{gnatmetric} switches are as follows:
14684 @item ^-files @var{filename}^/FILES=@var{filename}^
14685 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14686 Take the argument source files from the specified file. This file should be an
14687 ordinary text file containing file names separated by spaces or
14688 line breaks. You can use this switch more than once in the same call to
14689 @command{gnatmetric}. You also can combine this switch with
14690 an explicit list of files.
14692 @item ^-v^/VERBOSE^
14693 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14695 @command{gnatmetric} generates version information and then
14696 a trace of sources being processed.
14699 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14703 @node Generate project-wide metrics
14704 @subsection Generate project-wide metrics
14706 In order to compute metrics on all units of a given project, you can use
14707 the @command{gnat} driver along with the @option{-P} option:
14713 If the project @code{proj} depends upon other projects, you can compute
14714 the metrics on the project closure using the @option{-U} option:
14716 gnat metric -Pproj -U
14720 Finally, if not all the units are relevant to a particular main
14721 program in the project closure, you can generate metrics for the set
14722 of units needed to create a given main program (unit closure) using
14723 the @option{-U} option followed by the name of the main unit:
14725 gnat metric -Pproj -U main
14729 @c ***********************************
14730 @node File Name Krunching Using gnatkr
14731 @chapter File Name Krunching Using @code{gnatkr}
14735 This chapter discusses the method used by the compiler to shorten
14736 the default file names chosen for Ada units so that they do not
14737 exceed the maximum length permitted. It also describes the
14738 @code{gnatkr} utility that can be used to determine the result of
14739 applying this shortening.
14743 * Krunching Method::
14744 * Examples of gnatkr Usage::
14748 @section About @code{gnatkr}
14751 The default file naming rule in GNAT
14752 is that the file name must be derived from
14753 the unit name. The exact default rule is as follows:
14756 Take the unit name and replace all dots by hyphens.
14758 If such a replacement occurs in the
14759 second character position of a name, and the first character is
14760 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14761 then replace the dot by the character
14762 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14763 instead of a minus.
14765 The reason for this exception is to avoid clashes
14766 with the standard names for children of System, Ada, Interfaces,
14767 and GNAT, which use the prefixes
14768 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14771 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14772 switch of the compiler activates a ``krunching''
14773 circuit that limits file names to nn characters (where nn is a decimal
14774 integer). For example, using OpenVMS,
14775 where the maximum file name length is
14776 39, the value of nn is usually set to 39, but if you want to generate
14777 a set of files that would be usable if ported to a system with some
14778 different maximum file length, then a different value can be specified.
14779 The default value of 39 for OpenVMS need not be specified.
14781 The @code{gnatkr} utility can be used to determine the krunched name for
14782 a given file, when krunched to a specified maximum length.
14785 @section Using @code{gnatkr}
14788 The @code{gnatkr} command has the form
14792 @c $ gnatkr @var{name} @ovar{length}
14793 @c Expanding @ovar macro inline (explanation in macro def comments)
14794 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14800 $ gnatkr @var{name} /COUNT=nn
14805 @var{name} is the uncrunched file name, derived from the name of the unit
14806 in the standard manner described in the previous section (i.e., in particular
14807 all dots are replaced by hyphens). The file name may or may not have an
14808 extension (defined as a suffix of the form period followed by arbitrary
14809 characters other than period). If an extension is present then it will
14810 be preserved in the output. For example, when krunching @file{hellofile.ads}
14811 to eight characters, the result will be hellofil.ads.
14813 Note: for compatibility with previous versions of @code{gnatkr} dots may
14814 appear in the name instead of hyphens, but the last dot will always be
14815 taken as the start of an extension. So if @code{gnatkr} is given an argument
14816 such as @file{Hello.World.adb} it will be treated exactly as if the first
14817 period had been a hyphen, and for example krunching to eight characters
14818 gives the result @file{hellworl.adb}.
14820 Note that the result is always all lower case (except on OpenVMS where it is
14821 all upper case). Characters of the other case are folded as required.
14823 @var{length} represents the length of the krunched name. The default
14824 when no argument is given is ^8^39^ characters. A length of zero stands for
14825 unlimited, in other words do not chop except for system files where the
14826 implied crunching length is always eight characters.
14829 The output is the krunched name. The output has an extension only if the
14830 original argument was a file name with an extension.
14832 @node Krunching Method
14833 @section Krunching Method
14836 The initial file name is determined by the name of the unit that the file
14837 contains. The name is formed by taking the full expanded name of the
14838 unit and replacing the separating dots with hyphens and
14839 using ^lowercase^uppercase^
14840 for all letters, except that a hyphen in the second character position is
14841 replaced by a ^tilde^dollar sign^ if the first character is
14842 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14843 The extension is @code{.ads} for a
14844 spec and @code{.adb} for a body.
14845 Krunching does not affect the extension, but the file name is shortened to
14846 the specified length by following these rules:
14850 The name is divided into segments separated by hyphens, tildes or
14851 underscores and all hyphens, tildes, and underscores are
14852 eliminated. If this leaves the name short enough, we are done.
14855 If the name is too long, the longest segment is located (left-most
14856 if there are two of equal length), and shortened by dropping
14857 its last character. This is repeated until the name is short enough.
14859 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14860 to fit the name into 8 characters as required by some operating systems.
14863 our-strings-wide_fixed 22
14864 our strings wide fixed 19
14865 our string wide fixed 18
14866 our strin wide fixed 17
14867 our stri wide fixed 16
14868 our stri wide fixe 15
14869 our str wide fixe 14
14870 our str wid fixe 13
14876 Final file name: oustwifi.adb
14880 The file names for all predefined units are always krunched to eight
14881 characters. The krunching of these predefined units uses the following
14882 special prefix replacements:
14886 replaced by @file{^a^A^-}
14889 replaced by @file{^g^G^-}
14892 replaced by @file{^i^I^-}
14895 replaced by @file{^s^S^-}
14898 These system files have a hyphen in the second character position. That
14899 is why normal user files replace such a character with a
14900 ^tilde^dollar sign^, to
14901 avoid confusion with system file names.
14903 As an example of this special rule, consider
14904 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14907 ada-strings-wide_fixed 22
14908 a- strings wide fixed 18
14909 a- string wide fixed 17
14910 a- strin wide fixed 16
14911 a- stri wide fixed 15
14912 a- stri wide fixe 14
14913 a- str wide fixe 13
14919 Final file name: a-stwifi.adb
14923 Of course no file shortening algorithm can guarantee uniqueness over all
14924 possible unit names, and if file name krunching is used then it is your
14925 responsibility to ensure that no name clashes occur. The utility
14926 program @code{gnatkr} is supplied for conveniently determining the
14927 krunched name of a file.
14929 @node Examples of gnatkr Usage
14930 @section Examples of @code{gnatkr} Usage
14937 $ gnatkr very_long_unit_name.ads --> velounna.ads
14938 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14939 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14940 $ gnatkr grandparent-parent-child --> grparchi
14942 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14943 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14946 @node Preprocessing Using gnatprep
14947 @chapter Preprocessing Using @code{gnatprep}
14951 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14953 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14954 special GNAT features.
14955 For further discussion of conditional compilation in general, see
14956 @ref{Conditional Compilation}.
14959 * Preprocessing Symbols::
14961 * Switches for gnatprep::
14962 * Form of Definitions File::
14963 * Form of Input Text for gnatprep::
14966 @node Preprocessing Symbols
14967 @section Preprocessing Symbols
14970 Preprocessing symbols are defined in definition files and referred to in
14971 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14972 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14973 all characters need to be in the ASCII set (no accented letters).
14975 @node Using gnatprep
14976 @section Using @code{gnatprep}
14979 To call @code{gnatprep} use
14982 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14983 @c Expanding @ovar macro inline (explanation in macro def comments)
14984 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14991 is an optional sequence of switches as described in the next section.
14994 is the full name of the input file, which is an Ada source
14995 file containing preprocessor directives.
14998 is the full name of the output file, which is an Ada source
14999 in standard Ada form. When used with GNAT, this file name will
15000 normally have an ads or adb suffix.
15003 is the full name of a text file containing definitions of
15004 preprocessing symbols to be referenced by the preprocessor. This argument is
15005 optional, and can be replaced by the use of the @option{-D} switch.
15009 @node Switches for gnatprep
15010 @section Switches for @code{gnatprep}
15015 @item ^-b^/BLANK_LINES^
15016 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15017 Causes both preprocessor lines and the lines deleted by
15018 preprocessing to be replaced by blank lines in the output source file,
15019 preserving line numbers in the output file.
15021 @item ^-c^/COMMENTS^
15022 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15023 Causes both preprocessor lines and the lines deleted
15024 by preprocessing to be retained in the output source as comments marked
15025 with the special string @code{"--! "}. This option will result in line numbers
15026 being preserved in the output file.
15028 @item ^-C^/REPLACE_IN_COMMENTS^
15029 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15030 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15031 If this option is specified, then comments are scanned and any $symbol
15032 substitutions performed as in program text. This is particularly useful
15033 when structured comments are used (e.g., when writing programs in the
15034 SPARK dialect of Ada). Note that this switch is not available when
15035 doing integrated preprocessing (it would be useless in this context
15036 since comments are ignored by the compiler in any case).
15038 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15039 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15040 Defines a new preprocessing symbol, associated with value. If no value is given
15041 on the command line, then symbol is considered to be @code{True}. This switch
15042 can be used in place of a definition file.
15046 @cindex @option{/REMOVE} (@command{gnatprep})
15047 This is the default setting which causes lines deleted by preprocessing
15048 to be entirely removed from the output file.
15051 @item ^-r^/REFERENCE^
15052 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15053 Causes a @code{Source_Reference} pragma to be generated that
15054 references the original input file, so that error messages will use
15055 the file name of this original file. The use of this switch implies
15056 that preprocessor lines are not to be removed from the file, so its
15057 use will force @option{^-b^/BLANK_LINES^} mode if
15058 @option{^-c^/COMMENTS^}
15059 has not been specified explicitly.
15061 Note that if the file to be preprocessed contains multiple units, then
15062 it will be necessary to @code{gnatchop} the output file from
15063 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15064 in the preprocessed file, it will be respected by
15065 @code{gnatchop ^-r^/REFERENCE^}
15066 so that the final chopped files will correctly refer to the original
15067 input source file for @code{gnatprep}.
15069 @item ^-s^/SYMBOLS^
15070 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15071 Causes a sorted list of symbol names and values to be
15072 listed on the standard output file.
15074 @item ^-u^/UNDEFINED^
15075 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15076 Causes undefined symbols to be treated as having the value FALSE in the context
15077 of a preprocessor test. In the absence of this option, an undefined symbol in
15078 a @code{#if} or @code{#elsif} test will be treated as an error.
15084 Note: if neither @option{-b} nor @option{-c} is present,
15085 then preprocessor lines and
15086 deleted lines are completely removed from the output, unless -r is
15087 specified, in which case -b is assumed.
15090 @node Form of Definitions File
15091 @section Form of Definitions File
15094 The definitions file contains lines of the form
15101 where symbol is a preprocessing symbol, and value is one of the following:
15105 Empty, corresponding to a null substitution
15107 A string literal using normal Ada syntax
15109 Any sequence of characters from the set
15110 (letters, digits, period, underline).
15114 Comment lines may also appear in the definitions file, starting with
15115 the usual @code{--},
15116 and comments may be added to the definitions lines.
15118 @node Form of Input Text for gnatprep
15119 @section Form of Input Text for @code{gnatprep}
15122 The input text may contain preprocessor conditional inclusion lines,
15123 as well as general symbol substitution sequences.
15125 The preprocessor conditional inclusion commands have the form
15130 #if @i{expression} @r{[}then@r{]}
15132 #elsif @i{expression} @r{[}then@r{]}
15134 #elsif @i{expression} @r{[}then@r{]}
15145 In this example, @i{expression} is defined by the following grammar:
15147 @i{expression} ::= <symbol>
15148 @i{expression} ::= <symbol> = "<value>"
15149 @i{expression} ::= <symbol> = <symbol>
15150 @i{expression} ::= <symbol> 'Defined
15151 @i{expression} ::= not @i{expression}
15152 @i{expression} ::= @i{expression} and @i{expression}
15153 @i{expression} ::= @i{expression} or @i{expression}
15154 @i{expression} ::= @i{expression} and then @i{expression}
15155 @i{expression} ::= @i{expression} or else @i{expression}
15156 @i{expression} ::= ( @i{expression} )
15159 The following restriction exists: it is not allowed to have "and" or "or"
15160 following "not" in the same expression without parentheses. For example, this
15167 This should be one of the following:
15175 For the first test (@i{expression} ::= <symbol>) the symbol must have
15176 either the value true or false, that is to say the right-hand of the
15177 symbol definition must be one of the (case-insensitive) literals
15178 @code{True} or @code{False}. If the value is true, then the
15179 corresponding lines are included, and if the value is false, they are
15182 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15183 the symbol has been defined in the definition file or by a @option{-D}
15184 switch on the command line. Otherwise, the test is false.
15186 The equality tests are case insensitive, as are all the preprocessor lines.
15188 If the symbol referenced is not defined in the symbol definitions file,
15189 then the effect depends on whether or not switch @option{-u}
15190 is specified. If so, then the symbol is treated as if it had the value
15191 false and the test fails. If this switch is not specified, then
15192 it is an error to reference an undefined symbol. It is also an error to
15193 reference a symbol that is defined with a value other than @code{True}
15196 The use of the @code{not} operator inverts the sense of this logical test.
15197 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15198 operators, without parentheses. For example, "if not X or Y then" is not
15199 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15201 The @code{then} keyword is optional as shown
15203 The @code{#} must be the first non-blank character on a line, but
15204 otherwise the format is free form. Spaces or tabs may appear between
15205 the @code{#} and the keyword. The keywords and the symbols are case
15206 insensitive as in normal Ada code. Comments may be used on a
15207 preprocessor line, but other than that, no other tokens may appear on a
15208 preprocessor line. Any number of @code{elsif} clauses can be present,
15209 including none at all. The @code{else} is optional, as in Ada.
15211 The @code{#} marking the start of a preprocessor line must be the first
15212 non-blank character on the line, i.e., it must be preceded only by
15213 spaces or horizontal tabs.
15215 Symbol substitution outside of preprocessor lines is obtained by using
15223 anywhere within a source line, except in a comment or within a
15224 string literal. The identifier
15225 following the @code{$} must match one of the symbols defined in the symbol
15226 definition file, and the result is to substitute the value of the
15227 symbol in place of @code{$symbol} in the output file.
15229 Note that although the substitution of strings within a string literal
15230 is not possible, it is possible to have a symbol whose defined value is
15231 a string literal. So instead of setting XYZ to @code{hello} and writing:
15234 Header : String := "$XYZ";
15238 you should set XYZ to @code{"hello"} and write:
15241 Header : String := $XYZ;
15245 and then the substitution will occur as desired.
15247 @node The GNAT Library Browser gnatls
15248 @chapter The GNAT Library Browser @code{gnatls}
15250 @cindex Library browser
15253 @code{gnatls} is a tool that outputs information about compiled
15254 units. It gives the relationship between objects, unit names and source
15255 files. It can also be used to check the source dependencies of a unit
15256 as well as various characteristics.
15258 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15259 driver (see @ref{The GNAT Driver and Project Files}).
15263 * Switches for gnatls::
15264 * Examples of gnatls Usage::
15267 @node Running gnatls
15268 @section Running @code{gnatls}
15271 The @code{gnatls} command has the form
15274 $ gnatls switches @var{object_or_ali_file}
15278 The main argument is the list of object or @file{ali} files
15279 (@pxref{The Ada Library Information Files})
15280 for which information is requested.
15282 In normal mode, without additional option, @code{gnatls} produces a
15283 four-column listing. Each line represents information for a specific
15284 object. The first column gives the full path of the object, the second
15285 column gives the name of the principal unit in this object, the third
15286 column gives the status of the source and the fourth column gives the
15287 full path of the source representing this unit.
15288 Here is a simple example of use:
15292 ^./^[]^demo1.o demo1 DIF demo1.adb
15293 ^./^[]^demo2.o demo2 OK demo2.adb
15294 ^./^[]^hello.o h1 OK hello.adb
15295 ^./^[]^instr-child.o instr.child MOK instr-child.adb
15296 ^./^[]^instr.o instr OK instr.adb
15297 ^./^[]^tef.o tef DIF tef.adb
15298 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
15299 ^./^[]^tgef.o tgef DIF tgef.adb
15303 The first line can be interpreted as follows: the main unit which is
15305 object file @file{demo1.o} is demo1, whose main source is in
15306 @file{demo1.adb}. Furthermore, the version of the source used for the
15307 compilation of demo1 has been modified (DIF). Each source file has a status
15308 qualifier which can be:
15311 @item OK (unchanged)
15312 The version of the source file used for the compilation of the
15313 specified unit corresponds exactly to the actual source file.
15315 @item MOK (slightly modified)
15316 The version of the source file used for the compilation of the
15317 specified unit differs from the actual source file but not enough to
15318 require recompilation. If you use gnatmake with the qualifier
15319 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15320 MOK will not be recompiled.
15322 @item DIF (modified)
15323 No version of the source found on the path corresponds to the source
15324 used to build this object.
15326 @item ??? (file not found)
15327 No source file was found for this unit.
15329 @item HID (hidden, unchanged version not first on PATH)
15330 The version of the source that corresponds exactly to the source used
15331 for compilation has been found on the path but it is hidden by another
15332 version of the same source that has been modified.
15336 @node Switches for gnatls
15337 @section Switches for @code{gnatls}
15340 @code{gnatls} recognizes the following switches:
15344 @cindex @option{--version} @command{gnatls}
15345 Display Copyright and version, then exit disregarding all other options.
15348 @cindex @option{--help} @command{gnatls}
15349 If @option{--version} was not used, display usage, then exit disregarding
15352 @item ^-a^/ALL_UNITS^
15353 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15354 Consider all units, including those of the predefined Ada library.
15355 Especially useful with @option{^-d^/DEPENDENCIES^}.
15357 @item ^-d^/DEPENDENCIES^
15358 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15359 List sources from which specified units depend on.
15361 @item ^-h^/OUTPUT=OPTIONS^
15362 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15363 Output the list of options.
15365 @item ^-o^/OUTPUT=OBJECTS^
15366 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15367 Only output information about object files.
15369 @item ^-s^/OUTPUT=SOURCES^
15370 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15371 Only output information about source files.
15373 @item ^-u^/OUTPUT=UNITS^
15374 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15375 Only output information about compilation units.
15377 @item ^-files^/FILES^=@var{file}
15378 @cindex @option{^-files^/FILES^} (@code{gnatls})
15379 Take as arguments the files listed in text file @var{file}.
15380 Text file @var{file} may contain empty lines that are ignored.
15381 Each nonempty line should contain the name of an existing file.
15382 Several such switches may be specified simultaneously.
15384 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15385 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15386 @itemx ^-I^/SEARCH=^@var{dir}
15387 @itemx ^-I-^/NOCURRENT_DIRECTORY^
15389 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15390 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15391 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15392 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15393 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15394 flags (@pxref{Switches for gnatmake}).
15396 @item --RTS=@var{rts-path}
15397 @cindex @option{--RTS} (@code{gnatls})
15398 Specifies the default location of the runtime library. Same meaning as the
15399 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15401 @item ^-v^/OUTPUT=VERBOSE^
15402 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15403 Verbose mode. Output the complete source, object and project paths. Do not use
15404 the default column layout but instead use long format giving as much as
15405 information possible on each requested units, including special
15406 characteristics such as:
15409 @item Preelaborable
15410 The unit is preelaborable in the Ada sense.
15413 No elaboration code has been produced by the compiler for this unit.
15416 The unit is pure in the Ada sense.
15418 @item Elaborate_Body
15419 The unit contains a pragma Elaborate_Body.
15422 The unit contains a pragma Remote_Types.
15424 @item Shared_Passive
15425 The unit contains a pragma Shared_Passive.
15428 This unit is part of the predefined environment and cannot be modified
15431 @item Remote_Call_Interface
15432 The unit contains a pragma Remote_Call_Interface.
15438 @node Examples of gnatls Usage
15439 @section Example of @code{gnatls} Usage
15443 Example of using the verbose switch. Note how the source and
15444 object paths are affected by the -I switch.
15447 $ gnatls -v -I.. demo1.o
15449 GNATLS 5.03w (20041123-34)
15450 Copyright 1997-2004 Free Software Foundation, Inc.
15452 Source Search Path:
15453 <Current_Directory>
15455 /home/comar/local/adainclude/
15457 Object Search Path:
15458 <Current_Directory>
15460 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15462 Project Search Path:
15463 <Current_Directory>
15464 /home/comar/local/lib/gnat/
15469 Kind => subprogram body
15470 Flags => No_Elab_Code
15471 Source => demo1.adb modified
15475 The following is an example of use of the dependency list.
15476 Note the use of the -s switch
15477 which gives a straight list of source files. This can be useful for
15478 building specialized scripts.
15481 $ gnatls -d demo2.o
15482 ./demo2.o demo2 OK demo2.adb
15488 $ gnatls -d -s -a demo1.o
15490 /home/comar/local/adainclude/ada.ads
15491 /home/comar/local/adainclude/a-finali.ads
15492 /home/comar/local/adainclude/a-filico.ads
15493 /home/comar/local/adainclude/a-stream.ads
15494 /home/comar/local/adainclude/a-tags.ads
15497 /home/comar/local/adainclude/gnat.ads
15498 /home/comar/local/adainclude/g-io.ads
15500 /home/comar/local/adainclude/system.ads
15501 /home/comar/local/adainclude/s-exctab.ads
15502 /home/comar/local/adainclude/s-finimp.ads
15503 /home/comar/local/adainclude/s-finroo.ads
15504 /home/comar/local/adainclude/s-secsta.ads
15505 /home/comar/local/adainclude/s-stalib.ads
15506 /home/comar/local/adainclude/s-stoele.ads
15507 /home/comar/local/adainclude/s-stratt.ads
15508 /home/comar/local/adainclude/s-tasoli.ads
15509 /home/comar/local/adainclude/s-unstyp.ads
15510 /home/comar/local/adainclude/unchconv.ads
15516 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15518 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15519 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15520 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15521 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15522 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15526 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15527 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15529 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15530 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15531 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15532 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15533 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15534 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15535 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15536 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15537 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15538 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15539 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15543 @node Cleaning Up Using gnatclean
15544 @chapter Cleaning Up Using @code{gnatclean}
15546 @cindex Cleaning tool
15549 @code{gnatclean} is a tool that allows the deletion of files produced by the
15550 compiler, binder and linker, including ALI files, object files, tree files,
15551 expanded source files, library files, interface copy source files, binder
15552 generated files and executable files.
15555 * Running gnatclean::
15556 * Switches for gnatclean::
15557 @c * Examples of gnatclean Usage::
15560 @node Running gnatclean
15561 @section Running @code{gnatclean}
15564 The @code{gnatclean} command has the form:
15567 $ gnatclean switches @var{names}
15571 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15572 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15573 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15576 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15577 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15578 the linker. In informative-only mode, specified by switch
15579 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15580 normal mode is listed, but no file is actually deleted.
15582 @node Switches for gnatclean
15583 @section Switches for @code{gnatclean}
15586 @code{gnatclean} recognizes the following switches:
15590 @cindex @option{--version} @command{gnatclean}
15591 Display Copyright and version, then exit disregarding all other options.
15594 @cindex @option{--help} @command{gnatclean}
15595 If @option{--version} was not used, display usage, then exit disregarding
15598 @item ^--subdirs^/SUBDIRS^=subdir
15599 Actual object directory of each project file is the subdirectory subdir of the
15600 object directory specified or defaulted in the project file.
15602 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15603 By default, shared library projects are not allowed to import static library
15604 projects. When this switch is used on the command line, this restriction is
15607 @item ^-c^/COMPILER_FILES_ONLY^
15608 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15609 Only attempt to delete the files produced by the compiler, not those produced
15610 by the binder or the linker. The files that are not to be deleted are library
15611 files, interface copy files, binder generated files and executable files.
15613 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15614 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15615 Indicate that ALI and object files should normally be found in directory
15618 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15619 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15620 When using project files, if some errors or warnings are detected during
15621 parsing and verbose mode is not in effect (no use of switch
15622 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15623 file, rather than its simple file name.
15626 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15627 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15629 @item ^-n^/NODELETE^
15630 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15631 Informative-only mode. Do not delete any files. Output the list of the files
15632 that would have been deleted if this switch was not specified.
15634 @item ^-P^/PROJECT_FILE=^@var{project}
15635 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15636 Use project file @var{project}. Only one such switch can be used.
15637 When cleaning a project file, the files produced by the compilation of the
15638 immediate sources or inherited sources of the project files are to be
15639 deleted. This is not depending on the presence or not of executable names
15640 on the command line.
15643 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15644 Quiet output. If there are no errors, do not output anything, except in
15645 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15646 (switch ^-n^/NODELETE^).
15648 @item ^-r^/RECURSIVE^
15649 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15650 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15651 clean all imported and extended project files, recursively. If this switch
15652 is not specified, only the files related to the main project file are to be
15653 deleted. This switch has no effect if no project file is specified.
15655 @item ^-v^/VERBOSE^
15656 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15659 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15660 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15661 Indicates the verbosity of the parsing of GNAT project files.
15662 @xref{Switches Related to Project Files}.
15664 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15665 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15666 Indicates that external variable @var{name} has the value @var{value}.
15667 The Project Manager will use this value for occurrences of
15668 @code{external(name)} when parsing the project file.
15669 @xref{Switches Related to Project Files}.
15671 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15672 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15673 When searching for ALI and object files, look in directory
15676 @item ^-I^/SEARCH=^@var{dir}
15677 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15678 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15680 @item ^-I-^/NOCURRENT_DIRECTORY^
15681 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15682 @cindex Source files, suppressing search
15683 Do not look for ALI or object files in the directory
15684 where @code{gnatclean} was invoked.
15688 @c @node Examples of gnatclean Usage
15689 @c @section Examples of @code{gnatclean} Usage
15692 @node GNAT and Libraries
15693 @chapter GNAT and Libraries
15694 @cindex Library, building, installing, using
15697 This chapter describes how to build and use libraries with GNAT, and also shows
15698 how to recompile the GNAT run-time library. You should be familiar with the
15699 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15703 * Introduction to Libraries in GNAT::
15704 * General Ada Libraries::
15705 * Stand-alone Ada Libraries::
15706 * Rebuilding the GNAT Run-Time Library::
15709 @node Introduction to Libraries in GNAT
15710 @section Introduction to Libraries in GNAT
15713 A library is, conceptually, a collection of objects which does not have its
15714 own main thread of execution, but rather provides certain services to the
15715 applications that use it. A library can be either statically linked with the
15716 application, in which case its code is directly included in the application,
15717 or, on platforms that support it, be dynamically linked, in which case
15718 its code is shared by all applications making use of this library.
15720 GNAT supports both types of libraries.
15721 In the static case, the compiled code can be provided in different ways. The
15722 simplest approach is to provide directly the set of objects resulting from
15723 compilation of the library source files. Alternatively, you can group the
15724 objects into an archive using whatever commands are provided by the operating
15725 system. For the latter case, the objects are grouped into a shared library.
15727 In the GNAT environment, a library has three types of components:
15733 @xref{The Ada Library Information Files}.
15735 Object files, an archive or a shared library.
15739 A GNAT library may expose all its source files, which is useful for
15740 documentation purposes. Alternatively, it may expose only the units needed by
15741 an external user to make use of the library. That is to say, the specs
15742 reflecting the library services along with all the units needed to compile
15743 those specs, which can include generic bodies or any body implementing an
15744 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15745 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15747 All compilation units comprising an application, including those in a library,
15748 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15749 computes the elaboration order from the @file{ALI} files and this is why they
15750 constitute a mandatory part of GNAT libraries.
15751 @emph{Stand-alone libraries} are the exception to this rule because a specific
15752 library elaboration routine is produced independently of the application(s)
15755 @node General Ada Libraries
15756 @section General Ada Libraries
15759 * Building a library::
15760 * Installing a library::
15761 * Using a library::
15764 @node Building a library
15765 @subsection Building a library
15768 The easiest way to build a library is to use the Project Manager,
15769 which supports a special type of project called a @emph{Library Project}
15770 (@pxref{Library Projects}).
15772 A project is considered a library project, when two project-level attributes
15773 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15774 control different aspects of library configuration, additional optional
15775 project-level attributes can be specified:
15778 This attribute controls whether the library is to be static or dynamic
15780 @item Library_Version
15781 This attribute specifies the library version; this value is used
15782 during dynamic linking of shared libraries to determine if the currently
15783 installed versions of the binaries are compatible.
15785 @item Library_Options
15787 These attributes specify additional low-level options to be used during
15788 library generation, and redefine the actual application used to generate
15793 The GNAT Project Manager takes full care of the library maintenance task,
15794 including recompilation of the source files for which objects do not exist
15795 or are not up to date, assembly of the library archive, and installation of
15796 the library (i.e., copying associated source, object and @file{ALI} files
15797 to the specified location).
15799 Here is a simple library project file:
15800 @smallexample @c ada
15802 for Source_Dirs use ("src1", "src2");
15803 for Object_Dir use "obj";
15804 for Library_Name use "mylib";
15805 for Library_Dir use "lib";
15806 for Library_Kind use "dynamic";
15811 and the compilation command to build and install the library:
15813 @smallexample @c ada
15814 $ gnatmake -Pmy_lib
15818 It is not entirely trivial to perform manually all the steps required to
15819 produce a library. We recommend that you use the GNAT Project Manager
15820 for this task. In special cases where this is not desired, the necessary
15821 steps are discussed below.
15823 There are various possibilities for compiling the units that make up the
15824 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15825 with a conventional script. For simple libraries, it is also possible to create
15826 a dummy main program which depends upon all the packages that comprise the
15827 interface of the library. This dummy main program can then be given to
15828 @command{gnatmake}, which will ensure that all necessary objects are built.
15830 After this task is accomplished, you should follow the standard procedure
15831 of the underlying operating system to produce the static or shared library.
15833 Here is an example of such a dummy program:
15834 @smallexample @c ada
15836 with My_Lib.Service1;
15837 with My_Lib.Service2;
15838 with My_Lib.Service3;
15839 procedure My_Lib_Dummy is
15847 Here are the generic commands that will build an archive or a shared library.
15850 # compiling the library
15851 $ gnatmake -c my_lib_dummy.adb
15853 # we don't need the dummy object itself
15854 $ rm my_lib_dummy.o my_lib_dummy.ali
15856 # create an archive with the remaining objects
15857 $ ar rc libmy_lib.a *.o
15858 # some systems may require "ranlib" to be run as well
15860 # or create a shared library
15861 $ gcc -shared -o libmy_lib.so *.o
15862 # some systems may require the code to have been compiled with -fPIC
15864 # remove the object files that are now in the library
15867 # Make the ALI files read-only so that gnatmake will not try to
15868 # regenerate the objects that are in the library
15873 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15874 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15875 be accessed by the directive @option{-l@var{xxx}} at link time.
15877 @node Installing a library
15878 @subsection Installing a library
15879 @cindex @code{ADA_PROJECT_PATH}
15880 @cindex @code{GPR_PROJECT_PATH}
15883 If you use project files, library installation is part of the library build
15884 process (@pxref{Installing a library with project files}).
15886 When project files are not an option, it is also possible, but not recommended,
15887 to install the library so that the sources needed to use the library are on the
15888 Ada source path and the ALI files & libraries be on the Ada Object path (see
15889 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15890 administrator can place general-purpose libraries in the default compiler
15891 paths, by specifying the libraries' location in the configuration files
15892 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15893 must be located in the GNAT installation tree at the same place as the gcc spec
15894 file. The location of the gcc spec file can be determined as follows:
15900 The configuration files mentioned above have a simple format: each line
15901 must contain one unique directory name.
15902 Those names are added to the corresponding path
15903 in their order of appearance in the file. The names can be either absolute
15904 or relative; in the latter case, they are relative to where theses files
15907 The files @file{ada_source_path} and @file{ada_object_path} might not be
15909 GNAT installation, in which case, GNAT will look for its run-time library in
15910 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15911 objects and @file{ALI} files). When the files exist, the compiler does not
15912 look in @file{adainclude} and @file{adalib}, and thus the
15913 @file{ada_source_path} file
15914 must contain the location for the GNAT run-time sources (which can simply
15915 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15916 contain the location for the GNAT run-time objects (which can simply
15919 You can also specify a new default path to the run-time library at compilation
15920 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15921 the run-time library you want your program to be compiled with. This switch is
15922 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15923 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15925 It is possible to install a library before or after the standard GNAT
15926 library, by reordering the lines in the configuration files. In general, a
15927 library must be installed before the GNAT library if it redefines
15930 @node Using a library
15931 @subsection Using a library
15933 @noindent Once again, the project facility greatly simplifies the use of
15934 libraries. In this context, using a library is just a matter of adding a
15935 @code{with} clause in the user project. For instance, to make use of the
15936 library @code{My_Lib} shown in examples in earlier sections, you can
15939 @smallexample @c projectfile
15946 Even if you have a third-party, non-Ada library, you can still use GNAT's
15947 Project Manager facility to provide a wrapper for it. For example, the
15948 following project, when @code{with}ed by your main project, will link with the
15949 third-party library @file{liba.a}:
15951 @smallexample @c projectfile
15954 for Externally_Built use "true";
15955 for Source_Files use ();
15956 for Library_Dir use "lib";
15957 for Library_Name use "a";
15958 for Library_Kind use "static";
15962 This is an alternative to the use of @code{pragma Linker_Options}. It is
15963 especially interesting in the context of systems with several interdependent
15964 static libraries where finding a proper linker order is not easy and best be
15965 left to the tools having visibility over project dependence information.
15968 In order to use an Ada library manually, you need to make sure that this
15969 library is on both your source and object path
15970 (see @ref{Search Paths and the Run-Time Library (RTL)}
15971 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15972 in an archive or a shared library, you need to specify the desired
15973 library at link time.
15975 For example, you can use the library @file{mylib} installed in
15976 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15979 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15984 This can be expressed more simply:
15989 when the following conditions are met:
15992 @file{/dir/my_lib_src} has been added by the user to the environment
15993 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15994 @file{ada_source_path}
15996 @file{/dir/my_lib_obj} has been added by the user to the environment
15997 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15998 @file{ada_object_path}
16000 a pragma @code{Linker_Options} has been added to one of the sources.
16003 @smallexample @c ada
16004 pragma Linker_Options ("-lmy_lib");
16008 @node Stand-alone Ada Libraries
16009 @section Stand-alone Ada Libraries
16010 @cindex Stand-alone library, building, using
16013 * Introduction to Stand-alone Libraries::
16014 * Building a Stand-alone Library::
16015 * Creating a Stand-alone Library to be used in a non-Ada context::
16016 * Restrictions in Stand-alone Libraries::
16019 @node Introduction to Stand-alone Libraries
16020 @subsection Introduction to Stand-alone Libraries
16023 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16025 elaborate the Ada units that are included in the library. In contrast with
16026 an ordinary library, which consists of all sources, objects and @file{ALI}
16028 library, a SAL may specify a restricted subset of compilation units
16029 to serve as a library interface. In this case, the fully
16030 self-sufficient set of files will normally consist of an objects
16031 archive, the sources of interface units' specs, and the @file{ALI}
16032 files of interface units.
16033 If an interface spec contains a generic unit or an inlined subprogram,
16035 source must also be provided; if the units that must be provided in the source
16036 form depend on other units, the source and @file{ALI} files of those must
16039 The main purpose of a SAL is to minimize the recompilation overhead of client
16040 applications when a new version of the library is installed. Specifically,
16041 if the interface sources have not changed, client applications do not need to
16042 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16043 version, controlled by @code{Library_Version} attribute, is not changed,
16044 then the clients do not need to be relinked.
16046 SALs also allow the library providers to minimize the amount of library source
16047 text exposed to the clients. Such ``information hiding'' might be useful or
16048 necessary for various reasons.
16050 Stand-alone libraries are also well suited to be used in an executable whose
16051 main routine is not written in Ada.
16053 @node Building a Stand-alone Library
16054 @subsection Building a Stand-alone Library
16057 GNAT's Project facility provides a simple way of building and installing
16058 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16059 To be a Stand-alone Library Project, in addition to the two attributes
16060 that make a project a Library Project (@code{Library_Name} and
16061 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16062 @code{Library_Interface} must be defined. For example:
16064 @smallexample @c projectfile
16066 for Library_Dir use "lib_dir";
16067 for Library_Name use "dummy";
16068 for Library_Interface use ("int1", "int1.child");
16073 Attribute @code{Library_Interface} has a non-empty string list value,
16074 each string in the list designating a unit contained in an immediate source
16075 of the project file.
16077 When a Stand-alone Library is built, first the binder is invoked to build
16078 a package whose name depends on the library name
16079 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16080 This binder-generated package includes initialization and
16081 finalization procedures whose
16082 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16084 above). The object corresponding to this package is included in the library.
16086 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16087 calling of these procedures if a static SAL is built, or if a shared SAL
16089 with the project-level attribute @code{Library_Auto_Init} set to
16092 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16093 (those that are listed in attribute @code{Library_Interface}) are copied to
16094 the Library Directory. As a consequence, only the Interface Units may be
16095 imported from Ada units outside of the library. If other units are imported,
16096 the binding phase will fail.
16098 The attribute @code{Library_Src_Dir} may be specified for a
16099 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16100 single string value. Its value must be the path (absolute or relative to the
16101 project directory) of an existing directory. This directory cannot be the
16102 object directory or one of the source directories, but it can be the same as
16103 the library directory. The sources of the Interface
16104 Units of the library that are needed by an Ada client of the library will be
16105 copied to the designated directory, called the Interface Copy directory.
16106 These sources include the specs of the Interface Units, but they may also
16107 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16108 are used, or when there is a generic unit in the spec. Before the sources
16109 are copied to the Interface Copy directory, an attempt is made to delete all
16110 files in the Interface Copy directory.
16112 Building stand-alone libraries by hand is somewhat tedious, but for those
16113 occasions when it is necessary here are the steps that you need to perform:
16116 Compile all library sources.
16119 Invoke the binder with the switch @option{-n} (No Ada main program),
16120 with all the @file{ALI} files of the interfaces, and
16121 with the switch @option{-L} to give specific names to the @code{init}
16122 and @code{final} procedures. For example:
16124 gnatbind -n int1.ali int2.ali -Lsal1
16128 Compile the binder generated file:
16134 Link the dynamic library with all the necessary object files,
16135 indicating to the linker the names of the @code{init} (and possibly
16136 @code{final}) procedures for automatic initialization (and finalization).
16137 The built library should be placed in a directory different from
16138 the object directory.
16141 Copy the @code{ALI} files of the interface to the library directory,
16142 add in this copy an indication that it is an interface to a SAL
16143 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16144 with letter ``P'') and make the modified copy of the @file{ALI} file
16149 Using SALs is not different from using other libraries
16150 (see @ref{Using a library}).
16152 @node Creating a Stand-alone Library to be used in a non-Ada context
16153 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16156 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16159 The only extra step required is to ensure that library interface subprograms
16160 are compatible with the main program, by means of @code{pragma Export}
16161 or @code{pragma Convention}.
16163 Here is an example of simple library interface for use with C main program:
16165 @smallexample @c ada
16166 package My_Package is
16168 procedure Do_Something;
16169 pragma Export (C, Do_Something, "do_something");
16171 procedure Do_Something_Else;
16172 pragma Export (C, Do_Something_Else, "do_something_else");
16178 On the foreign language side, you must provide a ``foreign'' view of the
16179 library interface; remember that it should contain elaboration routines in
16180 addition to interface subprograms.
16182 The example below shows the content of @code{mylib_interface.h} (note
16183 that there is no rule for the naming of this file, any name can be used)
16185 /* the library elaboration procedure */
16186 extern void mylibinit (void);
16188 /* the library finalization procedure */
16189 extern void mylibfinal (void);
16191 /* the interface exported by the library */
16192 extern void do_something (void);
16193 extern void do_something_else (void);
16197 Libraries built as explained above can be used from any program, provided
16198 that the elaboration procedures (named @code{mylibinit} in the previous
16199 example) are called before the library services are used. Any number of
16200 libraries can be used simultaneously, as long as the elaboration
16201 procedure of each library is called.
16203 Below is an example of a C program that uses the @code{mylib} library.
16206 #include "mylib_interface.h"
16211 /* First, elaborate the library before using it */
16214 /* Main program, using the library exported entities */
16216 do_something_else ();
16218 /* Library finalization at the end of the program */
16225 Note that invoking any library finalization procedure generated by
16226 @code{gnatbind} shuts down the Ada run-time environment.
16228 finalization of all Ada libraries must be performed at the end of the program.
16229 No call to these libraries or to the Ada run-time library should be made
16230 after the finalization phase.
16232 @node Restrictions in Stand-alone Libraries
16233 @subsection Restrictions in Stand-alone Libraries
16236 The pragmas listed below should be used with caution inside libraries,
16237 as they can create incompatibilities with other Ada libraries:
16239 @item pragma @code{Locking_Policy}
16240 @item pragma @code{Queuing_Policy}
16241 @item pragma @code{Task_Dispatching_Policy}
16242 @item pragma @code{Unreserve_All_Interrupts}
16246 When using a library that contains such pragmas, the user must make sure
16247 that all libraries use the same pragmas with the same values. Otherwise,
16248 @code{Program_Error} will
16249 be raised during the elaboration of the conflicting
16250 libraries. The usage of these pragmas and its consequences for the user
16251 should therefore be well documented.
16253 Similarly, the traceback in the exception occurrence mechanism should be
16254 enabled or disabled in a consistent manner across all libraries.
16255 Otherwise, Program_Error will be raised during the elaboration of the
16256 conflicting libraries.
16258 If the @code{Version} or @code{Body_Version}
16259 attributes are used inside a library, then you need to
16260 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16261 libraries, so that version identifiers can be properly computed.
16262 In practice these attributes are rarely used, so this is unlikely
16263 to be a consideration.
16265 @node Rebuilding the GNAT Run-Time Library
16266 @section Rebuilding the GNAT Run-Time Library
16267 @cindex GNAT Run-Time Library, rebuilding
16268 @cindex Building the GNAT Run-Time Library
16269 @cindex Rebuilding the GNAT Run-Time Library
16270 @cindex Run-Time Library, rebuilding
16273 It may be useful to recompile the GNAT library in various contexts, the
16274 most important one being the use of partition-wide configuration pragmas
16275 such as @code{Normalize_Scalars}. A special Makefile called
16276 @code{Makefile.adalib} is provided to that effect and can be found in
16277 the directory containing the GNAT library. The location of this
16278 directory depends on the way the GNAT environment has been installed and can
16279 be determined by means of the command:
16286 The last entry in the object search path usually contains the
16287 gnat library. This Makefile contains its own documentation and in
16288 particular the set of instructions needed to rebuild a new library and
16291 @node Using the GNU make Utility
16292 @chapter Using the GNU @code{make} Utility
16296 This chapter offers some examples of makefiles that solve specific
16297 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16298 make, make, GNU @code{make}}), nor does it try to replace the
16299 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16301 All the examples in this section are specific to the GNU version of
16302 make. Although @command{make} is a standard utility, and the basic language
16303 is the same, these examples use some advanced features found only in
16307 * Using gnatmake in a Makefile::
16308 * Automatically Creating a List of Directories::
16309 * Generating the Command Line Switches::
16310 * Overcoming Command Line Length Limits::
16313 @node Using gnatmake in a Makefile
16314 @section Using gnatmake in a Makefile
16319 Complex project organizations can be handled in a very powerful way by
16320 using GNU make combined with gnatmake. For instance, here is a Makefile
16321 which allows you to build each subsystem of a big project into a separate
16322 shared library. Such a makefile allows you to significantly reduce the link
16323 time of very big applications while maintaining full coherence at
16324 each step of the build process.
16326 The list of dependencies are handled automatically by
16327 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16328 the appropriate directories.
16330 Note that you should also read the example on how to automatically
16331 create the list of directories
16332 (@pxref{Automatically Creating a List of Directories})
16333 which might help you in case your project has a lot of subdirectories.
16338 @font@heightrm=cmr8
16341 ## This Makefile is intended to be used with the following directory
16343 ## - The sources are split into a series of csc (computer software components)
16344 ## Each of these csc is put in its own directory.
16345 ## Their name are referenced by the directory names.
16346 ## They will be compiled into shared library (although this would also work
16347 ## with static libraries
16348 ## - The main program (and possibly other packages that do not belong to any
16349 ## csc is put in the top level directory (where the Makefile is).
16350 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16351 ## \_ second_csc (sources) __ lib (will contain the library)
16353 ## Although this Makefile is build for shared library, it is easy to modify
16354 ## to build partial link objects instead (modify the lines with -shared and
16357 ## With this makefile, you can change any file in the system or add any new
16358 ## file, and everything will be recompiled correctly (only the relevant shared
16359 ## objects will be recompiled, and the main program will be re-linked).
16361 # The list of computer software component for your project. This might be
16362 # generated automatically.
16365 # Name of the main program (no extension)
16368 # If we need to build objects with -fPIC, uncomment the following line
16371 # The following variable should give the directory containing libgnat.so
16372 # You can get this directory through 'gnatls -v'. This is usually the last
16373 # directory in the Object_Path.
16376 # The directories for the libraries
16377 # (This macro expands the list of CSC to the list of shared libraries, you
16378 # could simply use the expanded form:
16379 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16380 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16382 $@{MAIN@}: objects $@{LIB_DIR@}
16383 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16384 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16387 # recompile the sources
16388 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16390 # Note: In a future version of GNAT, the following commands will be simplified
16391 # by a new tool, gnatmlib
16393 mkdir -p $@{dir $@@ @}
16394 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16395 cd $@{dir $@@ @} && cp -f ../*.ali .
16397 # The dependencies for the modules
16398 # Note that we have to force the expansion of *.o, since in some cases
16399 # make won't be able to do it itself.
16400 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16401 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16402 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16404 # Make sure all of the shared libraries are in the path before starting the
16407 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16410 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16411 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16412 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16413 $@{RM@} *.o *.ali $@{MAIN@}
16416 @node Automatically Creating a List of Directories
16417 @section Automatically Creating a List of Directories
16420 In most makefiles, you will have to specify a list of directories, and
16421 store it in a variable. For small projects, it is often easier to
16422 specify each of them by hand, since you then have full control over what
16423 is the proper order for these directories, which ones should be
16426 However, in larger projects, which might involve hundreds of
16427 subdirectories, it might be more convenient to generate this list
16430 The example below presents two methods. The first one, although less
16431 general, gives you more control over the list. It involves wildcard
16432 characters, that are automatically expanded by @command{make}. Its
16433 shortcoming is that you need to explicitly specify some of the
16434 organization of your project, such as for instance the directory tree
16435 depth, whether some directories are found in a separate tree, @enddots{}
16437 The second method is the most general one. It requires an external
16438 program, called @command{find}, which is standard on all Unix systems. All
16439 the directories found under a given root directory will be added to the
16445 @font@heightrm=cmr8
16448 # The examples below are based on the following directory hierarchy:
16449 # All the directories can contain any number of files
16450 # ROOT_DIRECTORY -> a -> aa -> aaa
16453 # -> b -> ba -> baa
16456 # This Makefile creates a variable called DIRS, that can be reused any time
16457 # you need this list (see the other examples in this section)
16459 # The root of your project's directory hierarchy
16463 # First method: specify explicitly the list of directories
16464 # This allows you to specify any subset of all the directories you need.
16467 DIRS := a/aa/ a/ab/ b/ba/
16470 # Second method: use wildcards
16471 # Note that the argument(s) to wildcard below should end with a '/'.
16472 # Since wildcards also return file names, we have to filter them out
16473 # to avoid duplicate directory names.
16474 # We thus use make's @code{dir} and @code{sort} functions.
16475 # It sets DIRs to the following value (note that the directories aaa and baa
16476 # are not given, unless you change the arguments to wildcard).
16477 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16480 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16481 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16484 # Third method: use an external program
16485 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16486 # This is the most complete command: it sets DIRs to the following value:
16487 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16490 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16494 @node Generating the Command Line Switches
16495 @section Generating the Command Line Switches
16498 Once you have created the list of directories as explained in the
16499 previous section (@pxref{Automatically Creating a List of Directories}),
16500 you can easily generate the command line arguments to pass to gnatmake.
16502 For the sake of completeness, this example assumes that the source path
16503 is not the same as the object path, and that you have two separate lists
16507 # see "Automatically creating a list of directories" to create
16512 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16513 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16516 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16519 @node Overcoming Command Line Length Limits
16520 @section Overcoming Command Line Length Limits
16523 One problem that might be encountered on big projects is that many
16524 operating systems limit the length of the command line. It is thus hard to give
16525 gnatmake the list of source and object directories.
16527 This example shows how you can set up environment variables, which will
16528 make @command{gnatmake} behave exactly as if the directories had been
16529 specified on the command line, but have a much higher length limit (or
16530 even none on most systems).
16532 It assumes that you have created a list of directories in your Makefile,
16533 using one of the methods presented in
16534 @ref{Automatically Creating a List of Directories}.
16535 For the sake of completeness, we assume that the object
16536 path (where the ALI files are found) is different from the sources patch.
16538 Note a small trick in the Makefile below: for efficiency reasons, we
16539 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16540 expanded immediately by @code{make}. This way we overcome the standard
16541 make behavior which is to expand the variables only when they are
16544 On Windows, if you are using the standard Windows command shell, you must
16545 replace colons with semicolons in the assignments to these variables.
16550 @font@heightrm=cmr8
16553 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16554 # This is the same thing as putting the -I arguments on the command line.
16555 # (the equivalent of using -aI on the command line would be to define
16556 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16557 # You can of course have different values for these variables.
16559 # Note also that we need to keep the previous values of these variables, since
16560 # they might have been set before running 'make' to specify where the GNAT
16561 # library is installed.
16563 # see "Automatically creating a list of directories" to create these
16569 space:=$@{empty@} $@{empty@}
16570 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16571 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16572 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16573 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16574 export ADA_INCLUDE_PATH
16575 export ADA_OBJECTS_PATH
16582 @node Memory Management Issues
16583 @chapter Memory Management Issues
16586 This chapter describes some useful memory pools provided in the GNAT library
16587 and in particular the GNAT Debug Pool facility, which can be used to detect
16588 incorrect uses of access values (including ``dangling references'').
16590 It also describes the @command{gnatmem} tool, which can be used to track down
16595 * Some Useful Memory Pools::
16596 * The GNAT Debug Pool Facility::
16598 * The gnatmem Tool::
16602 @node Some Useful Memory Pools
16603 @section Some Useful Memory Pools
16604 @findex Memory Pool
16605 @cindex storage, pool
16608 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16609 storage pool. Allocations use the standard system call @code{malloc} while
16610 deallocations use the standard system call @code{free}. No reclamation is
16611 performed when the pool goes out of scope. For performance reasons, the
16612 standard default Ada allocators/deallocators do not use any explicit storage
16613 pools but if they did, they could use this storage pool without any change in
16614 behavior. That is why this storage pool is used when the user
16615 manages to make the default implicit allocator explicit as in this example:
16616 @smallexample @c ada
16617 type T1 is access Something;
16618 -- no Storage pool is defined for T2
16619 type T2 is access Something_Else;
16620 for T2'Storage_Pool use T1'Storage_Pool;
16621 -- the above is equivalent to
16622 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16626 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16627 pool. The allocation strategy is similar to @code{Pool_Local}'s
16628 except that the all
16629 storage allocated with this pool is reclaimed when the pool object goes out of
16630 scope. This pool provides a explicit mechanism similar to the implicit one
16631 provided by several Ada 83 compilers for allocations performed through a local
16632 access type and whose purpose was to reclaim memory when exiting the
16633 scope of a given local access. As an example, the following program does not
16634 leak memory even though it does not perform explicit deallocation:
16636 @smallexample @c ada
16637 with System.Pool_Local;
16638 procedure Pooloc1 is
16639 procedure Internal is
16640 type A is access Integer;
16641 X : System.Pool_Local.Unbounded_Reclaim_Pool;
16642 for A'Storage_Pool use X;
16645 for I in 1 .. 50 loop
16650 for I in 1 .. 100 loop
16657 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16658 @code{Storage_Size} is specified for an access type.
16659 The whole storage for the pool is
16660 allocated at once, usually on the stack at the point where the access type is
16661 elaborated. It is automatically reclaimed when exiting the scope where the
16662 access type is defined. This package is not intended to be used directly by the
16663 user and it is implicitly used for each such declaration:
16665 @smallexample @c ada
16666 type T1 is access Something;
16667 for T1'Storage_Size use 10_000;
16670 @node The GNAT Debug Pool Facility
16671 @section The GNAT Debug Pool Facility
16673 @cindex storage, pool, memory corruption
16676 The use of unchecked deallocation and unchecked conversion can easily
16677 lead to incorrect memory references. The problems generated by such
16678 references are usually difficult to tackle because the symptoms can be
16679 very remote from the origin of the problem. In such cases, it is
16680 very helpful to detect the problem as early as possible. This is the
16681 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16683 In order to use the GNAT specific debugging pool, the user must
16684 associate a debug pool object with each of the access types that may be
16685 related to suspected memory problems. See Ada Reference Manual 13.11.
16686 @smallexample @c ada
16687 type Ptr is access Some_Type;
16688 Pool : GNAT.Debug_Pools.Debug_Pool;
16689 for Ptr'Storage_Pool use Pool;
16693 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16694 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16695 allow the user to redefine allocation and deallocation strategies. They
16696 also provide a checkpoint for each dereference, through the use of
16697 the primitive operation @code{Dereference} which is implicitly called at
16698 each dereference of an access value.
16700 Once an access type has been associated with a debug pool, operations on
16701 values of the type may raise four distinct exceptions,
16702 which correspond to four potential kinds of memory corruption:
16705 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16707 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16709 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16711 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16715 For types associated with a Debug_Pool, dynamic allocation is performed using
16716 the standard GNAT allocation routine. References to all allocated chunks of
16717 memory are kept in an internal dictionary. Several deallocation strategies are
16718 provided, whereupon the user can choose to release the memory to the system,
16719 keep it allocated for further invalid access checks, or fill it with an easily
16720 recognizable pattern for debug sessions. The memory pattern is the old IBM
16721 hexadecimal convention: @code{16#DEADBEEF#}.
16723 See the documentation in the file g-debpoo.ads for more information on the
16724 various strategies.
16726 Upon each dereference, a check is made that the access value denotes a
16727 properly allocated memory location. Here is a complete example of use of
16728 @code{Debug_Pools}, that includes typical instances of memory corruption:
16729 @smallexample @c ada
16733 with Gnat.Io; use Gnat.Io;
16734 with Unchecked_Deallocation;
16735 with Unchecked_Conversion;
16736 with GNAT.Debug_Pools;
16737 with System.Storage_Elements;
16738 with Ada.Exceptions; use Ada.Exceptions;
16739 procedure Debug_Pool_Test is
16741 type T is access Integer;
16742 type U is access all T;
16744 P : GNAT.Debug_Pools.Debug_Pool;
16745 for T'Storage_Pool use P;
16747 procedure Free is new Unchecked_Deallocation (Integer, T);
16748 function UC is new Unchecked_Conversion (U, T);
16751 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16761 Put_Line (Integer'Image(B.all));
16763 when E : others => Put_Line ("raised: " & Exception_Name (E));
16768 when E : others => Put_Line ("raised: " & Exception_Name (E));
16772 Put_Line (Integer'Image(B.all));
16774 when E : others => Put_Line ("raised: " & Exception_Name (E));
16779 when E : others => Put_Line ("raised: " & Exception_Name (E));
16782 end Debug_Pool_Test;
16786 The debug pool mechanism provides the following precise diagnostics on the
16787 execution of this erroneous program:
16790 Total allocated bytes : 0
16791 Total deallocated bytes : 0
16792 Current Water Mark: 0
16796 Total allocated bytes : 8
16797 Total deallocated bytes : 0
16798 Current Water Mark: 8
16801 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16802 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16803 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16804 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16806 Total allocated bytes : 8
16807 Total deallocated bytes : 4
16808 Current Water Mark: 4
16813 @node The gnatmem Tool
16814 @section The @command{gnatmem} Tool
16818 The @code{gnatmem} utility monitors dynamic allocation and
16819 deallocation activity in a program, and displays information about
16820 incorrect deallocations and possible sources of memory leaks.
16821 It is designed to work in association with a static runtime library
16822 only and in this context provides three types of information:
16825 General information concerning memory management, such as the total
16826 number of allocations and deallocations, the amount of allocated
16827 memory and the high water mark, i.e.@: the largest amount of allocated
16828 memory in the course of program execution.
16831 Backtraces for all incorrect deallocations, that is to say deallocations
16832 which do not correspond to a valid allocation.
16835 Information on each allocation that is potentially the origin of a memory
16840 * Running gnatmem::
16841 * Switches for gnatmem::
16842 * Example of gnatmem Usage::
16845 @node Running gnatmem
16846 @subsection Running @code{gnatmem}
16849 @code{gnatmem} makes use of the output created by the special version of
16850 allocation and deallocation routines that record call information. This
16851 allows to obtain accurate dynamic memory usage history at a minimal cost to
16852 the execution speed. Note however, that @code{gnatmem} is not supported on
16853 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16854 Solaris and Windows NT/2000/XP (x86).
16857 The @code{gnatmem} command has the form
16860 @c $ gnatmem @ovar{switches} user_program
16861 @c Expanding @ovar macro inline (explanation in macro def comments)
16862 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16866 The program must have been linked with the instrumented version of the
16867 allocation and deallocation routines. This is done by linking with the
16868 @file{libgmem.a} library. For correct symbolic backtrace information,
16869 the user program should be compiled with debugging options
16870 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16873 $ gnatmake -g my_program -largs -lgmem
16877 As library @file{libgmem.a} contains an alternate body for package
16878 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16879 when an executable is linked with library @file{libgmem.a}. It is then not
16880 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16883 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16884 This file contains information about all allocations and deallocations
16885 performed by the program. It is produced by the instrumented allocations and
16886 deallocations routines and will be used by @code{gnatmem}.
16888 In order to produce symbolic backtrace information for allocations and
16889 deallocations performed by the GNAT run-time library, you need to use a
16890 version of that library that has been compiled with the @option{-g} switch
16891 (see @ref{Rebuilding the GNAT Run-Time Library}).
16893 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16894 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16895 @option{-i} switch, gnatmem will assume that this file can be found in the
16896 current directory. For example, after you have executed @file{my_program},
16897 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16900 $ gnatmem my_program
16904 This will produce the output with the following format:
16906 *************** debut cc
16908 $ gnatmem my_program
16912 Total number of allocations : 45
16913 Total number of deallocations : 6
16914 Final Water Mark (non freed mem) : 11.29 Kilobytes
16915 High Water Mark : 11.40 Kilobytes
16920 Allocation Root # 2
16921 -------------------
16922 Number of non freed allocations : 11
16923 Final Water Mark (non freed mem) : 1.16 Kilobytes
16924 High Water Mark : 1.27 Kilobytes
16926 my_program.adb:23 my_program.alloc
16932 The first block of output gives general information. In this case, the
16933 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16934 Unchecked_Deallocation routine occurred.
16937 Subsequent paragraphs display information on all allocation roots.
16938 An allocation root is a specific point in the execution of the program
16939 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16940 construct. This root is represented by an execution backtrace (or subprogram
16941 call stack). By default the backtrace depth for allocations roots is 1, so
16942 that a root corresponds exactly to a source location. The backtrace can
16943 be made deeper, to make the root more specific.
16945 @node Switches for gnatmem
16946 @subsection Switches for @code{gnatmem}
16949 @code{gnatmem} recognizes the following switches:
16954 @cindex @option{-q} (@code{gnatmem})
16955 Quiet. Gives the minimum output needed to identify the origin of the
16956 memory leaks. Omits statistical information.
16959 @cindex @var{N} (@code{gnatmem})
16960 N is an integer literal (usually between 1 and 10) which controls the
16961 depth of the backtraces defining allocation root. The default value for
16962 N is 1. The deeper the backtrace, the more precise the localization of
16963 the root. Note that the total number of roots can depend on this
16964 parameter. This parameter must be specified @emph{before} the name of the
16965 executable to be analyzed, to avoid ambiguity.
16968 @cindex @option{-b} (@code{gnatmem})
16969 This switch has the same effect as just depth parameter.
16971 @item -i @var{file}
16972 @cindex @option{-i} (@code{gnatmem})
16973 Do the @code{gnatmem} processing starting from @file{file}, rather than
16974 @file{gmem.out} in the current directory.
16977 @cindex @option{-m} (@code{gnatmem})
16978 This switch causes @code{gnatmem} to mask the allocation roots that have less
16979 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16980 examine even the roots that didn't result in leaks.
16983 @cindex @option{-s} (@code{gnatmem})
16984 This switch causes @code{gnatmem} to sort the allocation roots according to the
16985 specified order of sort criteria, each identified by a single letter. The
16986 currently supported criteria are @code{n, h, w} standing respectively for
16987 number of unfreed allocations, high watermark, and final watermark
16988 corresponding to a specific root. The default order is @code{nwh}.
16992 @node Example of gnatmem Usage
16993 @subsection Example of @code{gnatmem} Usage
16996 The following example shows the use of @code{gnatmem}
16997 on a simple memory-leaking program.
16998 Suppose that we have the following Ada program:
17000 @smallexample @c ada
17003 with Unchecked_Deallocation;
17004 procedure Test_Gm is
17006 type T is array (1..1000) of Integer;
17007 type Ptr is access T;
17008 procedure Free is new Unchecked_Deallocation (T, Ptr);
17011 procedure My_Alloc is
17016 procedure My_DeAlloc is
17024 for I in 1 .. 5 loop
17025 for J in I .. 5 loop
17036 The program needs to be compiled with debugging option and linked with
17037 @code{gmem} library:
17040 $ gnatmake -g test_gm -largs -lgmem
17044 Then we execute the program as usual:
17051 Then @code{gnatmem} is invoked simply with
17057 which produces the following output (result may vary on different platforms):
17062 Total number of allocations : 18
17063 Total number of deallocations : 5
17064 Final Water Mark (non freed mem) : 53.00 Kilobytes
17065 High Water Mark : 56.90 Kilobytes
17067 Allocation Root # 1
17068 -------------------
17069 Number of non freed allocations : 11
17070 Final Water Mark (non freed mem) : 42.97 Kilobytes
17071 High Water Mark : 46.88 Kilobytes
17073 test_gm.adb:11 test_gm.my_alloc
17075 Allocation Root # 2
17076 -------------------
17077 Number of non freed allocations : 1
17078 Final Water Mark (non freed mem) : 10.02 Kilobytes
17079 High Water Mark : 10.02 Kilobytes
17081 s-secsta.adb:81 system.secondary_stack.ss_init
17083 Allocation Root # 3
17084 -------------------
17085 Number of non freed allocations : 1
17086 Final Water Mark (non freed mem) : 12 Bytes
17087 High Water Mark : 12 Bytes
17089 s-secsta.adb:181 system.secondary_stack.ss_init
17093 Note that the GNAT run time contains itself a certain number of
17094 allocations that have no corresponding deallocation,
17095 as shown here for root #2 and root
17096 #3. This is a normal behavior when the number of non-freed allocations
17097 is one, it allocates dynamic data structures that the run time needs for
17098 the complete lifetime of the program. Note also that there is only one
17099 allocation root in the user program with a single line back trace:
17100 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17101 program shows that 'My_Alloc' is called at 2 different points in the
17102 source (line 21 and line 24). If those two allocation roots need to be
17103 distinguished, the backtrace depth parameter can be used:
17106 $ gnatmem 3 test_gm
17110 which will give the following output:
17115 Total number of allocations : 18
17116 Total number of deallocations : 5
17117 Final Water Mark (non freed mem) : 53.00 Kilobytes
17118 High Water Mark : 56.90 Kilobytes
17120 Allocation Root # 1
17121 -------------------
17122 Number of non freed allocations : 10
17123 Final Water Mark (non freed mem) : 39.06 Kilobytes
17124 High Water Mark : 42.97 Kilobytes
17126 test_gm.adb:11 test_gm.my_alloc
17127 test_gm.adb:24 test_gm
17128 b_test_gm.c:52 main
17130 Allocation Root # 2
17131 -------------------
17132 Number of non freed allocations : 1
17133 Final Water Mark (non freed mem) : 10.02 Kilobytes
17134 High Water Mark : 10.02 Kilobytes
17136 s-secsta.adb:81 system.secondary_stack.ss_init
17137 s-secsta.adb:283 <system__secondary_stack___elabb>
17138 b_test_gm.c:33 adainit
17140 Allocation Root # 3
17141 -------------------
17142 Number of non freed allocations : 1
17143 Final Water Mark (non freed mem) : 3.91 Kilobytes
17144 High Water Mark : 3.91 Kilobytes
17146 test_gm.adb:11 test_gm.my_alloc
17147 test_gm.adb:21 test_gm
17148 b_test_gm.c:52 main
17150 Allocation Root # 4
17151 -------------------
17152 Number of non freed allocations : 1
17153 Final Water Mark (non freed mem) : 12 Bytes
17154 High Water Mark : 12 Bytes
17156 s-secsta.adb:181 system.secondary_stack.ss_init
17157 s-secsta.adb:283 <system__secondary_stack___elabb>
17158 b_test_gm.c:33 adainit
17162 The allocation root #1 of the first example has been split in 2 roots #1
17163 and #3 thanks to the more precise associated backtrace.
17167 @node Stack Related Facilities
17168 @chapter Stack Related Facilities
17171 This chapter describes some useful tools associated with stack
17172 checking and analysis. In
17173 particular, it deals with dynamic and static stack usage measurements.
17176 * Stack Overflow Checking::
17177 * Static Stack Usage Analysis::
17178 * Dynamic Stack Usage Analysis::
17181 @node Stack Overflow Checking
17182 @section Stack Overflow Checking
17183 @cindex Stack Overflow Checking
17184 @cindex -fstack-check
17187 For most operating systems, @command{gcc} does not perform stack overflow
17188 checking by default. This means that if the main environment task or
17189 some other task exceeds the available stack space, then unpredictable
17190 behavior will occur. Most native systems offer some level of protection by
17191 adding a guard page at the end of each task stack. This mechanism is usually
17192 not enough for dealing properly with stack overflow situations because
17193 a large local variable could ``jump'' above the guard page.
17194 Furthermore, when the
17195 guard page is hit, there may not be any space left on the stack for executing
17196 the exception propagation code. Enabling stack checking avoids
17199 To activate stack checking, compile all units with the gcc option
17200 @option{-fstack-check}. For example:
17203 gcc -c -fstack-check package1.adb
17207 Units compiled with this option will generate extra instructions to check
17208 that any use of the stack (for procedure calls or for declaring local
17209 variables in declare blocks) does not exceed the available stack space.
17210 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17212 For declared tasks, the stack size is controlled by the size
17213 given in an applicable @code{Storage_Size} pragma or by the value specified
17214 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17215 the default size as defined in the GNAT runtime otherwise.
17217 For the environment task, the stack size depends on
17218 system defaults and is unknown to the compiler. Stack checking
17219 may still work correctly if a fixed
17220 size stack is allocated, but this cannot be guaranteed.
17222 To ensure that a clean exception is signalled for stack
17223 overflow, set the environment variable
17224 @env{GNAT_STACK_LIMIT} to indicate the maximum
17225 stack area that can be used, as in:
17226 @cindex GNAT_STACK_LIMIT
17229 SET GNAT_STACK_LIMIT 1600
17233 The limit is given in kilobytes, so the above declaration would
17234 set the stack limit of the environment task to 1.6 megabytes.
17235 Note that the only purpose of this usage is to limit the amount
17236 of stack used by the environment task. If it is necessary to
17237 increase the amount of stack for the environment task, then this
17238 is an operating systems issue, and must be addressed with the
17239 appropriate operating systems commands.
17242 To have a fixed size stack in the environment task, the stack must be put
17243 in the P0 address space and its size specified. Use these switches to
17247 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17251 The quotes are required to keep case. The number after @samp{STACK=} is the
17252 size of the environmental task stack in pagelets (512 bytes). In this example
17253 the stack size is about 2 megabytes.
17256 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17257 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
17258 more details about the @option{/p0image} qualifier and the @option{stack}
17262 @node Static Stack Usage Analysis
17263 @section Static Stack Usage Analysis
17264 @cindex Static Stack Usage Analysis
17265 @cindex -fstack-usage
17268 A unit compiled with @option{-fstack-usage} will generate an extra file
17270 the maximum amount of stack used, on a per-function basis.
17271 The file has the same
17272 basename as the target object file with a @file{.su} extension.
17273 Each line of this file is made up of three fields:
17277 The name of the function.
17281 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17284 The second field corresponds to the size of the known part of the function
17287 The qualifier @code{static} means that the function frame size
17289 It usually means that all local variables have a static size.
17290 In this case, the second field is a reliable measure of the function stack
17293 The qualifier @code{dynamic} means that the function frame size is not static.
17294 It happens mainly when some local variables have a dynamic size. When this
17295 qualifier appears alone, the second field is not a reliable measure
17296 of the function stack analysis. When it is qualified with @code{bounded}, it
17297 means that the second field is a reliable maximum of the function stack
17300 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17301 subprogram whose stack usage might be larger than the specified amount of
17302 bytes. The wording is in keeping with the qualifier documented above.
17304 @node Dynamic Stack Usage Analysis
17305 @section Dynamic Stack Usage Analysis
17308 It is possible to measure the maximum amount of stack used by a task, by
17309 adding a switch to @command{gnatbind}, as:
17312 $ gnatbind -u0 file
17316 With this option, at each task termination, its stack usage is output on
17318 It is not always convenient to output the stack usage when the program
17319 is still running. Hence, it is possible to delay this output until program
17320 termination. for a given number of tasks specified as the argument of the
17321 @option{-u} option. For instance:
17324 $ gnatbind -u100 file
17328 will buffer the stack usage information of the first 100 tasks to terminate and
17329 output this info at program termination. Results are displayed in four
17333 Index | Task Name | Stack Size | Stack Usage
17340 is a number associated with each task.
17343 is the name of the task analyzed.
17346 is the maximum size for the stack.
17349 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17350 is not entirely analyzed, and it's not possible to know exactly how
17351 much has actually been used.
17356 The environment task stack, e.g., the stack that contains the main unit, is
17357 only processed when the environment variable GNAT_STACK_LIMIT is set.
17360 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17361 stack usage reports at run-time. See its body for the details.
17363 @c *********************************
17365 @c *********************************
17366 @node Verifying Properties Using gnatcheck
17367 @chapter Verifying Properties Using @command{gnatcheck}
17369 @cindex @command{gnatcheck}
17372 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17373 of Ada source files according to a given set of semantic rules.
17376 In order to check compliance with a given rule, @command{gnatcheck} has to
17377 semantically analyze the Ada sources.
17378 Therefore, checks can only be performed on
17379 legal Ada units. Moreover, when a unit depends semantically upon units located
17380 outside the current directory, the source search path has to be provided when
17381 calling @command{gnatcheck}, either through a specified project file or
17382 through @command{gnatcheck} switches.
17384 For full details, refer to @cite{GNATcheck Reference Manual} document.
17387 @c *********************************
17388 @node Creating Sample Bodies Using gnatstub
17389 @chapter Creating Sample Bodies Using @command{gnatstub}
17393 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17394 for library unit declarations.
17396 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17397 driver (see @ref{The GNAT Driver and Project Files}).
17399 To create a body stub, @command{gnatstub} has to compile the library
17400 unit declaration. Therefore, bodies can be created only for legal
17401 library units. Moreover, if a library unit depends semantically upon
17402 units located outside the current directory, you have to provide
17403 the source search path when calling @command{gnatstub}, see the description
17404 of @command{gnatstub} switches below.
17406 By default, all the program unit body stubs generated by @code{gnatstub}
17407 raise the predefined @code{Program_Error} exception, which will catch
17408 accidental calls of generated stubs. This behavior can be changed with
17409 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17412 * Running gnatstub::
17413 * Switches for gnatstub::
17416 @node Running gnatstub
17417 @section Running @command{gnatstub}
17420 @command{gnatstub} has the command-line interface of the form
17423 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17424 @c Expanding @ovar macro inline (explanation in macro def comments)
17425 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17432 is the name of the source file that contains a library unit declaration
17433 for which a body must be created. The file name may contain the path
17435 The file name does not have to follow the GNAT file name conventions. If the
17437 does not follow GNAT file naming conventions, the name of the body file must
17439 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17440 If the file name follows the GNAT file naming
17441 conventions and the name of the body file is not provided,
17444 of the body file from the argument file name by replacing the @file{.ads}
17446 with the @file{.adb} suffix.
17449 indicates the directory in which the body stub is to be placed (the default
17453 @item @samp{@var{gcc_switches}} is a list of switches for
17454 @command{gcc}. They will be passed on to all compiler invocations made by
17455 @command{gnatelim} to generate the ASIS trees. Here you can provide
17456 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17457 use the @option{-gnatec} switch to set the configuration file,
17458 use the @option{-gnat05} switch if sources should be compiled in
17462 is an optional sequence of switches as described in the next section
17465 @node Switches for gnatstub
17466 @section Switches for @command{gnatstub}
17472 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17473 If the destination directory already contains a file with the name of the
17475 for the argument spec file, replace it with the generated body stub.
17477 @item ^-hs^/HEADER=SPEC^
17478 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17479 Put the comment header (i.e., all the comments preceding the
17480 compilation unit) from the source of the library unit declaration
17481 into the body stub.
17483 @item ^-hg^/HEADER=GENERAL^
17484 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17485 Put a sample comment header into the body stub.
17487 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17488 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17489 Use the content of the file as the comment header for a generated body stub.
17493 @cindex @option{-IDIR} (@command{gnatstub})
17495 @cindex @option{-I-} (@command{gnatstub})
17498 @item /NOCURRENT_DIRECTORY
17499 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17501 ^These switches have ^This switch has^ the same meaning as in calls to
17503 ^They define ^It defines ^ the source search path in the call to
17504 @command{gcc} issued
17505 by @command{gnatstub} to compile an argument source file.
17507 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17508 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17509 This switch has the same meaning as in calls to @command{gcc}.
17510 It defines the additional configuration file to be passed to the call to
17511 @command{gcc} issued
17512 by @command{gnatstub} to compile an argument source file.
17514 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17515 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17516 (@var{n} is a non-negative integer). Set the maximum line length in the
17517 body stub to @var{n}; the default is 79. The maximum value that can be
17518 specified is 32767. Note that in the special case of configuration
17519 pragma files, the maximum is always 32767 regardless of whether or
17520 not this switch appears.
17522 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17523 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17524 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17525 the generated body sample to @var{n}.
17526 The default indentation is 3.
17528 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17529 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17530 Order local bodies alphabetically. (By default local bodies are ordered
17531 in the same way as the corresponding local specs in the argument spec file.)
17533 @item ^-i^/INDENTATION=^@var{n}
17534 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17535 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17537 @item ^-k^/TREE_FILE=SAVE^
17538 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17539 Do not remove the tree file (i.e., the snapshot of the compiler internal
17540 structures used by @command{gnatstub}) after creating the body stub.
17542 @item ^-l^/LINE_LENGTH=^@var{n}
17543 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17544 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17546 @item ^--no-exception^/NO_EXCEPTION^
17547 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17548 void raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17549 This is not always possible for function stubs.
17551 @item ^--no-local-header^/NO_LOCAL_HEADER^
17552 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17553 Do not place local comment header with unit name before body stub for a
17556 @item ^-o ^/BODY=^@var{body-name}
17557 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17558 Body file name. This should be set if the argument file name does not
17560 the GNAT file naming
17561 conventions. If this switch is omitted the default name for the body will be
17563 from the argument file name according to the GNAT file naming conventions.
17566 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17567 Quiet mode: do not generate a confirmation when a body is
17568 successfully created, and do not generate a message when a body is not
17572 @item ^-r^/TREE_FILE=REUSE^
17573 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17574 Reuse the tree file (if it exists) instead of creating it. Instead of
17575 creating the tree file for the library unit declaration, @command{gnatstub}
17576 tries to find it in the current directory and use it for creating
17577 a body. If the tree file is not found, no body is created. This option
17578 also implies @option{^-k^/SAVE^}, whether or not
17579 the latter is set explicitly.
17581 @item ^-t^/TREE_FILE=OVERWRITE^
17582 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17583 Overwrite the existing tree file. If the current directory already
17584 contains the file which, according to the GNAT file naming rules should
17585 be considered as a tree file for the argument source file,
17587 will refuse to create the tree file needed to create a sample body
17588 unless this option is set.
17590 @item ^-v^/VERBOSE^
17591 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17592 Verbose mode: generate version information.
17596 @c *********************************
17597 @node Generating Ada Bindings for C and C++ headers
17598 @chapter Generating Ada Bindings for C and C++ headers
17602 GNAT now comes with a binding generator for C and C++ headers which is
17603 intended to do 95% of the tedious work of generating Ada specs from C
17604 or C++ header files.
17606 Note that this capability is not intended to generate 100% correct Ada specs,
17607 and will is some cases require manual adjustments, although it can often
17608 be used out of the box in practice.
17610 Some of the known limitations include:
17613 @item only very simple character constant macros are translated into Ada
17614 constants. Function macros (macros with arguments) are partially translated
17615 as comments, to be completed manually if needed.
17616 @item some extensions (e.g. vector types) are not supported
17617 @item pointers to pointers or complex structures are mapped to System.Address
17618 @item identifiers with identical name (except casing) will generate compilation
17619 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
17622 The code generated is using the Ada 2005 syntax, which makes it
17623 easier to interface with other languages than previous versions of Ada.
17626 * Running the binding generator::
17627 * Generating bindings for C++ headers::
17631 @node Running the binding generator
17632 @section Running the binding generator
17635 The binding generator is part of the @command{gcc} compiler and can be
17636 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
17637 spec files for the header files specified on the command line, and all
17638 header files needed by these files transitively. For example:
17641 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
17642 $ gcc -c -gnat05 *.ads
17645 will generate, under GNU/Linux, the following files: @file{time_h.ads},
17646 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
17647 correspond to the files @file{/usr/include/time.h},
17648 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
17649 mode these Ada specs.
17651 The @code{-C} switch tells @command{gcc} to extract comments from headers,
17652 and will attempt to generate corresponding Ada comments.
17654 If you want to generate a single Ada file and not the transitive closure, you
17655 can use instead the @option{-fdump-ada-spec-slim} switch.
17657 Note that we recommend when possible to use the @command{g++} driver to
17658 generate bindings, even for most C headers, since this will in general
17659 generate better Ada specs. For generating bindings for C++ headers, it is
17660 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
17661 is equivalent in this case. If @command{g++} cannot work on your C headers
17662 because of incompatibilities between C and C++, then you can fallback to
17663 @command{gcc} instead.
17665 For an example of better bindings generated from the C++ front-end,
17666 the name of the parameters (when available) are actually ignored by the C
17667 front-end. Consider the following C header:
17670 extern void foo (int variable);
17673 with the C front-end, @code{variable} is ignored, and the above is handled as:
17676 extern void foo (int);
17679 generating a generic:
17682 procedure foo (param1 : int);
17685 with the C++ front-end, the name is available, and we generate:
17688 procedure foo (variable : int);
17691 In some cases, the generated bindings will be more complete or more meaningful
17692 when defining some macros, which you can do via the @option{-D} switch. This
17693 is for example the case with @file{Xlib.h} under GNU/Linux:
17696 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
17699 The above will generate more complete bindings than a straight call without
17700 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
17702 In other cases, it is not possible to parse a header file in a stand alone
17703 manner, because other include files need to be included first. In this
17704 case, the solution is to create a small header file including the needed
17705 @code{#include} and possible @code{#define} directives. For example, to
17706 generate Ada bindings for @file{readline/readline.h}, you need to first
17707 include @file{stdio.h}, so you can create a file with the following two
17708 lines in e.g. @file{readline1.h}:
17712 #include <readline/readline.h>
17715 and then generate Ada bindings from this file:
17718 $ g++ -c -fdump-ada-spec readline1.h
17721 @node Generating bindings for C++ headers
17722 @section Generating bindings for C++ headers
17725 Generating bindings for C++ headers is done using the same options, always
17726 with the @command{g++} compiler.
17728 In this mode, C++ classes will be mapped to Ada tagged types, constructors
17729 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
17730 multiple inheritance of abstract classes will be mapped to Ada interfaces
17731 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
17732 information on interfacing to C++).
17734 For example, given the following C++ header file:
17741 virtual int Number_Of_Teeth () = 0;
17746 virtual void Set_Owner (char* Name) = 0;
17752 virtual void Set_Age (int New_Age);
17755 class Dog : Animal, Carnivore, Domestic @{
17760 virtual int Number_Of_Teeth ();
17761 virtual void Set_Owner (char* Name);
17769 The corresponding Ada code is generated:
17771 @smallexample @c ada
17774 package Class_Carnivore is
17775 type Carnivore is limited interface;
17776 pragma Import (CPP, Carnivore);
17778 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
17780 use Class_Carnivore;
17782 package Class_Domestic is
17783 type Domestic is limited interface;
17784 pragma Import (CPP, Domestic);
17786 procedure Set_Owner
17787 (this : access Domestic;
17788 Name : Interfaces.C.Strings.chars_ptr) is abstract;
17790 use Class_Domestic;
17792 package Class_Animal is
17793 type Animal is tagged limited record
17794 Age_Count : aliased int;
17796 pragma Import (CPP, Animal);
17798 procedure Set_Age (this : access Animal; New_Age : int);
17799 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
17803 package Class_Dog is
17804 type Dog is new Animal and Carnivore and Domestic with record
17805 Tooth_Count : aliased int;
17806 Owner : Interfaces.C.Strings.chars_ptr;
17808 pragma Import (CPP, Dog);
17810 function Number_Of_Teeth (this : access Dog) return int;
17811 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
17813 procedure Set_Owner
17814 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
17815 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
17817 function New_Dog return Dog;
17818 pragma CPP_Constructor (New_Dog);
17819 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
17830 @item -fdump-ada-spec
17831 @cindex @option{-fdump-ada-spec} (@command{gcc})
17832 Generate Ada spec files for the given header files transitively (including
17833 all header files that these headers depend upon).
17835 @item -fdump-ada-spec-slim
17836 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
17837 Generate Ada spec files for the header files specified on the command line
17841 @cindex @option{-C} (@command{gcc})
17842 Extract comments from headers and generate Ada comments in the Ada spec files.
17845 @node Other Utility Programs
17846 @chapter Other Utility Programs
17849 This chapter discusses some other utility programs available in the Ada
17853 * Using Other Utility Programs with GNAT::
17854 * The External Symbol Naming Scheme of GNAT::
17855 * Converting Ada Files to html with gnathtml::
17856 * Installing gnathtml::
17863 @node Using Other Utility Programs with GNAT
17864 @section Using Other Utility Programs with GNAT
17867 The object files generated by GNAT are in standard system format and in
17868 particular the debugging information uses this format. This means
17869 programs generated by GNAT can be used with existing utilities that
17870 depend on these formats.
17873 In general, any utility program that works with C will also often work with
17874 Ada programs generated by GNAT. This includes software utilities such as
17875 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17879 @node The External Symbol Naming Scheme of GNAT
17880 @section The External Symbol Naming Scheme of GNAT
17883 In order to interpret the output from GNAT, when using tools that are
17884 originally intended for use with other languages, it is useful to
17885 understand the conventions used to generate link names from the Ada
17888 All link names are in all lowercase letters. With the exception of library
17889 procedure names, the mechanism used is simply to use the full expanded
17890 Ada name with dots replaced by double underscores. For example, suppose
17891 we have the following package spec:
17893 @smallexample @c ada
17904 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17905 the corresponding link name is @code{qrs__mn}.
17907 Of course if a @code{pragma Export} is used this may be overridden:
17909 @smallexample @c ada
17914 pragma Export (Var1, C, External_Name => "var1_name");
17916 pragma Export (Var2, C, Link_Name => "var2_link_name");
17923 In this case, the link name for @var{Var1} is whatever link name the
17924 C compiler would assign for the C function @var{var1_name}. This typically
17925 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17926 system conventions, but other possibilities exist. The link name for
17927 @var{Var2} is @var{var2_link_name}, and this is not operating system
17931 One exception occurs for library level procedures. A potential ambiguity
17932 arises between the required name @code{_main} for the C main program,
17933 and the name we would otherwise assign to an Ada library level procedure
17934 called @code{Main} (which might well not be the main program).
17936 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17937 names. So if we have a library level procedure such as
17939 @smallexample @c ada
17942 procedure Hello (S : String);
17948 the external name of this procedure will be @var{_ada_hello}.
17951 @node Converting Ada Files to html with gnathtml
17952 @section Converting Ada Files to HTML with @code{gnathtml}
17955 This @code{Perl} script allows Ada source files to be browsed using
17956 standard Web browsers. For installation procedure, see the section
17957 @xref{Installing gnathtml}.
17959 Ada reserved keywords are highlighted in a bold font and Ada comments in
17960 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17961 switch to suppress the generation of cross-referencing information, user
17962 defined variables and types will appear in a different color; you will
17963 be able to click on any identifier and go to its declaration.
17965 The command line is as follow:
17967 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
17968 @c Expanding @ovar macro inline (explanation in macro def comments)
17969 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
17973 You can pass it as many Ada files as you want. @code{gnathtml} will generate
17974 an html file for every ada file, and a global file called @file{index.htm}.
17975 This file is an index of every identifier defined in the files.
17977 The available ^switches^options^ are the following ones:
17981 @cindex @option{-83} (@code{gnathtml})
17982 Only the Ada 83 subset of keywords will be highlighted.
17984 @item -cc @var{color}
17985 @cindex @option{-cc} (@code{gnathtml})
17986 This option allows you to change the color used for comments. The default
17987 value is green. The color argument can be any name accepted by html.
17990 @cindex @option{-d} (@code{gnathtml})
17991 If the Ada files depend on some other files (for instance through
17992 @code{with} clauses, the latter files will also be converted to html.
17993 Only the files in the user project will be converted to html, not the files
17994 in the run-time library itself.
17997 @cindex @option{-D} (@code{gnathtml})
17998 This command is the same as @option{-d} above, but @command{gnathtml} will
17999 also look for files in the run-time library, and generate html files for them.
18001 @item -ext @var{extension}
18002 @cindex @option{-ext} (@code{gnathtml})
18003 This option allows you to change the extension of the generated HTML files.
18004 If you do not specify an extension, it will default to @file{htm}.
18007 @cindex @option{-f} (@code{gnathtml})
18008 By default, gnathtml will generate html links only for global entities
18009 ('with'ed units, global variables and types,@dots{}). If you specify
18010 @option{-f} on the command line, then links will be generated for local
18013 @item -l @var{number}
18014 @cindex @option{-l} (@code{gnathtml})
18015 If this ^switch^option^ is provided and @var{number} is not 0, then
18016 @code{gnathtml} will number the html files every @var{number} line.
18019 @cindex @option{-I} (@code{gnathtml})
18020 Specify a directory to search for library files (@file{.ALI} files) and
18021 source files. You can provide several -I switches on the command line,
18022 and the directories will be parsed in the order of the command line.
18025 @cindex @option{-o} (@code{gnathtml})
18026 Specify the output directory for html files. By default, gnathtml will
18027 saved the generated html files in a subdirectory named @file{html/}.
18029 @item -p @var{file}
18030 @cindex @option{-p} (@code{gnathtml})
18031 If you are using Emacs and the most recent Emacs Ada mode, which provides
18032 a full Integrated Development Environment for compiling, checking,
18033 running and debugging applications, you may use @file{.gpr} files
18034 to give the directories where Emacs can find sources and object files.
18036 Using this ^switch^option^, you can tell gnathtml to use these files.
18037 This allows you to get an html version of your application, even if it
18038 is spread over multiple directories.
18040 @item -sc @var{color}
18041 @cindex @option{-sc} (@code{gnathtml})
18042 This ^switch^option^ allows you to change the color used for symbol
18044 The default value is red. The color argument can be any name accepted by html.
18046 @item -t @var{file}
18047 @cindex @option{-t} (@code{gnathtml})
18048 This ^switch^option^ provides the name of a file. This file contains a list of
18049 file names to be converted, and the effect is exactly as though they had
18050 appeared explicitly on the command line. This
18051 is the recommended way to work around the command line length limit on some
18056 @node Installing gnathtml
18057 @section Installing @code{gnathtml}
18060 @code{Perl} needs to be installed on your machine to run this script.
18061 @code{Perl} is freely available for almost every architecture and
18062 Operating System via the Internet.
18064 On Unix systems, you may want to modify the first line of the script
18065 @code{gnathtml}, to explicitly tell the Operating system where Perl
18066 is. The syntax of this line is:
18068 #!full_path_name_to_perl
18072 Alternatively, you may run the script using the following command line:
18075 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18076 @c Expanding @ovar macro inline (explanation in macro def comments)
18077 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18086 The GNAT distribution provides an Ada 95 template for the HP Language
18087 Sensitive Editor (LSE), a component of DECset. In order to
18088 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18095 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18096 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18097 the collection phase with the /DEBUG qualifier.
18100 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18101 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18102 $ RUN/DEBUG <PROGRAM_NAME>
18108 @c ******************************
18109 @node Code Coverage and Profiling
18110 @chapter Code Coverage and Profiling
18111 @cindex Code Coverage
18115 This chapter describes how to use @code{gcov} - coverage testing tool - and
18116 @code{gprof} - profiler tool - on your Ada programs.
18119 * Code Coverage of Ada Programs using gcov::
18120 * Profiling an Ada Program using gprof::
18123 @node Code Coverage of Ada Programs using gcov
18124 @section Code Coverage of Ada Programs using gcov
18126 @cindex -fprofile-arcs
18127 @cindex -ftest-coverage
18129 @cindex Code Coverage
18132 @code{gcov} is a test coverage program: it analyzes the execution of a given
18133 program on selected tests, to help you determine the portions of the program
18134 that are still untested.
18136 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18137 User's Guide. You can refer to this documentation for a more complete
18140 This chapter provides a quick startup guide, and
18141 details some Gnat-specific features.
18144 * Quick startup guide::
18148 @node Quick startup guide
18149 @subsection Quick startup guide
18151 In order to perform coverage analysis of a program using @code{gcov}, 3
18156 Code instrumentation during the compilation process
18158 Execution of the instrumented program
18160 Execution of the @code{gcov} tool to generate the result.
18163 The code instrumentation needed by gcov is created at the object level:
18164 The source code is not modified in any way, because the instrumentation code is
18165 inserted by gcc during the compilation process. To compile your code with code
18166 coverage activated, you need to recompile your whole project using the
18168 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18169 @code{-fprofile-arcs}.
18172 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18173 -largs -fprofile-arcs
18176 This compilation process will create @file{.gcno} files together with
18177 the usual object files.
18179 Once the program is compiled with coverage instrumentation, you can
18180 run it as many times as needed - on portions of a test suite for
18181 example. The first execution will produce @file{.gcda} files at the
18182 same location as the @file{.gcno} files. The following executions
18183 will update those files, so that a cumulative result of the covered
18184 portions of the program is generated.
18186 Finally, you need to call the @code{gcov} tool. The different options of
18187 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18189 This will create annotated source files with a @file{.gcov} extension:
18190 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18192 @node Gnat specifics
18193 @subsection Gnat specifics
18195 Because Ada semantics, portions of the source code may be shared among
18196 several object files. This is the case for example when generics are
18197 involved, when inlining is active or when declarations generate initialisation
18198 calls. In order to take
18199 into account this shared code, you need to call @code{gcov} on all
18200 source files of the tested program at once.
18202 The list of source files might exceed the system's maximum command line
18203 length. In order to bypass this limitation, a new mechanism has been
18204 implemented in @code{gcov}: you can now list all your project's files into a
18205 text file, and provide this file to gcov as a parameter, preceded by a @@
18206 (e.g. @samp{gcov @@mysrclist.txt}).
18208 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18209 not supported as there can be unresolved symbols during the final link.
18211 @node Profiling an Ada Program using gprof
18212 @section Profiling an Ada Program using gprof
18218 This section is not meant to be an exhaustive documentation of @code{gprof}.
18219 Full documentation for it can be found in the GNU Profiler User's Guide
18220 documentation that is part of this GNAT distribution.
18222 Profiling a program helps determine the parts of a program that are executed
18223 most often, and are therefore the most time-consuming.
18225 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18226 better handle Ada programs and multitasking.
18227 It is currently supported on the following platforms
18232 solaris sparc/sparc64/x86
18238 In order to profile a program using @code{gprof}, 3 steps are needed:
18242 Code instrumentation, requiring a full recompilation of the project with the
18245 Execution of the program under the analysis conditions, i.e. with the desired
18248 Analysis of the results using the @code{gprof} tool.
18252 The following sections detail the different steps, and indicate how
18253 to interpret the results:
18255 * Compilation for profiling::
18256 * Program execution::
18258 * Interpretation of profiling results::
18261 @node Compilation for profiling
18262 @subsection Compilation for profiling
18266 In order to profile a program the first step is to tell the compiler
18267 to generate the necessary profiling information. The compiler switch to be used
18268 is @code{-pg}, which must be added to other compilation switches. This
18269 switch needs to be specified both during compilation and link stages, and can
18270 be specified once when using gnatmake:
18273 gnatmake -f -pg -P my_project
18277 Note that only the objects that were compiled with the @samp{-pg} switch will
18278 be profiled; if you need to profile your whole project, use the @samp{-f}
18279 gnatmake switch to force full recompilation.
18281 @node Program execution
18282 @subsection Program execution
18285 Once the program has been compiled for profiling, you can run it as usual.
18287 The only constraint imposed by profiling is that the program must terminate
18288 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18291 Once the program completes execution, a data file called @file{gmon.out} is
18292 generated in the directory where the program was launched from. If this file
18293 already exists, it will be overwritten.
18295 @node Running gprof
18296 @subsection Running gprof
18299 The @code{gprof} tool is called as follow:
18302 gprof my_prog gmon.out
18313 The complete form of the gprof command line is the following:
18316 gprof [^switches^options^] [executable [data-file]]
18320 @code{gprof} supports numerous ^switch^options^. The order of these
18321 ^switch^options^ does not matter. The full list of options can be found in
18322 the GNU Profiler User's Guide documentation that comes with this documentation.
18324 The following is the subset of those switches that is most relevant:
18328 @item --demangle[=@var{style}]
18329 @itemx --no-demangle
18330 @cindex @option{--demangle} (@code{gprof})
18331 These options control whether symbol names should be demangled when
18332 printing output. The default is to demangle C++ symbols. The
18333 @code{--no-demangle} option may be used to turn off demangling. Different
18334 compilers have different mangling styles. The optional demangling style
18335 argument can be used to choose an appropriate demangling style for your
18336 compiler, in particular Ada symbols generated by GNAT can be demangled using
18337 @code{--demangle=gnat}.
18339 @item -e @var{function_name}
18340 @cindex @option{-e} (@code{gprof})
18341 The @samp{-e @var{function}} option tells @code{gprof} not to print
18342 information about the function @var{function_name} (and its
18343 children@dots{}) in the call graph. The function will still be listed
18344 as a child of any functions that call it, but its index number will be
18345 shown as @samp{[not printed]}. More than one @samp{-e} option may be
18346 given; only one @var{function_name} may be indicated with each @samp{-e}
18349 @item -E @var{function_name}
18350 @cindex @option{-E} (@code{gprof})
18351 The @code{-E @var{function}} option works like the @code{-e} option, but
18352 execution time spent in the function (and children who were not called from
18353 anywhere else), will not be used to compute the percentages-of-time for
18354 the call graph. More than one @samp{-E} option may be given; only one
18355 @var{function_name} may be indicated with each @samp{-E} option.
18357 @item -f @var{function_name}
18358 @cindex @option{-f} (@code{gprof})
18359 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18360 call graph to the function @var{function_name} and its children (and
18361 their children@dots{}). More than one @samp{-f} option may be given;
18362 only one @var{function_name} may be indicated with each @samp{-f}
18365 @item -F @var{function_name}
18366 @cindex @option{-F} (@code{gprof})
18367 The @samp{-F @var{function}} option works like the @code{-f} option, but
18368 only time spent in the function and its children (and their
18369 children@dots{}) will be used to determine total-time and
18370 percentages-of-time for the call graph. More than one @samp{-F} option
18371 may be given; only one @var{function_name} may be indicated with each
18372 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
18376 @node Interpretation of profiling results
18377 @subsection Interpretation of profiling results
18381 The results of the profiling analysis are represented by two arrays: the
18382 'flat profile' and the 'call graph'. Full documentation of those outputs
18383 can be found in the GNU Profiler User's Guide.
18385 The flat profile shows the time spent in each function of the program, and how
18386 many time it has been called. This allows you to locate easily the most
18387 time-consuming functions.
18389 The call graph shows, for each subprogram, the subprograms that call it,
18390 and the subprograms that it calls. It also provides an estimate of the time
18391 spent in each of those callers/called subprograms.
18394 @c ******************************
18395 @node Running and Debugging Ada Programs
18396 @chapter Running and Debugging Ada Programs
18400 This chapter discusses how to debug Ada programs.
18402 It applies to GNAT on the Alpha OpenVMS platform;
18403 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18404 since HP has implemented Ada support in the OpenVMS debugger on I64.
18407 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18411 The illegality may be a violation of the static semantics of Ada. In
18412 that case GNAT diagnoses the constructs in the program that are illegal.
18413 It is then a straightforward matter for the user to modify those parts of
18417 The illegality may be a violation of the dynamic semantics of Ada. In
18418 that case the program compiles and executes, but may generate incorrect
18419 results, or may terminate abnormally with some exception.
18422 When presented with a program that contains convoluted errors, GNAT
18423 itself may terminate abnormally without providing full diagnostics on
18424 the incorrect user program.
18428 * The GNAT Debugger GDB::
18430 * Introduction to GDB Commands::
18431 * Using Ada Expressions::
18432 * Calling User-Defined Subprograms::
18433 * Using the Next Command in a Function::
18436 * Debugging Generic Units::
18437 * Remote Debugging using gdbserver::
18438 * GNAT Abnormal Termination or Failure to Terminate::
18439 * Naming Conventions for GNAT Source Files::
18440 * Getting Internal Debugging Information::
18441 * Stack Traceback::
18447 @node The GNAT Debugger GDB
18448 @section The GNAT Debugger GDB
18451 @code{GDB} is a general purpose, platform-independent debugger that
18452 can be used to debug mixed-language programs compiled with @command{gcc},
18453 and in particular is capable of debugging Ada programs compiled with
18454 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18455 complex Ada data structures.
18457 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18459 located in the GNU:[DOCS] directory,
18461 for full details on the usage of @code{GDB}, including a section on
18462 its usage on programs. This manual should be consulted for full
18463 details. The section that follows is a brief introduction to the
18464 philosophy and use of @code{GDB}.
18466 When GNAT programs are compiled, the compiler optionally writes debugging
18467 information into the generated object file, including information on
18468 line numbers, and on declared types and variables. This information is
18469 separate from the generated code. It makes the object files considerably
18470 larger, but it does not add to the size of the actual executable that
18471 will be loaded into memory, and has no impact on run-time performance. The
18472 generation of debug information is triggered by the use of the
18473 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18474 used to carry out the compilations. It is important to emphasize that
18475 the use of these options does not change the generated code.
18477 The debugging information is written in standard system formats that
18478 are used by many tools, including debuggers and profilers. The format
18479 of the information is typically designed to describe C types and
18480 semantics, but GNAT implements a translation scheme which allows full
18481 details about Ada types and variables to be encoded into these
18482 standard C formats. Details of this encoding scheme may be found in
18483 the file exp_dbug.ads in the GNAT source distribution. However, the
18484 details of this encoding are, in general, of no interest to a user,
18485 since @code{GDB} automatically performs the necessary decoding.
18487 When a program is bound and linked, the debugging information is
18488 collected from the object files, and stored in the executable image of
18489 the program. Again, this process significantly increases the size of
18490 the generated executable file, but it does not increase the size of
18491 the executable program itself. Furthermore, if this program is run in
18492 the normal manner, it runs exactly as if the debug information were
18493 not present, and takes no more actual memory.
18495 However, if the program is run under control of @code{GDB}, the
18496 debugger is activated. The image of the program is loaded, at which
18497 point it is ready to run. If a run command is given, then the program
18498 will run exactly as it would have if @code{GDB} were not present. This
18499 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
18500 entirely non-intrusive until a breakpoint is encountered. If no
18501 breakpoint is ever hit, the program will run exactly as it would if no
18502 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18503 the debugging information and can respond to user commands to inspect
18504 variables, and more generally to report on the state of execution.
18508 @section Running GDB
18511 This section describes how to initiate the debugger.
18512 @c The above sentence is really just filler, but it was otherwise
18513 @c clumsy to get the first paragraph nonindented given the conditional
18514 @c nature of the description
18517 The debugger can be launched from a @code{GPS} menu or
18518 directly from the command line. The description below covers the latter use.
18519 All the commands shown can be used in the @code{GPS} debug console window,
18520 but there are usually more GUI-based ways to achieve the same effect.
18523 The command to run @code{GDB} is
18526 $ ^gdb program^GDB PROGRAM^
18530 where @code{^program^PROGRAM^} is the name of the executable file. This
18531 activates the debugger and results in a prompt for debugger commands.
18532 The simplest command is simply @code{run}, which causes the program to run
18533 exactly as if the debugger were not present. The following section
18534 describes some of the additional commands that can be given to @code{GDB}.
18536 @c *******************************
18537 @node Introduction to GDB Commands
18538 @section Introduction to GDB Commands
18541 @code{GDB} contains a large repertoire of commands. @xref{Top,,
18542 Debugging with GDB, gdb, Debugging with GDB},
18544 located in the GNU:[DOCS] directory,
18546 for extensive documentation on the use
18547 of these commands, together with examples of their use. Furthermore,
18548 the command @command{help} invoked from within GDB activates a simple help
18549 facility which summarizes the available commands and their options.
18550 In this section we summarize a few of the most commonly
18551 used commands to give an idea of what @code{GDB} is about. You should create
18552 a simple program with debugging information and experiment with the use of
18553 these @code{GDB} commands on the program as you read through the
18557 @item set args @var{arguments}
18558 The @var{arguments} list above is a list of arguments to be passed to
18559 the program on a subsequent run command, just as though the arguments
18560 had been entered on a normal invocation of the program. The @code{set args}
18561 command is not needed if the program does not require arguments.
18564 The @code{run} command causes execution of the program to start from
18565 the beginning. If the program is already running, that is to say if
18566 you are currently positioned at a breakpoint, then a prompt will ask
18567 for confirmation that you want to abandon the current execution and
18570 @item breakpoint @var{location}
18571 The breakpoint command sets a breakpoint, that is to say a point at which
18572 execution will halt and @code{GDB} will await further
18573 commands. @var{location} is
18574 either a line number within a file, given in the format @code{file:linenumber},
18575 or it is the name of a subprogram. If you request that a breakpoint be set on
18576 a subprogram that is overloaded, a prompt will ask you to specify on which of
18577 those subprograms you want to breakpoint. You can also
18578 specify that all of them should be breakpointed. If the program is run
18579 and execution encounters the breakpoint, then the program
18580 stops and @code{GDB} signals that the breakpoint was encountered by
18581 printing the line of code before which the program is halted.
18583 @item catch exception @var{name}
18584 This command causes the program execution to stop whenever exception
18585 @var{name} is raised. If @var{name} is omitted, then the execution is
18586 suspended when any exception is raised.
18588 @item print @var{expression}
18589 This will print the value of the given expression. Most simple
18590 Ada expression formats are properly handled by @code{GDB}, so the expression
18591 can contain function calls, variables, operators, and attribute references.
18594 Continues execution following a breakpoint, until the next breakpoint or the
18595 termination of the program.
18598 Executes a single line after a breakpoint. If the next statement
18599 is a subprogram call, execution continues into (the first statement of)
18600 the called subprogram.
18603 Executes a single line. If this line is a subprogram call, executes and
18604 returns from the call.
18607 Lists a few lines around the current source location. In practice, it
18608 is usually more convenient to have a separate edit window open with the
18609 relevant source file displayed. Successive applications of this command
18610 print subsequent lines. The command can be given an argument which is a
18611 line number, in which case it displays a few lines around the specified one.
18614 Displays a backtrace of the call chain. This command is typically
18615 used after a breakpoint has occurred, to examine the sequence of calls that
18616 leads to the current breakpoint. The display includes one line for each
18617 activation record (frame) corresponding to an active subprogram.
18620 At a breakpoint, @code{GDB} can display the values of variables local
18621 to the current frame. The command @code{up} can be used to
18622 examine the contents of other active frames, by moving the focus up
18623 the stack, that is to say from callee to caller, one frame at a time.
18626 Moves the focus of @code{GDB} down from the frame currently being
18627 examined to the frame of its callee (the reverse of the previous command),
18629 @item frame @var{n}
18630 Inspect the frame with the given number. The value 0 denotes the frame
18631 of the current breakpoint, that is to say the top of the call stack.
18636 The above list is a very short introduction to the commands that
18637 @code{GDB} provides. Important additional capabilities, including conditional
18638 breakpoints, the ability to execute command sequences on a breakpoint,
18639 the ability to debug at the machine instruction level and many other
18640 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
18641 Debugging with GDB}. Note that most commands can be abbreviated
18642 (for example, c for continue, bt for backtrace).
18644 @node Using Ada Expressions
18645 @section Using Ada Expressions
18646 @cindex Ada expressions
18649 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18650 extensions. The philosophy behind the design of this subset is
18654 That @code{GDB} should provide basic literals and access to operations for
18655 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18656 leaving more sophisticated computations to subprograms written into the
18657 program (which therefore may be called from @code{GDB}).
18660 That type safety and strict adherence to Ada language restrictions
18661 are not particularly important to the @code{GDB} user.
18664 That brevity is important to the @code{GDB} user.
18668 Thus, for brevity, the debugger acts as if there were
18669 implicit @code{with} and @code{use} clauses in effect for all user-written
18670 packages, thus making it unnecessary to fully qualify most names with
18671 their packages, regardless of context. Where this causes ambiguity,
18672 @code{GDB} asks the user's intent.
18674 For details on the supported Ada syntax, see @ref{Top,, Debugging with
18675 GDB, gdb, Debugging with GDB}.
18677 @node Calling User-Defined Subprograms
18678 @section Calling User-Defined Subprograms
18681 An important capability of @code{GDB} is the ability to call user-defined
18682 subprograms while debugging. This is achieved simply by entering
18683 a subprogram call statement in the form:
18686 call subprogram-name (parameters)
18690 The keyword @code{call} can be omitted in the normal case where the
18691 @code{subprogram-name} does not coincide with any of the predefined
18692 @code{GDB} commands.
18694 The effect is to invoke the given subprogram, passing it the
18695 list of parameters that is supplied. The parameters can be expressions and
18696 can include variables from the program being debugged. The
18697 subprogram must be defined
18698 at the library level within your program, and @code{GDB} will call the
18699 subprogram within the environment of your program execution (which
18700 means that the subprogram is free to access or even modify variables
18701 within your program).
18703 The most important use of this facility is in allowing the inclusion of
18704 debugging routines that are tailored to particular data structures
18705 in your program. Such debugging routines can be written to provide a suitably
18706 high-level description of an abstract type, rather than a low-level dump
18707 of its physical layout. After all, the standard
18708 @code{GDB print} command only knows the physical layout of your
18709 types, not their abstract meaning. Debugging routines can provide information
18710 at the desired semantic level and are thus enormously useful.
18712 For example, when debugging GNAT itself, it is crucial to have access to
18713 the contents of the tree nodes used to represent the program internally.
18714 But tree nodes are represented simply by an integer value (which in turn
18715 is an index into a table of nodes).
18716 Using the @code{print} command on a tree node would simply print this integer
18717 value, which is not very useful. But the PN routine (defined in file
18718 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18719 a useful high level representation of the tree node, which includes the
18720 syntactic category of the node, its position in the source, the integers
18721 that denote descendant nodes and parent node, as well as varied
18722 semantic information. To study this example in more detail, you might want to
18723 look at the body of the PN procedure in the stated file.
18725 @node Using the Next Command in a Function
18726 @section Using the Next Command in a Function
18729 When you use the @code{next} command in a function, the current source
18730 location will advance to the next statement as usual. A special case
18731 arises in the case of a @code{return} statement.
18733 Part of the code for a return statement is the ``epilog'' of the function.
18734 This is the code that returns to the caller. There is only one copy of
18735 this epilog code, and it is typically associated with the last return
18736 statement in the function if there is more than one return. In some
18737 implementations, this epilog is associated with the first statement
18740 The result is that if you use the @code{next} command from a return
18741 statement that is not the last return statement of the function you
18742 may see a strange apparent jump to the last return statement or to
18743 the start of the function. You should simply ignore this odd jump.
18744 The value returned is always that from the first return statement
18745 that was stepped through.
18747 @node Ada Exceptions
18748 @section Stopping when Ada Exceptions are Raised
18752 You can set catchpoints that stop the program execution when your program
18753 raises selected exceptions.
18756 @item catch exception
18757 Set a catchpoint that stops execution whenever (any task in the) program
18758 raises any exception.
18760 @item catch exception @var{name}
18761 Set a catchpoint that stops execution whenever (any task in the) program
18762 raises the exception @var{name}.
18764 @item catch exception unhandled
18765 Set a catchpoint that stops executing whenever (any task in the) program
18766 raises an exception for which there is no handler.
18768 @item info exceptions
18769 @itemx info exceptions @var{regexp}
18770 The @code{info exceptions} command permits the user to examine all defined
18771 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18772 argument, prints out only those exceptions whose name matches @var{regexp}.
18780 @code{GDB} allows the following task-related commands:
18784 This command shows a list of current Ada tasks, as in the following example:
18791 ID TID P-ID Thread Pri State Name
18792 1 8088000 0 807e000 15 Child Activation Wait main_task
18793 2 80a4000 1 80ae000 15 Accept/Select Wait b
18794 3 809a800 1 80a4800 15 Child Activation Wait a
18795 * 4 80ae800 3 80b8000 15 Running c
18799 In this listing, the asterisk before the first task indicates it to be the
18800 currently running task. The first column lists the task ID that is used
18801 to refer to tasks in the following commands.
18803 @item break @var{linespec} task @var{taskid}
18804 @itemx break @var{linespec} task @var{taskid} if @dots{}
18805 @cindex Breakpoints and tasks
18806 These commands are like the @code{break @dots{} thread @dots{}}.
18807 @var{linespec} specifies source lines.
18809 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18810 to specify that you only want @code{GDB} to stop the program when a
18811 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18812 numeric task identifiers assigned by @code{GDB}, shown in the first
18813 column of the @samp{info tasks} display.
18815 If you do not specify @samp{task @var{taskid}} when you set a
18816 breakpoint, the breakpoint applies to @emph{all} tasks of your
18819 You can use the @code{task} qualifier on conditional breakpoints as
18820 well; in this case, place @samp{task @var{taskid}} before the
18821 breakpoint condition (before the @code{if}).
18823 @item task @var{taskno}
18824 @cindex Task switching
18826 This command allows to switch to the task referred by @var{taskno}. In
18827 particular, This allows to browse the backtrace of the specified
18828 task. It is advised to switch back to the original task before
18829 continuing execution otherwise the scheduling of the program may be
18834 For more detailed information on the tasking support,
18835 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
18837 @node Debugging Generic Units
18838 @section Debugging Generic Units
18839 @cindex Debugging Generic Units
18843 GNAT always uses code expansion for generic instantiation. This means that
18844 each time an instantiation occurs, a complete copy of the original code is
18845 made, with appropriate substitutions of formals by actuals.
18847 It is not possible to refer to the original generic entities in
18848 @code{GDB}, but it is always possible to debug a particular instance of
18849 a generic, by using the appropriate expanded names. For example, if we have
18851 @smallexample @c ada
18856 generic package k is
18857 procedure kp (v1 : in out integer);
18861 procedure kp (v1 : in out integer) is
18867 package k1 is new k;
18868 package k2 is new k;
18870 var : integer := 1;
18883 Then to break on a call to procedure kp in the k2 instance, simply
18887 (gdb) break g.k2.kp
18891 When the breakpoint occurs, you can step through the code of the
18892 instance in the normal manner and examine the values of local variables, as for
18895 @node Remote Debugging using gdbserver
18896 @section Remote Debugging using gdbserver
18897 @cindex Remote Debugging using gdbserver
18900 On platforms where gdbserver is supported, it is possible to use this tool
18901 to debug your application remotely. This can be useful in situations
18902 where the program needs to be run on a target host that is different
18903 from the host used for development, particularly when the target has
18904 a limited amount of resources (either CPU and/or memory).
18906 To do so, start your program using gdbserver on the target machine.
18907 gdbserver then automatically suspends the execution of your program
18908 at its entry point, waiting for a debugger to connect to it. The
18909 following commands starts an application and tells gdbserver to
18910 wait for a connection with the debugger on localhost port 4444.
18913 $ gdbserver localhost:4444 program
18914 Process program created; pid = 5685
18915 Listening on port 4444
18918 Once gdbserver has started listening, we can tell the debugger to establish
18919 a connection with this gdbserver, and then start the same debugging session
18920 as if the program was being debugged on the same host, directly under
18921 the control of GDB.
18925 (gdb) target remote targethost:4444
18926 Remote debugging using targethost:4444
18927 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18929 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18933 Breakpoint 1, foo () at foo.adb:4
18937 It is also possible to use gdbserver to attach to an already running
18938 program, in which case the execution of that program is simply suspended
18939 until the connection between the debugger and gdbserver is established.
18941 For more information on how to use gdbserver, @ref{Top, Server, Using
18942 the gdbserver Program, gdb, Debugging with GDB}. GNAT Pro provides support
18943 for gdbserver on x86-linux, x86-windows and x86_64-linux.
18945 @node GNAT Abnormal Termination or Failure to Terminate
18946 @section GNAT Abnormal Termination or Failure to Terminate
18947 @cindex GNAT Abnormal Termination or Failure to Terminate
18950 When presented with programs that contain serious errors in syntax
18952 GNAT may on rare occasions experience problems in operation, such
18954 segmentation fault or illegal memory access, raising an internal
18955 exception, terminating abnormally, or failing to terminate at all.
18956 In such cases, you can activate
18957 various features of GNAT that can help you pinpoint the construct in your
18958 program that is the likely source of the problem.
18960 The following strategies are presented in increasing order of
18961 difficulty, corresponding to your experience in using GNAT and your
18962 familiarity with compiler internals.
18966 Run @command{gcc} with the @option{-gnatf}. This first
18967 switch causes all errors on a given line to be reported. In its absence,
18968 only the first error on a line is displayed.
18970 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18971 are encountered, rather than after compilation is terminated. If GNAT
18972 terminates prematurely or goes into an infinite loop, the last error
18973 message displayed may help to pinpoint the culprit.
18976 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
18977 mode, @command{gcc} produces ongoing information about the progress of the
18978 compilation and provides the name of each procedure as code is
18979 generated. This switch allows you to find which Ada procedure was being
18980 compiled when it encountered a code generation problem.
18983 @cindex @option{-gnatdc} switch
18984 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18985 switch that does for the front-end what @option{^-v^VERBOSE^} does
18986 for the back end. The system prints the name of each unit,
18987 either a compilation unit or nested unit, as it is being analyzed.
18989 Finally, you can start
18990 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18991 front-end of GNAT, and can be run independently (normally it is just
18992 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
18993 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18994 @code{where} command is the first line of attack; the variable
18995 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18996 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
18997 which the execution stopped, and @code{input_file name} indicates the name of
19001 @node Naming Conventions for GNAT Source Files
19002 @section Naming Conventions for GNAT Source Files
19005 In order to examine the workings of the GNAT system, the following
19006 brief description of its organization may be helpful:
19010 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19013 All files prefixed with @file{^par^PAR^} are components of the parser. The
19014 numbers correspond to chapters of the Ada Reference Manual. For example,
19015 parsing of select statements can be found in @file{par-ch9.adb}.
19018 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19019 numbers correspond to chapters of the Ada standard. For example, all
19020 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19021 addition, some features of the language require sufficient special processing
19022 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19023 dynamic dispatching, etc.
19026 All files prefixed with @file{^exp^EXP^} perform normalization and
19027 expansion of the intermediate representation (abstract syntax tree, or AST).
19028 these files use the same numbering scheme as the parser and semantics files.
19029 For example, the construction of record initialization procedures is done in
19030 @file{exp_ch3.adb}.
19033 The files prefixed with @file{^bind^BIND^} implement the binder, which
19034 verifies the consistency of the compilation, determines an order of
19035 elaboration, and generates the bind file.
19038 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19039 data structures used by the front-end.
19042 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19043 the abstract syntax tree as produced by the parser.
19046 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19047 all entities, computed during semantic analysis.
19050 Library management issues are dealt with in files with prefix
19056 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19057 defined in Annex A.
19062 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19063 defined in Annex B.
19067 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19068 both language-defined children and GNAT run-time routines.
19072 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19073 general-purpose packages, fully documented in their specs. All
19074 the other @file{.c} files are modifications of common @command{gcc} files.
19077 @node Getting Internal Debugging Information
19078 @section Getting Internal Debugging Information
19081 Most compilers have internal debugging switches and modes. GNAT
19082 does also, except GNAT internal debugging switches and modes are not
19083 secret. A summary and full description of all the compiler and binder
19084 debug flags are in the file @file{debug.adb}. You must obtain the
19085 sources of the compiler to see the full detailed effects of these flags.
19087 The switches that print the source of the program (reconstructed from
19088 the internal tree) are of general interest for user programs, as are the
19090 the full internal tree, and the entity table (the symbol table
19091 information). The reconstructed source provides a readable version of the
19092 program after the front-end has completed analysis and expansion,
19093 and is useful when studying the performance of specific constructs.
19094 For example, constraint checks are indicated, complex aggregates
19095 are replaced with loops and assignments, and tasking primitives
19096 are replaced with run-time calls.
19098 @node Stack Traceback
19099 @section Stack Traceback
19101 @cindex stack traceback
19102 @cindex stack unwinding
19105 Traceback is a mechanism to display the sequence of subprogram calls that
19106 leads to a specified execution point in a program. Often (but not always)
19107 the execution point is an instruction at which an exception has been raised.
19108 This mechanism is also known as @i{stack unwinding} because it obtains
19109 its information by scanning the run-time stack and recovering the activation
19110 records of all active subprograms. Stack unwinding is one of the most
19111 important tools for program debugging.
19113 The first entry stored in traceback corresponds to the deepest calling level,
19114 that is to say the subprogram currently executing the instruction
19115 from which we want to obtain the traceback.
19117 Note that there is no runtime performance penalty when stack traceback
19118 is enabled, and no exception is raised during program execution.
19121 * Non-Symbolic Traceback::
19122 * Symbolic Traceback::
19125 @node Non-Symbolic Traceback
19126 @subsection Non-Symbolic Traceback
19127 @cindex traceback, non-symbolic
19130 Note: this feature is not supported on all platforms. See
19131 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19135 * Tracebacks From an Unhandled Exception::
19136 * Tracebacks From Exception Occurrences (non-symbolic)::
19137 * Tracebacks From Anywhere in a Program (non-symbolic)::
19140 @node Tracebacks From an Unhandled Exception
19141 @subsubsection Tracebacks From an Unhandled Exception
19144 A runtime non-symbolic traceback is a list of addresses of call instructions.
19145 To enable this feature you must use the @option{-E}
19146 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19147 of exception information. You can retrieve this information using the
19148 @code{addr2line} tool.
19150 Here is a simple example:
19152 @smallexample @c ada
19158 raise Constraint_Error;
19173 $ gnatmake stb -bargs -E
19176 Execution terminated by unhandled exception
19177 Exception name: CONSTRAINT_ERROR
19179 Call stack traceback locations:
19180 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19184 As we see the traceback lists a sequence of addresses for the unhandled
19185 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19186 guess that this exception come from procedure P1. To translate these
19187 addresses into the source lines where the calls appear, the
19188 @code{addr2line} tool, described below, is invaluable. The use of this tool
19189 requires the program to be compiled with debug information.
19192 $ gnatmake -g stb -bargs -E
19195 Execution terminated by unhandled exception
19196 Exception name: CONSTRAINT_ERROR
19198 Call stack traceback locations:
19199 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19201 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19202 0x4011f1 0x77e892a4
19204 00401373 at d:/stb/stb.adb:5
19205 0040138B at d:/stb/stb.adb:10
19206 0040139C at d:/stb/stb.adb:14
19207 00401335 at d:/stb/b~stb.adb:104
19208 004011C4 at /build/@dots{}/crt1.c:200
19209 004011F1 at /build/@dots{}/crt1.c:222
19210 77E892A4 in ?? at ??:0
19214 The @code{addr2line} tool has several other useful options:
19218 to get the function name corresponding to any location
19220 @item --demangle=gnat
19221 to use the gnat decoding mode for the function names. Note that
19222 for binutils version 2.9.x the option is simply @option{--demangle}.
19226 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19227 0x40139c 0x401335 0x4011c4 0x4011f1
19229 00401373 in stb.p1 at d:/stb/stb.adb:5
19230 0040138B in stb.p2 at d:/stb/stb.adb:10
19231 0040139C in stb at d:/stb/stb.adb:14
19232 00401335 in main at d:/stb/b~stb.adb:104
19233 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19234 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19238 From this traceback we can see that the exception was raised in
19239 @file{stb.adb} at line 5, which was reached from a procedure call in
19240 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19241 which contains the call to the main program.
19242 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19243 and the output will vary from platform to platform.
19245 It is also possible to use @code{GDB} with these traceback addresses to debug
19246 the program. For example, we can break at a given code location, as reported
19247 in the stack traceback:
19253 Furthermore, this feature is not implemented inside Windows DLL. Only
19254 the non-symbolic traceback is reported in this case.
19257 (gdb) break *0x401373
19258 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19262 It is important to note that the stack traceback addresses
19263 do not change when debug information is included. This is particularly useful
19264 because it makes it possible to release software without debug information (to
19265 minimize object size), get a field report that includes a stack traceback
19266 whenever an internal bug occurs, and then be able to retrieve the sequence
19267 of calls with the same program compiled with debug information.
19269 @node Tracebacks From Exception Occurrences (non-symbolic)
19270 @subsubsection Tracebacks From Exception Occurrences
19273 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19274 The stack traceback is attached to the exception information string, and can
19275 be retrieved in an exception handler within the Ada program, by means of the
19276 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19278 @smallexample @c ada
19280 with Ada.Exceptions;
19285 use Ada.Exceptions;
19293 Text_IO.Put_Line (Exception_Information (E));
19307 This program will output:
19312 Exception name: CONSTRAINT_ERROR
19313 Message: stb.adb:12
19314 Call stack traceback locations:
19315 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19318 @node Tracebacks From Anywhere in a Program (non-symbolic)
19319 @subsubsection Tracebacks From Anywhere in a Program
19322 It is also possible to retrieve a stack traceback from anywhere in a
19323 program. For this you need to
19324 use the @code{GNAT.Traceback} API. This package includes a procedure called
19325 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19326 display procedures described below. It is not necessary to use the
19327 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19328 is invoked explicitly.
19331 In the following example we compute a traceback at a specific location in
19332 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19333 convert addresses to strings:
19335 @smallexample @c ada
19337 with GNAT.Traceback;
19338 with GNAT.Debug_Utilities;
19344 use GNAT.Traceback;
19347 TB : Tracebacks_Array (1 .. 10);
19348 -- We are asking for a maximum of 10 stack frames.
19350 -- Len will receive the actual number of stack frames returned.
19352 Call_Chain (TB, Len);
19354 Text_IO.Put ("In STB.P1 : ");
19356 for K in 1 .. Len loop
19357 Text_IO.Put (Debug_Utilities.Image (TB (K)));
19378 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19379 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19383 You can then get further information by invoking the @code{addr2line}
19384 tool as described earlier (note that the hexadecimal addresses
19385 need to be specified in C format, with a leading ``0x'').
19387 @node Symbolic Traceback
19388 @subsection Symbolic Traceback
19389 @cindex traceback, symbolic
19392 A symbolic traceback is a stack traceback in which procedure names are
19393 associated with each code location.
19396 Note that this feature is not supported on all platforms. See
19397 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19398 list of currently supported platforms.
19401 Note that the symbolic traceback requires that the program be compiled
19402 with debug information. If it is not compiled with debug information
19403 only the non-symbolic information will be valid.
19406 * Tracebacks From Exception Occurrences (symbolic)::
19407 * Tracebacks From Anywhere in a Program (symbolic)::
19410 @node Tracebacks From Exception Occurrences (symbolic)
19411 @subsubsection Tracebacks From Exception Occurrences
19413 @smallexample @c ada
19415 with GNAT.Traceback.Symbolic;
19421 raise Constraint_Error;
19438 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19443 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19446 0040149F in stb.p1 at stb.adb:8
19447 004014B7 in stb.p2 at stb.adb:13
19448 004014CF in stb.p3 at stb.adb:18
19449 004015DD in ada.stb at stb.adb:22
19450 00401461 in main at b~stb.adb:168
19451 004011C4 in __mingw_CRTStartup at crt1.c:200
19452 004011F1 in mainCRTStartup at crt1.c:222
19453 77E892A4 in ?? at ??:0
19457 In the above example the ``.\'' syntax in the @command{gnatmake} command
19458 is currently required by @command{addr2line} for files that are in
19459 the current working directory.
19460 Moreover, the exact sequence of linker options may vary from platform
19462 The above @option{-largs} section is for Windows platforms. By contrast,
19463 under Unix there is no need for the @option{-largs} section.
19464 Differences across platforms are due to details of linker implementation.
19466 @node Tracebacks From Anywhere in a Program (symbolic)
19467 @subsubsection Tracebacks From Anywhere in a Program
19470 It is possible to get a symbolic stack traceback
19471 from anywhere in a program, just as for non-symbolic tracebacks.
19472 The first step is to obtain a non-symbolic
19473 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19474 information. Here is an example:
19476 @smallexample @c ada
19478 with GNAT.Traceback;
19479 with GNAT.Traceback.Symbolic;
19484 use GNAT.Traceback;
19485 use GNAT.Traceback.Symbolic;
19488 TB : Tracebacks_Array (1 .. 10);
19489 -- We are asking for a maximum of 10 stack frames.
19491 -- Len will receive the actual number of stack frames returned.
19493 Call_Chain (TB, Len);
19494 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19507 @c ******************************
19509 @node Compatibility with HP Ada
19510 @chapter Compatibility with HP Ada
19511 @cindex Compatibility
19516 @cindex Compatibility between GNAT and HP Ada
19517 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19518 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19519 GNAT is highly compatible
19520 with HP Ada, and it should generally be straightforward to port code
19521 from the HP Ada environment to GNAT. However, there are a few language
19522 and implementation differences of which the user must be aware. These
19523 differences are discussed in this chapter. In
19524 addition, the operating environment and command structure for the
19525 compiler are different, and these differences are also discussed.
19527 For further details on these and other compatibility issues,
19528 see Appendix E of the HP publication
19529 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19531 Except where otherwise indicated, the description of GNAT for OpenVMS
19532 applies to both the Alpha and I64 platforms.
19534 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19535 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19537 The discussion in this chapter addresses specifically the implementation
19538 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19539 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19540 GNAT always follows the Alpha implementation.
19542 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19543 attributes are recognized, although only a subset of them can sensibly
19544 be implemented. The description of pragmas in
19545 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19546 indicates whether or not they are applicable to non-VMS systems.
19549 * Ada Language Compatibility::
19550 * Differences in the Definition of Package System::
19551 * Language-Related Features::
19552 * The Package STANDARD::
19553 * The Package SYSTEM::
19554 * Tasking and Task-Related Features::
19555 * Pragmas and Pragma-Related Features::
19556 * Library of Predefined Units::
19558 * Main Program Definition::
19559 * Implementation-Defined Attributes::
19560 * Compiler and Run-Time Interfacing::
19561 * Program Compilation and Library Management::
19563 * Implementation Limits::
19564 * Tools and Utilities::
19567 @node Ada Language Compatibility
19568 @section Ada Language Compatibility
19571 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19572 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19573 with Ada 83, and therefore Ada 83 programs will compile
19574 and run under GNAT with
19575 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
19576 provides details on specific incompatibilities.
19578 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
19579 as well as the pragma @code{ADA_83}, to force the compiler to
19580 operate in Ada 83 mode. This mode does not guarantee complete
19581 conformance to Ada 83, but in practice is sufficient to
19582 eliminate most sources of incompatibilities.
19583 In particular, it eliminates the recognition of the
19584 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
19585 in Ada 83 programs is legal, and handles the cases of packages
19586 with optional bodies, and generics that instantiate unconstrained
19587 types without the use of @code{(<>)}.
19589 @node Differences in the Definition of Package System
19590 @section Differences in the Definition of Package @code{System}
19593 An Ada compiler is allowed to add
19594 implementation-dependent declarations to package @code{System}.
19596 GNAT does not take advantage of this permission, and the version of
19597 @code{System} provided by GNAT exactly matches that defined in the Ada
19600 However, HP Ada adds an extensive set of declarations to package
19602 as fully documented in the HP Ada manuals. To minimize changes required
19603 for programs that make use of these extensions, GNAT provides the pragma
19604 @code{Extend_System} for extending the definition of package System. By using:
19605 @cindex pragma @code{Extend_System}
19606 @cindex @code{Extend_System} pragma
19608 @smallexample @c ada
19611 pragma Extend_System (Aux_DEC);
19617 the set of definitions in @code{System} is extended to include those in
19618 package @code{System.Aux_DEC}.
19619 @cindex @code{System.Aux_DEC} package
19620 @cindex @code{Aux_DEC} package (child of @code{System})
19621 These definitions are incorporated directly into package @code{System},
19622 as though they had been declared there. For a
19623 list of the declarations added, see the spec of this package,
19624 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
19625 @cindex @file{s-auxdec.ads} file
19626 The pragma @code{Extend_System} is a configuration pragma, which means that
19627 it can be placed in the file @file{gnat.adc}, so that it will automatically
19628 apply to all subsequent compilations. See @ref{Configuration Pragmas},
19629 for further details.
19631 An alternative approach that avoids the use of the non-standard
19632 @code{Extend_System} pragma is to add a context clause to the unit that
19633 references these facilities:
19635 @smallexample @c ada
19637 with System.Aux_DEC;
19638 use System.Aux_DEC;
19643 The effect is not quite semantically identical to incorporating
19644 the declarations directly into package @code{System},
19645 but most programs will not notice a difference
19646 unless they use prefix notation (e.g.@: @code{System.Integer_8})
19647 to reference the entities directly in package @code{System}.
19648 For units containing such references,
19649 the prefixes must either be removed, or the pragma @code{Extend_System}
19652 @node Language-Related Features
19653 @section Language-Related Features
19656 The following sections highlight differences in types,
19657 representations of types, operations, alignment, and
19661 * Integer Types and Representations::
19662 * Floating-Point Types and Representations::
19663 * Pragmas Float_Representation and Long_Float::
19664 * Fixed-Point Types and Representations::
19665 * Record and Array Component Alignment::
19666 * Address Clauses::
19667 * Other Representation Clauses::
19670 @node Integer Types and Representations
19671 @subsection Integer Types and Representations
19674 The set of predefined integer types is identical in HP Ada and GNAT.
19675 Furthermore the representation of these integer types is also identical,
19676 including the capability of size clauses forcing biased representation.
19679 HP Ada for OpenVMS Alpha systems has defined the
19680 following additional integer types in package @code{System}:
19697 @code{LARGEST_INTEGER}
19701 In GNAT, the first four of these types may be obtained from the
19702 standard Ada package @code{Interfaces}.
19703 Alternatively, by use of the pragma @code{Extend_System}, identical
19704 declarations can be referenced directly in package @code{System}.
19705 On both GNAT and HP Ada, the maximum integer size is 64 bits.
19707 @node Floating-Point Types and Representations
19708 @subsection Floating-Point Types and Representations
19709 @cindex Floating-Point types
19712 The set of predefined floating-point types is identical in HP Ada and GNAT.
19713 Furthermore the representation of these floating-point
19714 types is also identical. One important difference is that the default
19715 representation for HP Ada is @code{VAX_Float}, but the default representation
19718 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
19719 pragma @code{Float_Representation} as described in the HP Ada
19721 For example, the declarations:
19723 @smallexample @c ada
19725 type F_Float is digits 6;
19726 pragma Float_Representation (VAX_Float, F_Float);
19731 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
19733 This set of declarations actually appears in @code{System.Aux_DEC},
19735 the full set of additional floating-point declarations provided in
19736 the HP Ada version of package @code{System}.
19737 This and similar declarations may be accessed in a user program
19738 by using pragma @code{Extend_System}. The use of this
19739 pragma, and the related pragma @code{Long_Float} is described in further
19740 detail in the following section.
19742 @node Pragmas Float_Representation and Long_Float
19743 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
19746 HP Ada provides the pragma @code{Float_Representation}, which
19747 acts as a program library switch to allow control over
19748 the internal representation chosen for the predefined
19749 floating-point types declared in the package @code{Standard}.
19750 The format of this pragma is as follows:
19752 @smallexample @c ada
19754 pragma Float_Representation(VAX_Float | IEEE_Float);
19759 This pragma controls the representation of floating-point
19764 @code{VAX_Float} specifies that floating-point
19765 types are represented by default with the VAX system hardware types
19766 @code{F-floating}, @code{D-floating}, @code{G-floating}.
19767 Note that the @code{H-floating}
19768 type was available only on VAX systems, and is not available
19769 in either HP Ada or GNAT.
19772 @code{IEEE_Float} specifies that floating-point
19773 types are represented by default with the IEEE single and
19774 double floating-point types.
19778 GNAT provides an identical implementation of the pragma
19779 @code{Float_Representation}, except that it functions as a
19780 configuration pragma. Note that the
19781 notion of configuration pragma corresponds closely to the
19782 HP Ada notion of a program library switch.
19784 When no pragma is used in GNAT, the default is @code{IEEE_Float},
19786 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
19787 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
19788 advisable to change the format of numbers passed to standard library
19789 routines, and if necessary explicit type conversions may be needed.
19791 The use of @code{IEEE_Float} is recommended in GNAT since it is more
19792 efficient, and (given that it conforms to an international standard)
19793 potentially more portable.
19794 The situation in which @code{VAX_Float} may be useful is in interfacing
19795 to existing code and data that expect the use of @code{VAX_Float}.
19796 In such a situation use the predefined @code{VAX_Float}
19797 types in package @code{System}, as extended by
19798 @code{Extend_System}. For example, use @code{System.F_Float}
19799 to specify the 32-bit @code{F-Float} format.
19802 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
19803 to allow control over the internal representation chosen
19804 for the predefined type @code{Long_Float} and for floating-point
19805 type declarations with digits specified in the range 7 .. 15.
19806 The format of this pragma is as follows:
19808 @smallexample @c ada
19810 pragma Long_Float (D_FLOAT | G_FLOAT);
19814 @node Fixed-Point Types and Representations
19815 @subsection Fixed-Point Types and Representations
19818 On HP Ada for OpenVMS Alpha systems, rounding is
19819 away from zero for both positive and negative numbers.
19820 Therefore, @code{+0.5} rounds to @code{1},
19821 and @code{-0.5} rounds to @code{-1}.
19823 On GNAT the results of operations
19824 on fixed-point types are in accordance with the Ada
19825 rules. In particular, results of operations on decimal
19826 fixed-point types are truncated.
19828 @node Record and Array Component Alignment
19829 @subsection Record and Array Component Alignment
19832 On HP Ada for OpenVMS Alpha, all non-composite components
19833 are aligned on natural boundaries. For example, 1-byte
19834 components are aligned on byte boundaries, 2-byte
19835 components on 2-byte boundaries, 4-byte components on 4-byte
19836 byte boundaries, and so on. The OpenVMS Alpha hardware
19837 runs more efficiently with naturally aligned data.
19839 On GNAT, alignment rules are compatible
19840 with HP Ada for OpenVMS Alpha.
19842 @node Address Clauses
19843 @subsection Address Clauses
19846 In HP Ada and GNAT, address clauses are supported for
19847 objects and imported subprograms.
19848 The predefined type @code{System.Address} is a private type
19849 in both compilers on Alpha OpenVMS, with the same representation
19850 (it is simply a machine pointer). Addition, subtraction, and comparison
19851 operations are available in the standard Ada package
19852 @code{System.Storage_Elements}, or in package @code{System}
19853 if it is extended to include @code{System.Aux_DEC} using a
19854 pragma @code{Extend_System} as previously described.
19856 Note that code that @code{with}'s both this extended package @code{System}
19857 and the package @code{System.Storage_Elements} should not @code{use}
19858 both packages, or ambiguities will result. In general it is better
19859 not to mix these two sets of facilities. The Ada package was
19860 designed specifically to provide the kind of features that HP Ada
19861 adds directly to package @code{System}.
19863 The type @code{System.Address} is a 64-bit integer type in GNAT for
19864 I64 OpenVMS. For more information,
19865 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19867 GNAT is compatible with HP Ada in its handling of address
19868 clauses, except for some limitations in
19869 the form of address clauses for composite objects with
19870 initialization. Such address clauses are easily replaced
19871 by the use of an explicitly-defined constant as described
19872 in the Ada Reference Manual (13.1(22)). For example, the sequence
19875 @smallexample @c ada
19877 X, Y : Integer := Init_Func;
19878 Q : String (X .. Y) := "abc";
19880 for Q'Address use Compute_Address;
19885 will be rejected by GNAT, since the address cannot be computed at the time
19886 that @code{Q} is declared. To achieve the intended effect, write instead:
19888 @smallexample @c ada
19891 X, Y : Integer := Init_Func;
19892 Q_Address : constant Address := Compute_Address;
19893 Q : String (X .. Y) := "abc";
19895 for Q'Address use Q_Address;
19901 which will be accepted by GNAT (and other Ada compilers), and is also
19902 compatible with Ada 83. A fuller description of the restrictions
19903 on address specifications is found in @ref{Top, GNAT Reference Manual,
19904 About This Guide, gnat_rm, GNAT Reference Manual}.
19906 @node Other Representation Clauses
19907 @subsection Other Representation Clauses
19910 GNAT implements in a compatible manner all the representation
19911 clauses supported by HP Ada. In addition, GNAT
19912 implements the representation clause forms that were introduced in Ada 95,
19913 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
19915 @node The Package STANDARD
19916 @section The Package @code{STANDARD}
19919 The package @code{STANDARD}, as implemented by HP Ada, is fully
19920 described in the @cite{Ada Reference Manual} and in the
19921 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
19922 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
19924 In addition, HP Ada supports the Latin-1 character set in
19925 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
19926 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
19927 the type @code{WIDE_CHARACTER}.
19929 The floating-point types supported by GNAT are those
19930 supported by HP Ada, but the defaults are different, and are controlled by
19931 pragmas. See @ref{Floating-Point Types and Representations}, for details.
19933 @node The Package SYSTEM
19934 @section The Package @code{SYSTEM}
19937 HP Ada provides a specific version of the package
19938 @code{SYSTEM} for each platform on which the language is implemented.
19939 For the complete spec of the package @code{SYSTEM}, see
19940 Appendix F of the @cite{HP Ada Language Reference Manual}.
19942 On HP Ada, the package @code{SYSTEM} includes the following conversion
19945 @item @code{TO_ADDRESS(INTEGER)}
19947 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
19949 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
19951 @item @code{TO_INTEGER(ADDRESS)}
19953 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
19955 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
19956 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
19960 By default, GNAT supplies a version of @code{SYSTEM} that matches
19961 the definition given in the @cite{Ada Reference Manual}.
19963 is a subset of the HP system definitions, which is as
19964 close as possible to the original definitions. The only difference
19965 is that the definition of @code{SYSTEM_NAME} is different:
19967 @smallexample @c ada
19969 type Name is (SYSTEM_NAME_GNAT);
19970 System_Name : constant Name := SYSTEM_NAME_GNAT;
19975 Also, GNAT adds the Ada declarations for
19976 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
19978 However, the use of the following pragma causes GNAT
19979 to extend the definition of package @code{SYSTEM} so that it
19980 encompasses the full set of HP-specific extensions,
19981 including the functions listed above:
19983 @smallexample @c ada
19985 pragma Extend_System (Aux_DEC);
19990 The pragma @code{Extend_System} is a configuration pragma that
19991 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
19992 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
19994 HP Ada does not allow the recompilation of the package
19995 @code{SYSTEM}. Instead HP Ada provides several pragmas
19996 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
19997 to modify values in the package @code{SYSTEM}.
19998 On OpenVMS Alpha systems, the pragma
19999 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20000 its single argument.
20002 GNAT does permit the recompilation of package @code{SYSTEM} using
20003 the special switch @option{-gnatg}, and this switch can be used if
20004 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20005 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20006 or @code{MEMORY_SIZE} by any other means.
20008 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20009 enumeration literal @code{SYSTEM_NAME_GNAT}.
20011 The definitions provided by the use of
20013 @smallexample @c ada
20014 pragma Extend_System (AUX_Dec);
20018 are virtually identical to those provided by the HP Ada 83 package
20019 @code{SYSTEM}. One important difference is that the name of the
20021 function for type @code{UNSIGNED_LONGWORD} is changed to
20022 @code{TO_ADDRESS_LONG}.
20023 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20024 discussion of why this change was necessary.
20027 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20029 an extension to Ada 83 not strictly compatible with the reference manual.
20030 GNAT, in order to be exactly compatible with the standard,
20031 does not provide this capability. In HP Ada 83, the
20032 point of this definition is to deal with a call like:
20034 @smallexample @c ada
20035 TO_ADDRESS (16#12777#);
20039 Normally, according to Ada 83 semantics, one would expect this to be
20040 ambiguous, since it matches both the @code{INTEGER} and
20041 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20042 However, in HP Ada 83, there is no ambiguity, since the
20043 definition using @i{universal_integer} takes precedence.
20045 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20047 not possible to be 100% compatible. Since there are many programs using
20048 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20050 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20051 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20053 @smallexample @c ada
20054 function To_Address (X : Integer) return Address;
20055 pragma Pure_Function (To_Address);
20057 function To_Address_Long (X : Unsigned_Longword) return Address;
20058 pragma Pure_Function (To_Address_Long);
20062 This means that programs using @code{TO_ADDRESS} for
20063 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20065 @node Tasking and Task-Related Features
20066 @section Tasking and Task-Related Features
20069 This section compares the treatment of tasking in GNAT
20070 and in HP Ada for OpenVMS Alpha.
20071 The GNAT description applies to both Alpha and I64 OpenVMS.
20072 For detailed information on tasking in
20073 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20074 relevant run-time reference manual.
20077 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20078 * Assigning Task IDs::
20079 * Task IDs and Delays::
20080 * Task-Related Pragmas::
20081 * Scheduling and Task Priority::
20083 * External Interrupts::
20086 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20087 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20090 On OpenVMS Alpha systems, each Ada task (except a passive
20091 task) is implemented as a single stream of execution
20092 that is created and managed by the kernel. On these
20093 systems, HP Ada tasking support is based on DECthreads,
20094 an implementation of the POSIX standard for threads.
20096 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20097 code that calls DECthreads routines can be used together.
20098 The interaction between Ada tasks and DECthreads routines
20099 can have some benefits. For example when on OpenVMS Alpha,
20100 HP Ada can call C code that is already threaded.
20102 GNAT uses the facilities of DECthreads,
20103 and Ada tasks are mapped to threads.
20105 @node Assigning Task IDs
20106 @subsection Assigning Task IDs
20109 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20110 the environment task that executes the main program. On
20111 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20112 that have been created but are not yet activated.
20114 On OpenVMS Alpha systems, task IDs are assigned at
20115 activation. On GNAT systems, task IDs are also assigned at
20116 task creation but do not have the same form or values as
20117 task ID values in HP Ada. There is no null task, and the
20118 environment task does not have a specific task ID value.
20120 @node Task IDs and Delays
20121 @subsection Task IDs and Delays
20124 On OpenVMS Alpha systems, tasking delays are implemented
20125 using Timer System Services. The Task ID is used for the
20126 identification of the timer request (the @code{REQIDT} parameter).
20127 If Timers are used in the application take care not to use
20128 @code{0} for the identification, because cancelling such a timer
20129 will cancel all timers and may lead to unpredictable results.
20131 @node Task-Related Pragmas
20132 @subsection Task-Related Pragmas
20135 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20136 specification of the size of the guard area for a task
20137 stack. (The guard area forms an area of memory that has no
20138 read or write access and thus helps in the detection of
20139 stack overflow.) On OpenVMS Alpha systems, if the pragma
20140 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20141 area is created. In the absence of a pragma @code{TASK_STORAGE},
20142 a default guard area is created.
20144 GNAT supplies the following task-related pragmas:
20147 @item @code{TASK_INFO}
20149 This pragma appears within a task definition and
20150 applies to the task in which it appears. The argument
20151 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20153 @item @code{TASK_STORAGE}
20155 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20156 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20157 @code{SUPPRESS}, and @code{VOLATILE}.
20159 @node Scheduling and Task Priority
20160 @subsection Scheduling and Task Priority
20163 HP Ada implements the Ada language requirement that
20164 when two tasks are eligible for execution and they have
20165 different priorities, the lower priority task does not
20166 execute while the higher priority task is waiting. The HP
20167 Ada Run-Time Library keeps a task running until either the
20168 task is suspended or a higher priority task becomes ready.
20170 On OpenVMS Alpha systems, the default strategy is round-
20171 robin with preemption. Tasks of equal priority take turns
20172 at the processor. A task is run for a certain period of
20173 time and then placed at the tail of the ready queue for
20174 its priority level.
20176 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20177 which can be used to enable or disable round-robin
20178 scheduling of tasks with the same priority.
20179 See the relevant HP Ada run-time reference manual for
20180 information on using the pragmas to control HP Ada task
20183 GNAT follows the scheduling rules of Annex D (Real-Time
20184 Annex) of the @cite{Ada Reference Manual}. In general, this
20185 scheduling strategy is fully compatible with HP Ada
20186 although it provides some additional constraints (as
20187 fully documented in Annex D).
20188 GNAT implements time slicing control in a manner compatible with
20189 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20190 are identical to the HP Ada 83 pragma of the same name.
20191 Note that it is not possible to mix GNAT tasking and
20192 HP Ada 83 tasking in the same program, since the two run-time
20193 libraries are not compatible.
20195 @node The Task Stack
20196 @subsection The Task Stack
20199 In HP Ada, a task stack is allocated each time a
20200 non-passive task is activated. As soon as the task is
20201 terminated, the storage for the task stack is deallocated.
20202 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20203 a default stack size is used. Also, regardless of the size
20204 specified, some additional space is allocated for task
20205 management purposes. On OpenVMS Alpha systems, at least
20206 one page is allocated.
20208 GNAT handles task stacks in a similar manner. In accordance with
20209 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20210 an alternative method for controlling the task stack size.
20211 The specification of the attribute @code{T'STORAGE_SIZE} is also
20212 supported in a manner compatible with HP Ada.
20214 @node External Interrupts
20215 @subsection External Interrupts
20218 On HP Ada, external interrupts can be associated with task entries.
20219 GNAT is compatible with HP Ada in its handling of external interrupts.
20221 @node Pragmas and Pragma-Related Features
20222 @section Pragmas and Pragma-Related Features
20225 Both HP Ada and GNAT supply all language-defined pragmas
20226 as specified by the Ada 83 standard. GNAT also supplies all
20227 language-defined pragmas introduced by Ada 95 and Ada 2005.
20228 In addition, GNAT implements the implementation-defined pragmas
20232 @item @code{AST_ENTRY}
20234 @item @code{COMMON_OBJECT}
20236 @item @code{COMPONENT_ALIGNMENT}
20238 @item @code{EXPORT_EXCEPTION}
20240 @item @code{EXPORT_FUNCTION}
20242 @item @code{EXPORT_OBJECT}
20244 @item @code{EXPORT_PROCEDURE}
20246 @item @code{EXPORT_VALUED_PROCEDURE}
20248 @item @code{FLOAT_REPRESENTATION}
20252 @item @code{IMPORT_EXCEPTION}
20254 @item @code{IMPORT_FUNCTION}
20256 @item @code{IMPORT_OBJECT}
20258 @item @code{IMPORT_PROCEDURE}
20260 @item @code{IMPORT_VALUED_PROCEDURE}
20262 @item @code{INLINE_GENERIC}
20264 @item @code{INTERFACE_NAME}
20266 @item @code{LONG_FLOAT}
20268 @item @code{MAIN_STORAGE}
20270 @item @code{PASSIVE}
20272 @item @code{PSECT_OBJECT}
20274 @item @code{SHARE_GENERIC}
20276 @item @code{SUPPRESS_ALL}
20278 @item @code{TASK_STORAGE}
20280 @item @code{TIME_SLICE}
20286 These pragmas are all fully implemented, with the exception of @code{TITLE},
20287 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20288 recognized, but which have no
20289 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20290 use of Ada protected objects. In GNAT, all generics are inlined.
20292 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20293 a separate subprogram specification which must appear before the
20296 GNAT also supplies a number of implementation-defined pragmas including the
20300 @item @code{ABORT_DEFER}
20302 @item @code{ADA_83}
20304 @item @code{ADA_95}
20306 @item @code{ADA_05}
20308 @item @code{Ada_2005}
20310 @item @code{Ada_12}
20312 @item @code{Ada_2012}
20314 @item @code{ANNOTATE}
20316 @item @code{ASSERT}
20318 @item @code{C_PASS_BY_COPY}
20320 @item @code{CPP_CLASS}
20322 @item @code{CPP_CONSTRUCTOR}
20324 @item @code{CPP_DESTRUCTOR}
20328 @item @code{EXTEND_SYSTEM}
20330 @item @code{LINKER_ALIAS}
20332 @item @code{LINKER_SECTION}
20334 @item @code{MACHINE_ATTRIBUTE}
20336 @item @code{NO_RETURN}
20338 @item @code{PURE_FUNCTION}
20340 @item @code{SOURCE_FILE_NAME}
20342 @item @code{SOURCE_REFERENCE}
20344 @item @code{TASK_INFO}
20346 @item @code{UNCHECKED_UNION}
20348 @item @code{UNIMPLEMENTED_UNIT}
20350 @item @code{UNIVERSAL_DATA}
20352 @item @code{UNSUPPRESS}
20354 @item @code{WARNINGS}
20356 @item @code{WEAK_EXTERNAL}
20360 For full details on these and other GNAT implementation-defined pragmas,
20361 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20365 * Restrictions on the Pragma INLINE::
20366 * Restrictions on the Pragma INTERFACE::
20367 * Restrictions on the Pragma SYSTEM_NAME::
20370 @node Restrictions on the Pragma INLINE
20371 @subsection Restrictions on Pragma @code{INLINE}
20374 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20376 @item Parameters cannot have a task type.
20378 @item Function results cannot be task types, unconstrained
20379 array types, or unconstrained types with discriminants.
20381 @item Bodies cannot declare the following:
20383 @item Subprogram body or stub (imported subprogram is allowed)
20387 @item Generic declarations
20389 @item Instantiations
20393 @item Access types (types derived from access types allowed)
20395 @item Array or record types
20397 @item Dependent tasks
20399 @item Direct recursive calls of subprogram or containing
20400 subprogram, directly or via a renaming
20406 In GNAT, the only restriction on pragma @code{INLINE} is that the
20407 body must occur before the call if both are in the same
20408 unit, and the size must be appropriately small. There are
20409 no other specific restrictions which cause subprograms to
20410 be incapable of being inlined.
20412 @node Restrictions on the Pragma INTERFACE
20413 @subsection Restrictions on Pragma @code{INTERFACE}
20416 The following restrictions on pragma @code{INTERFACE}
20417 are enforced by both HP Ada and GNAT:
20419 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
20420 Default is the default on OpenVMS Alpha systems.
20422 @item Parameter passing: Language specifies default
20423 mechanisms but can be overridden with an @code{EXPORT} pragma.
20426 @item Ada: Use internal Ada rules.
20428 @item Bliss, C: Parameters must be mode @code{in}; cannot be
20429 record or task type. Result cannot be a string, an
20430 array, or a record.
20432 @item Fortran: Parameters cannot have a task type. Result cannot
20433 be a string, an array, or a record.
20438 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20439 record parameters for all languages.
20441 @node Restrictions on the Pragma SYSTEM_NAME
20442 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
20445 For HP Ada for OpenVMS Alpha, the enumeration literal
20446 for the type @code{NAME} is @code{OPENVMS_AXP}.
20447 In GNAT, the enumeration
20448 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20450 @node Library of Predefined Units
20451 @section Library of Predefined Units
20454 A library of predefined units is provided as part of the
20455 HP Ada and GNAT implementations. HP Ada does not provide
20456 the package @code{MACHINE_CODE} but instead recommends importing
20459 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20460 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20462 The HP Ada Predefined Library units are modified to remove post-Ada 83
20463 incompatibilities and to make them interoperable with GNAT
20464 (@pxref{Changes to DECLIB}, for details).
20465 The units are located in the @file{DECLIB} directory.
20467 The GNAT RTL is contained in
20468 the @file{ADALIB} directory, and
20469 the default search path is set up to find @code{DECLIB} units in preference
20470 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20471 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20474 * Changes to DECLIB::
20477 @node Changes to DECLIB
20478 @subsection Changes to @code{DECLIB}
20481 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20482 compatibility are minor and include the following:
20485 @item Adjusting the location of pragmas and record representation
20486 clauses to obey Ada 95 (and thus Ada 2005) rules
20488 @item Adding the proper notation to generic formal parameters
20489 that take unconstrained types in instantiation
20491 @item Adding pragma @code{ELABORATE_BODY} to package specs
20492 that have package bodies not otherwise allowed
20494 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20495 ``@code{PROTECTD}''.
20496 Currently these are found only in the @code{STARLET} package spec.
20498 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20499 where the address size is constrained to 32 bits.
20503 None of the above changes is visible to users.
20509 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20512 @item Command Language Interpreter (CLI interface)
20514 @item DECtalk Run-Time Library (DTK interface)
20516 @item Librarian utility routines (LBR interface)
20518 @item General Purpose Run-Time Library (LIB interface)
20520 @item Math Run-Time Library (MTH interface)
20522 @item National Character Set Run-Time Library (NCS interface)
20524 @item Compiled Code Support Run-Time Library (OTS interface)
20526 @item Parallel Processing Run-Time Library (PPL interface)
20528 @item Screen Management Run-Time Library (SMG interface)
20530 @item Sort Run-Time Library (SOR interface)
20532 @item String Run-Time Library (STR interface)
20534 @item STARLET System Library
20537 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
20539 @item X Windows Toolkit (XT interface)
20541 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
20545 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20546 directory, on both the Alpha and I64 OpenVMS platforms.
20548 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20550 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20551 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20552 @code{Xt}, and @code{X_Lib}
20553 causing the default X/Motif sharable image libraries to be linked in. This
20554 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20555 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20557 It may be necessary to edit these options files to update or correct the
20558 library names if, for example, the newer X/Motif bindings from
20559 @file{ADA$EXAMPLES}
20560 had been (previous to installing GNAT) copied and renamed to supersede the
20561 default @file{ADA$PREDEFINED} versions.
20564 * Shared Libraries and Options Files::
20565 * Interfaces to C::
20568 @node Shared Libraries and Options Files
20569 @subsection Shared Libraries and Options Files
20572 When using the HP Ada
20573 predefined X and Motif bindings, the linking with their sharable images is
20574 done automatically by @command{GNAT LINK}.
20575 When using other X and Motif bindings, you need
20576 to add the corresponding sharable images to the command line for
20577 @code{GNAT LINK}. When linking with shared libraries, or with
20578 @file{.OPT} files, you must
20579 also add them to the command line for @command{GNAT LINK}.
20581 A shared library to be used with GNAT is built in the same way as other
20582 libraries under VMS. The VMS Link command can be used in standard fashion.
20584 @node Interfaces to C
20585 @subsection Interfaces to C
20589 provides the following Ada types and operations:
20592 @item C types package (@code{C_TYPES})
20594 @item C strings (@code{C_TYPES.NULL_TERMINATED})
20596 @item Other_types (@code{SHORT_INT})
20600 Interfacing to C with GNAT, you can use the above approach
20601 described for HP Ada or the facilities of Annex B of
20602 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
20603 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
20604 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
20606 The @option{-gnatF} qualifier forces default and explicit
20607 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
20608 to be uppercased for compatibility with the default behavior
20609 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
20611 @node Main Program Definition
20612 @section Main Program Definition
20615 The following section discusses differences in the
20616 definition of main programs on HP Ada and GNAT.
20617 On HP Ada, main programs are defined to meet the
20618 following conditions:
20620 @item Procedure with no formal parameters (returns @code{0} upon
20623 @item Procedure with no formal parameters (returns @code{42} when
20624 an unhandled exception is raised)
20626 @item Function with no formal parameters whose returned value
20627 is of a discrete type
20629 @item Procedure with one @code{out} formal of a discrete type for
20630 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
20635 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
20636 a main function or main procedure returns a discrete
20637 value whose size is less than 64 bits (32 on VAX systems),
20638 the value is zero- or sign-extended as appropriate.
20639 On GNAT, main programs are defined as follows:
20641 @item Must be a non-generic, parameterless subprogram that
20642 is either a procedure or function returning an Ada
20643 @code{STANDARD.INTEGER} (the predefined type)
20645 @item Cannot be a generic subprogram or an instantiation of a
20649 @node Implementation-Defined Attributes
20650 @section Implementation-Defined Attributes
20653 GNAT provides all HP Ada implementation-defined
20656 @node Compiler and Run-Time Interfacing
20657 @section Compiler and Run-Time Interfacing
20660 HP Ada provides the following qualifiers to pass options to the linker
20663 @item @option{/WAIT} and @option{/SUBMIT}
20665 @item @option{/COMMAND}
20667 @item @option{/@r{[}NO@r{]}MAP}
20669 @item @option{/OUTPUT=@var{file-spec}}
20671 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20675 To pass options to the linker, GNAT provides the following
20679 @item @option{/EXECUTABLE=@var{exec-name}}
20681 @item @option{/VERBOSE}
20683 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20687 For more information on these switches, see
20688 @ref{Switches for gnatlink}.
20689 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
20690 to control optimization. HP Ada also supplies the
20693 @item @code{OPTIMIZE}
20695 @item @code{INLINE}
20697 @item @code{INLINE_GENERIC}
20699 @item @code{SUPPRESS_ALL}
20701 @item @code{PASSIVE}
20705 In GNAT, optimization is controlled strictly by command
20706 line parameters, as described in the corresponding section of this guide.
20707 The HP pragmas for control of optimization are
20708 recognized but ignored.
20710 Note that in GNAT, the default is optimization off, whereas in HP Ada
20711 the default is that optimization is turned on.
20713 @node Program Compilation and Library Management
20714 @section Program Compilation and Library Management
20717 HP Ada and GNAT provide a comparable set of commands to
20718 build programs. HP Ada also provides a program library,
20719 which is a concept that does not exist on GNAT. Instead,
20720 GNAT provides directories of sources that are compiled as
20723 The following table summarizes
20724 the HP Ada commands and provides
20725 equivalent GNAT commands. In this table, some GNAT
20726 equivalents reflect the fact that GNAT does not use the
20727 concept of a program library. Instead, it uses a model
20728 in which collections of source and object files are used
20729 in a manner consistent with other languages like C and
20730 Fortran. Therefore, standard system file commands are used
20731 to manipulate these elements. Those GNAT commands are marked with
20733 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
20736 @multitable @columnfractions .35 .65
20738 @item @emph{HP Ada Command}
20739 @tab @emph{GNAT Equivalent / Description}
20741 @item @command{ADA}
20742 @tab @command{GNAT COMPILE}@*
20743 Invokes the compiler to compile one or more Ada source files.
20745 @item @command{ACS ATTACH}@*
20746 @tab [No equivalent]@*
20747 Switches control of terminal from current process running the program
20750 @item @command{ACS CHECK}
20751 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20752 Forms the execution closure of one
20753 or more compiled units and checks completeness and currency.
20755 @item @command{ACS COMPILE}
20756 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20757 Forms the execution closure of one or
20758 more specified units, checks completeness and currency,
20759 identifies units that have revised source files, compiles same,
20760 and recompiles units that are or will become obsolete.
20761 Also completes incomplete generic instantiations.
20763 @item @command{ACS COPY FOREIGN}
20765 Copies a foreign object file into the program library as a
20768 @item @command{ACS COPY UNIT}
20770 Copies a compiled unit from one program library to another.
20772 @item @command{ACS CREATE LIBRARY}
20773 @tab Create /directory (*)@*
20774 Creates a program library.
20776 @item @command{ACS CREATE SUBLIBRARY}
20777 @tab Create /directory (*)@*
20778 Creates a program sublibrary.
20780 @item @command{ACS DELETE LIBRARY}
20782 Deletes a program library and its contents.
20784 @item @command{ACS DELETE SUBLIBRARY}
20786 Deletes a program sublibrary and its contents.
20788 @item @command{ACS DELETE UNIT}
20789 @tab Delete file (*)@*
20790 On OpenVMS systems, deletes one or more compiled units from
20791 the current program library.
20793 @item @command{ACS DIRECTORY}
20794 @tab Directory (*)@*
20795 On OpenVMS systems, lists units contained in the current
20798 @item @command{ACS ENTER FOREIGN}
20800 Allows the import of a foreign body as an Ada library
20801 spec and enters a reference to a pointer.
20803 @item @command{ACS ENTER UNIT}
20805 Enters a reference (pointer) from the current program library to
20806 a unit compiled into another program library.
20808 @item @command{ACS EXIT}
20809 @tab [No equivalent]@*
20810 Exits from the program library manager.
20812 @item @command{ACS EXPORT}
20814 Creates an object file that contains system-specific object code
20815 for one or more units. With GNAT, object files can simply be copied
20816 into the desired directory.
20818 @item @command{ACS EXTRACT SOURCE}
20820 Allows access to the copied source file for each Ada compilation unit
20822 @item @command{ACS HELP}
20823 @tab @command{HELP GNAT}@*
20824 Provides online help.
20826 @item @command{ACS LINK}
20827 @tab @command{GNAT LINK}@*
20828 Links an object file containing Ada units into an executable file.
20830 @item @command{ACS LOAD}
20832 Loads (partially compiles) Ada units into the program library.
20833 Allows loading a program from a collection of files into a library
20834 without knowing the relationship among units.
20836 @item @command{ACS MERGE}
20838 Merges into the current program library, one or more units from
20839 another library where they were modified.
20841 @item @command{ACS RECOMPILE}
20842 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20843 Recompiles from external or copied source files any obsolete
20844 unit in the closure. Also, completes any incomplete generic
20847 @item @command{ACS REENTER}
20848 @tab @command{GNAT MAKE}@*
20849 Reenters current references to units compiled after last entered
20850 with the @command{ACS ENTER UNIT} command.
20852 @item @command{ACS SET LIBRARY}
20853 @tab Set default (*)@*
20854 Defines a program library to be the compilation context as well
20855 as the target library for compiler output and commands in general.
20857 @item @command{ACS SET PRAGMA}
20858 @tab Edit @file{gnat.adc} (*)@*
20859 Redefines specified values of the library characteristics
20860 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20861 and @code{Float_Representation}.
20863 @item @command{ACS SET SOURCE}
20864 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20865 Defines the source file search list for the @command{ACS COMPILE} command.
20867 @item @command{ACS SHOW LIBRARY}
20868 @tab Directory (*)@*
20869 Lists information about one or more program libraries.
20871 @item @command{ACS SHOW PROGRAM}
20872 @tab [No equivalent]@*
20873 Lists information about the execution closure of one or
20874 more units in the program library.
20876 @item @command{ACS SHOW SOURCE}
20877 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20878 Shows the source file search used when compiling units.
20880 @item @command{ACS SHOW VERSION}
20881 @tab Compile with @option{VERBOSE} option
20882 Displays the version number of the compiler and program library
20885 @item @command{ACS SPAWN}
20886 @tab [No equivalent]@*
20887 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20890 @item @command{ACS VERIFY}
20891 @tab [No equivalent]@*
20892 Performs a series of consistency checks on a program library to
20893 determine whether the library structure and library files are in
20900 @section Input-Output
20903 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
20904 Management Services (RMS) to perform operations on
20908 HP Ada and GNAT predefine an identical set of input-
20909 output packages. To make the use of the
20910 generic @code{TEXT_IO} operations more convenient, HP Ada
20911 provides predefined library packages that instantiate the
20912 integer and floating-point operations for the predefined
20913 integer and floating-point types as shown in the following table.
20915 @multitable @columnfractions .45 .55
20916 @item @emph{Package Name} @tab Instantiation
20918 @item @code{INTEGER_TEXT_IO}
20919 @tab @code{INTEGER_IO(INTEGER)}
20921 @item @code{SHORT_INTEGER_TEXT_IO}
20922 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20924 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20925 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20927 @item @code{FLOAT_TEXT_IO}
20928 @tab @code{FLOAT_IO(FLOAT)}
20930 @item @code{LONG_FLOAT_TEXT_IO}
20931 @tab @code{FLOAT_IO(LONG_FLOAT)}
20935 The HP Ada predefined packages and their operations
20936 are implemented using OpenVMS Alpha files and input-output
20937 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
20938 Familiarity with the following is recommended:
20940 @item RMS file organizations and access methods
20942 @item OpenVMS file specifications and directories
20944 @item OpenVMS File Definition Language (FDL)
20948 GNAT provides I/O facilities that are completely
20949 compatible with HP Ada. The distribution includes the
20950 standard HP Ada versions of all I/O packages, operating
20951 in a manner compatible with HP Ada. In particular, the
20952 following packages are by default the HP Ada (Ada 83)
20953 versions of these packages rather than the renamings
20954 suggested in Annex J of the Ada Reference Manual:
20956 @item @code{TEXT_IO}
20958 @item @code{SEQUENTIAL_IO}
20960 @item @code{DIRECT_IO}
20964 The use of the standard child package syntax (for
20965 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
20967 GNAT provides HP-compatible predefined instantiations
20968 of the @code{TEXT_IO} packages, and also
20969 provides the standard predefined instantiations required
20970 by the @cite{Ada Reference Manual}.
20972 For further information on how GNAT interfaces to the file
20973 system or how I/O is implemented in programs written in
20974 mixed languages, see @ref{Implementation of the Standard I/O,,,
20975 gnat_rm, GNAT Reference Manual}.
20976 This chapter covers the following:
20978 @item Standard I/O packages
20980 @item @code{FORM} strings
20982 @item @code{ADA.DIRECT_IO}
20984 @item @code{ADA.SEQUENTIAL_IO}
20986 @item @code{ADA.TEXT_IO}
20988 @item Stream pointer positioning
20990 @item Reading and writing non-regular files
20992 @item @code{GET_IMMEDIATE}
20994 @item Treating @code{TEXT_IO} files as streams
21001 @node Implementation Limits
21002 @section Implementation Limits
21005 The following table lists implementation limits for HP Ada
21007 @multitable @columnfractions .60 .20 .20
21009 @item @emph{Compilation Parameter}
21014 @item In a subprogram or entry declaration, maximum number of
21015 formal parameters that are of an unconstrained record type
21020 @item Maximum identifier length (number of characters)
21025 @item Maximum number of characters in a source line
21030 @item Maximum collection size (number of bytes)
21035 @item Maximum number of discriminants for a record type
21040 @item Maximum number of formal parameters in an entry or
21041 subprogram declaration
21046 @item Maximum number of dimensions in an array type
21051 @item Maximum number of library units and subunits in a compilation.
21056 @item Maximum number of library units and subunits in an execution.
21061 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21062 or @code{PSECT_OBJECT}
21067 @item Maximum number of enumeration literals in an enumeration type
21073 @item Maximum number of lines in a source file
21078 @item Maximum number of bits in any object
21083 @item Maximum size of the static portion of a stack frame (approximate)
21088 @node Tools and Utilities
21089 @section Tools and Utilities
21092 The following table lists some of the OpenVMS development tools
21093 available for HP Ada, and the corresponding tools for
21094 use with @value{EDITION} on Alpha and I64 platforms.
21095 Aside from the debugger, all the OpenVMS tools identified are part
21096 of the DECset package.
21099 @c Specify table in TeX since Texinfo does a poor job
21103 \settabs\+Language-Sensitive Editor\quad
21104 &Product with HP Ada\quad
21107 &\it Product with HP Ada
21108 & \it Product with GNAT Pro\cr
21110 \+Code Management System
21114 \+Language-Sensitive Editor
21116 & emacs or HP LSE (Alpha)\cr
21126 & OpenVMS Debug (I64)\cr
21128 \+Source Code Analyzer /
21145 \+Coverage Analyzer
21149 \+Module Management
21151 & Not applicable\cr
21161 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
21162 @c the TeX version above for the printed version
21164 @c @multitable @columnfractions .3 .4 .4
21165 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21167 @tab @i{Tool with HP Ada}
21168 @tab @i{Tool with @value{EDITION}}
21169 @item Code Management@*System
21172 @item Language-Sensitive@*Editor
21174 @tab emacs or HP LSE (Alpha)
21183 @tab OpenVMS Debug (I64)
21184 @item Source Code Analyzer /@*Cross Referencer
21188 @tab HP Digital Test@*Manager (DTM)
21190 @item Performance and@*Coverage Analyzer
21193 @item Module Management@*System
21195 @tab Not applicable
21202 @c **************************************
21203 @node Platform-Specific Information for the Run-Time Libraries
21204 @appendix Platform-Specific Information for the Run-Time Libraries
21205 @cindex Tasking and threads libraries
21206 @cindex Threads libraries and tasking
21207 @cindex Run-time libraries (platform-specific information)
21210 The GNAT run-time implementation may vary with respect to both the
21211 underlying threads library and the exception handling scheme.
21212 For threads support, one or more of the following are supplied:
21214 @item @b{native threads library}, a binding to the thread package from
21215 the underlying operating system
21217 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21218 POSIX thread package
21222 For exception handling, either or both of two models are supplied:
21224 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21225 Most programs should experience a substantial speed improvement by
21226 being compiled with a ZCX run-time.
21227 This is especially true for
21228 tasking applications or applications with many exception handlers.}
21229 @cindex Zero-Cost Exceptions
21230 @cindex ZCX (Zero-Cost Exceptions)
21231 which uses binder-generated tables that
21232 are interrogated at run time to locate a handler
21234 @item @b{setjmp / longjmp} (``SJLJ''),
21235 @cindex setjmp/longjmp Exception Model
21236 @cindex SJLJ (setjmp/longjmp Exception Model)
21237 which uses dynamically-set data to establish
21238 the set of handlers
21242 This appendix summarizes which combinations of threads and exception support
21243 are supplied on various GNAT platforms.
21244 It then shows how to select a particular library either
21245 permanently or temporarily,
21246 explains the properties of (and tradeoffs among) the various threads
21247 libraries, and provides some additional
21248 information about several specific platforms.
21251 * Summary of Run-Time Configurations::
21252 * Specifying a Run-Time Library::
21253 * Choosing the Scheduling Policy::
21254 * Solaris-Specific Considerations::
21255 * Linux-Specific Considerations::
21256 * AIX-Specific Considerations::
21257 * Irix-Specific Considerations::
21258 * RTX-Specific Considerations::
21259 * HP-UX-Specific Considerations::
21262 @node Summary of Run-Time Configurations
21263 @section Summary of Run-Time Configurations
21265 @multitable @columnfractions .30 .70
21266 @item @b{alpha-openvms}
21267 @item @code{@ @ }@i{rts-native (default)}
21268 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21269 @item @code{@ @ @ @ }Exceptions @tab ZCX
21271 @item @b{alpha-tru64}
21272 @item @code{@ @ }@i{rts-native (default)}
21273 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21274 @item @code{@ @ @ @ }Exceptions @tab ZCX
21276 @item @code{@ @ }@i{rts-sjlj}
21277 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21278 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21280 @item @b{ia64-hp_linux}
21281 @item @code{@ @ }@i{rts-native (default)}
21282 @item @code{@ @ @ @ }Tasking @tab pthread library
21283 @item @code{@ @ @ @ }Exceptions @tab ZCX
21285 @item @b{ia64-hpux}
21286 @item @code{@ @ }@i{rts-native (default)}
21287 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21288 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21290 @item @b{ia64-openvms}
21291 @item @code{@ @ }@i{rts-native (default)}
21292 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21293 @item @code{@ @ @ @ }Exceptions @tab ZCX
21295 @item @b{ia64-sgi_linux}
21296 @item @code{@ @ }@i{rts-native (default)}
21297 @item @code{@ @ @ @ }Tasking @tab pthread library
21298 @item @code{@ @ @ @ }Exceptions @tab ZCX
21300 @item @b{mips-irix}
21301 @item @code{@ @ }@i{rts-native (default)}
21302 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
21303 @item @code{@ @ @ @ }Exceptions @tab ZCX
21306 @item @code{@ @ }@i{rts-native (default)}
21307 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21308 @item @code{@ @ @ @ }Exceptions @tab ZCX
21310 @item @code{@ @ }@i{rts-sjlj}
21311 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21312 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21315 @item @code{@ @ }@i{rts-native (default)}
21316 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21317 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21319 @item @b{ppc-darwin}
21320 @item @code{@ @ }@i{rts-native (default)}
21321 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
21322 @item @code{@ @ @ @ }Exceptions @tab ZCX
21324 @item @b{sparc-solaris} @tab
21325 @item @code{@ @ }@i{rts-native (default)}
21326 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21327 @item @code{@ @ @ @ }Exceptions @tab ZCX
21329 @item @code{@ @ }@i{rts-pthread}
21330 @item @code{@ @ @ @ }Tasking @tab pthread library
21331 @item @code{@ @ @ @ }Exceptions @tab ZCX
21333 @item @code{@ @ }@i{rts-sjlj}
21334 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21335 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21337 @item @b{sparc64-solaris} @tab
21338 @item @code{@ @ }@i{rts-native (default)}
21339 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21340 @item @code{@ @ @ @ }Exceptions @tab ZCX
21342 @item @b{x86-linux}
21343 @item @code{@ @ }@i{rts-native (default)}
21344 @item @code{@ @ @ @ }Tasking @tab pthread library
21345 @item @code{@ @ @ @ }Exceptions @tab ZCX
21347 @item @code{@ @ }@i{rts-sjlj}
21348 @item @code{@ @ @ @ }Tasking @tab pthread library
21349 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21352 @item @code{@ @ }@i{rts-native (default)}
21353 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
21354 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21356 @item @b{x86-solaris}
21357 @item @code{@ @ }@i{rts-native (default)}
21358 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
21359 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21361 @item @b{x86-windows}
21362 @item @code{@ @ }@i{rts-native (default)}
21363 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21364 @item @code{@ @ @ @ }Exceptions @tab ZCX
21366 @item @code{@ @ }@i{rts-sjlj (default)}
21367 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21368 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21370 @item @b{x86-windows-rtx}
21371 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21372 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
21373 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21375 @item @code{@ @ }@i{rts-rtx-w32}
21376 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
21377 @item @code{@ @ @ @ }Exceptions @tab ZCX
21379 @item @b{x86_64-linux}
21380 @item @code{@ @ }@i{rts-native (default)}
21381 @item @code{@ @ @ @ }Tasking @tab pthread library
21382 @item @code{@ @ @ @ }Exceptions @tab ZCX
21384 @item @code{@ @ }@i{rts-sjlj}
21385 @item @code{@ @ @ @ }Tasking @tab pthread library
21386 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21390 @node Specifying a Run-Time Library
21391 @section Specifying a Run-Time Library
21394 The @file{adainclude} subdirectory containing the sources of the GNAT
21395 run-time library, and the @file{adalib} subdirectory containing the
21396 @file{ALI} files and the static and/or shared GNAT library, are located
21397 in the gcc target-dependent area:
21400 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21404 As indicated above, on some platforms several run-time libraries are supplied.
21405 These libraries are installed in the target dependent area and
21406 contain a complete source and binary subdirectory. The detailed description
21407 below explains the differences between the different libraries in terms of
21408 their thread support.
21410 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21411 This default run time is selected by the means of soft links.
21412 For example on x86-linux:
21418 +--- adainclude----------+
21420 +--- adalib-----------+ |
21422 +--- rts-native | |
21424 | +--- adainclude <---+
21426 | +--- adalib <----+
21437 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21438 these soft links can be modified with the following commands:
21442 $ rm -f adainclude adalib
21443 $ ln -s rts-sjlj/adainclude adainclude
21444 $ ln -s rts-sjlj/adalib adalib
21448 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21449 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21450 @file{$target/ada_object_path}.
21452 Selecting another run-time library temporarily can be
21453 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21454 @cindex @option{--RTS} option
21456 @node Choosing the Scheduling Policy
21457 @section Choosing the Scheduling Policy
21460 When using a POSIX threads implementation, you have a choice of several
21461 scheduling policies: @code{SCHED_FIFO},
21462 @cindex @code{SCHED_FIFO} scheduling policy
21464 @cindex @code{SCHED_RR} scheduling policy
21465 and @code{SCHED_OTHER}.
21466 @cindex @code{SCHED_OTHER} scheduling policy
21467 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21468 or @code{SCHED_RR} requires special (e.g., root) privileges.
21470 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21472 @cindex @code{SCHED_FIFO} scheduling policy
21473 you can use one of the following:
21477 @code{pragma Time_Slice (0.0)}
21478 @cindex pragma Time_Slice
21480 the corresponding binder option @option{-T0}
21481 @cindex @option{-T0} option
21483 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21484 @cindex pragma Task_Dispatching_Policy
21488 To specify @code{SCHED_RR},
21489 @cindex @code{SCHED_RR} scheduling policy
21490 you should use @code{pragma Time_Slice} with a
21491 value greater than @code{0.0}, or else use the corresponding @option{-T}
21494 @node Solaris-Specific Considerations
21495 @section Solaris-Specific Considerations
21496 @cindex Solaris Sparc threads libraries
21499 This section addresses some topics related to the various threads libraries
21503 * Solaris Threads Issues::
21506 @node Solaris Threads Issues
21507 @subsection Solaris Threads Issues
21510 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21511 library based on POSIX threads --- @emph{rts-pthread}.
21512 @cindex rts-pthread threads library
21513 This run-time library has the advantage of being mostly shared across all
21514 POSIX-compliant thread implementations, and it also provides under
21515 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21516 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21517 and @code{PTHREAD_PRIO_PROTECT}
21518 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21519 semantics that can be selected using the predefined pragma
21520 @code{Locking_Policy}
21521 @cindex pragma Locking_Policy (under rts-pthread)
21523 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21524 @cindex @code{Inheritance_Locking} (under rts-pthread)
21525 @cindex @code{Ceiling_Locking} (under rts-pthread)
21527 As explained above, the native run-time library is based on the Solaris thread
21528 library (@code{libthread}) and is the default library.
21530 When the Solaris threads library is used (this is the default), programs
21531 compiled with GNAT can automatically take advantage of
21532 and can thus execute on multiple processors.
21533 The user can alternatively specify a processor on which the program should run
21534 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21536 setting the environment variable @env{GNAT_PROCESSOR}
21537 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21538 to one of the following:
21542 Use the default configuration (run the program on all
21543 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21547 Let the run-time implementation choose one processor and run the program on
21550 @item 0 .. Last_Proc
21551 Run the program on the specified processor.
21552 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21553 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21556 @node Linux-Specific Considerations
21557 @section Linux-Specific Considerations
21558 @cindex Linux threads libraries
21561 On GNU/Linux without NPTL support (usually system with GNU C Library
21562 older than 2.3), the signal model is not POSIX compliant, which means
21563 that to send a signal to the process, you need to send the signal to all
21564 threads, e.g.@: by using @code{killpg()}.
21566 @node AIX-Specific Considerations
21567 @section AIX-Specific Considerations
21568 @cindex AIX resolver library
21571 On AIX, the resolver library initializes some internal structure on
21572 the first call to @code{get*by*} functions, which are used to implement
21573 @code{GNAT.Sockets.Get_Host_By_Name} and
21574 @code{GNAT.Sockets.Get_Host_By_Address}.
21575 If such initialization occurs within an Ada task, and the stack size for
21576 the task is the default size, a stack overflow may occur.
21578 To avoid this overflow, the user should either ensure that the first call
21579 to @code{GNAT.Sockets.Get_Host_By_Name} or
21580 @code{GNAT.Sockets.Get_Host_By_Addrss}
21581 occurs in the environment task, or use @code{pragma Storage_Size} to
21582 specify a sufficiently large size for the stack of the task that contains
21585 @node Irix-Specific Considerations
21586 @section Irix-Specific Considerations
21587 @cindex Irix libraries
21590 The GCC support libraries coming with the Irix compiler have moved to
21591 their canonical place with respect to the general Irix ABI related
21592 conventions. Running applications built with the default shared GNAT
21593 run-time now requires the LD_LIBRARY_PATH environment variable to
21594 include this location. A possible way to achieve this is to issue the
21595 following command line on a bash prompt:
21599 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
21603 @node RTX-Specific Considerations
21604 @section RTX-Specific Considerations
21605 @cindex RTX libraries
21608 The Real-time Extension (RTX) to Windows is based on the Windows Win32
21609 API. Applications can be built to work in two different modes:
21613 Windows executables that run in Ring 3 to utilize memory protection
21614 (@emph{rts-rtx-w32}).
21617 Real-time subsystem (RTSS) executables that run in Ring 0, where
21618 performance can be optimized with RTSS applications taking precedent
21619 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
21620 the Microsoft linker to handle RTSS libraries.
21624 @node HP-UX-Specific Considerations
21625 @section HP-UX-Specific Considerations
21626 @cindex HP-UX Scheduling
21629 On HP-UX, appropriate privileges are required to change the scheduling
21630 parameters of a task. The calling process must have appropriate
21631 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
21632 successfully change the scheduling parameters.
21634 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
21635 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
21636 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
21638 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
21639 one of the following:
21643 @code{pragma Time_Slice (0.0)}
21644 @cindex pragma Time_Slice
21646 the corresponding binder option @option{-T0}
21647 @cindex @option{-T0} option
21649 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21650 @cindex pragma Task_Dispatching_Policy
21654 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
21655 you should use @code{pragma Time_Slice} with a
21656 value greater than @code{0.0}, or use the corresponding @option{-T}
21657 binder option, or set the @code{pragma Task_Dispatching_Policy
21658 (Round_Robin_Within_Priorities)}.
21660 @c *******************************
21661 @node Example of Binder Output File
21662 @appendix Example of Binder Output File
21665 This Appendix displays the source code for @command{gnatbind}'s output
21666 file generated for a simple ``Hello World'' program.
21667 Comments have been added for clarification purposes.
21669 @smallexample @c adanocomment
21673 -- The package is called Ada_Main unless this name is actually used
21674 -- as a unit name in the partition, in which case some other unique
21678 package ada_main is
21680 Elab_Final_Code : Integer;
21681 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21683 -- The main program saves the parameters (argument count,
21684 -- argument values, environment pointer) in global variables
21685 -- for later access by other units including
21686 -- Ada.Command_Line.
21688 gnat_argc : Integer;
21689 gnat_argv : System.Address;
21690 gnat_envp : System.Address;
21692 -- The actual variables are stored in a library routine. This
21693 -- is useful for some shared library situations, where there
21694 -- are problems if variables are not in the library.
21696 pragma Import (C, gnat_argc);
21697 pragma Import (C, gnat_argv);
21698 pragma Import (C, gnat_envp);
21700 -- The exit status is similarly an external location
21702 gnat_exit_status : Integer;
21703 pragma Import (C, gnat_exit_status);
21705 GNAT_Version : constant String :=
21706 "GNAT Version: 6.0.0w (20061115)";
21707 pragma Export (C, GNAT_Version, "__gnat_version");
21709 -- This is the generated adafinal routine that performs
21710 -- finalization at the end of execution. In the case where
21711 -- Ada is the main program, this main program makes a call
21712 -- to adafinal at program termination.
21714 procedure adafinal;
21715 pragma Export (C, adafinal, "adafinal");
21717 -- This is the generated adainit routine that performs
21718 -- initialization at the start of execution. In the case
21719 -- where Ada is the main program, this main program makes
21720 -- a call to adainit at program startup.
21723 pragma Export (C, adainit, "adainit");
21725 -- This routine is called at the start of execution. It is
21726 -- a dummy routine that is used by the debugger to breakpoint
21727 -- at the start of execution.
21729 procedure Break_Start;
21730 pragma Import (C, Break_Start, "__gnat_break_start");
21732 -- This is the actual generated main program (it would be
21733 -- suppressed if the no main program switch were used). As
21734 -- required by standard system conventions, this program has
21735 -- the external name main.
21739 argv : System.Address;
21740 envp : System.Address)
21742 pragma Export (C, main, "main");
21744 -- The following set of constants give the version
21745 -- identification values for every unit in the bound
21746 -- partition. This identification is computed from all
21747 -- dependent semantic units, and corresponds to the
21748 -- string that would be returned by use of the
21749 -- Body_Version or Version attributes.
21751 type Version_32 is mod 2 ** 32;
21752 u00001 : constant Version_32 := 16#7880BEB3#;
21753 u00002 : constant Version_32 := 16#0D24CBD0#;
21754 u00003 : constant Version_32 := 16#3283DBEB#;
21755 u00004 : constant Version_32 := 16#2359F9ED#;
21756 u00005 : constant Version_32 := 16#664FB847#;
21757 u00006 : constant Version_32 := 16#68E803DF#;
21758 u00007 : constant Version_32 := 16#5572E604#;
21759 u00008 : constant Version_32 := 16#46B173D8#;
21760 u00009 : constant Version_32 := 16#156A40CF#;
21761 u00010 : constant Version_32 := 16#033DABE0#;
21762 u00011 : constant Version_32 := 16#6AB38FEA#;
21763 u00012 : constant Version_32 := 16#22B6217D#;
21764 u00013 : constant Version_32 := 16#68A22947#;
21765 u00014 : constant Version_32 := 16#18CC4A56#;
21766 u00015 : constant Version_32 := 16#08258E1B#;
21767 u00016 : constant Version_32 := 16#367D5222#;
21768 u00017 : constant Version_32 := 16#20C9ECA4#;
21769 u00018 : constant Version_32 := 16#50D32CB6#;
21770 u00019 : constant Version_32 := 16#39A8BB77#;
21771 u00020 : constant Version_32 := 16#5CF8FA2B#;
21772 u00021 : constant Version_32 := 16#2F1EB794#;
21773 u00022 : constant Version_32 := 16#31AB6444#;
21774 u00023 : constant Version_32 := 16#1574B6E9#;
21775 u00024 : constant Version_32 := 16#5109C189#;
21776 u00025 : constant Version_32 := 16#56D770CD#;
21777 u00026 : constant Version_32 := 16#02F9DE3D#;
21778 u00027 : constant Version_32 := 16#08AB6B2C#;
21779 u00028 : constant Version_32 := 16#3FA37670#;
21780 u00029 : constant Version_32 := 16#476457A0#;
21781 u00030 : constant Version_32 := 16#731E1B6E#;
21782 u00031 : constant Version_32 := 16#23C2E789#;
21783 u00032 : constant Version_32 := 16#0F1BD6A1#;
21784 u00033 : constant Version_32 := 16#7C25DE96#;
21785 u00034 : constant Version_32 := 16#39ADFFA2#;
21786 u00035 : constant Version_32 := 16#571DE3E7#;
21787 u00036 : constant Version_32 := 16#5EB646AB#;
21788 u00037 : constant Version_32 := 16#4249379B#;
21789 u00038 : constant Version_32 := 16#0357E00A#;
21790 u00039 : constant Version_32 := 16#3784FB72#;
21791 u00040 : constant Version_32 := 16#2E723019#;
21792 u00041 : constant Version_32 := 16#623358EA#;
21793 u00042 : constant Version_32 := 16#107F9465#;
21794 u00043 : constant Version_32 := 16#6843F68A#;
21795 u00044 : constant Version_32 := 16#63305874#;
21796 u00045 : constant Version_32 := 16#31E56CE1#;
21797 u00046 : constant Version_32 := 16#02917970#;
21798 u00047 : constant Version_32 := 16#6CCBA70E#;
21799 u00048 : constant Version_32 := 16#41CD4204#;
21800 u00049 : constant Version_32 := 16#572E3F58#;
21801 u00050 : constant Version_32 := 16#20729FF5#;
21802 u00051 : constant Version_32 := 16#1D4F93E8#;
21803 u00052 : constant Version_32 := 16#30B2EC3D#;
21804 u00053 : constant Version_32 := 16#34054F96#;
21805 u00054 : constant Version_32 := 16#5A199860#;
21806 u00055 : constant Version_32 := 16#0E7F912B#;
21807 u00056 : constant Version_32 := 16#5760634A#;
21808 u00057 : constant Version_32 := 16#5D851835#;
21810 -- The following Export pragmas export the version numbers
21811 -- with symbolic names ending in B (for body) or S
21812 -- (for spec) so that they can be located in a link. The
21813 -- information provided here is sufficient to track down
21814 -- the exact versions of units used in a given build.
21816 pragma Export (C, u00001, "helloB");
21817 pragma Export (C, u00002, "system__standard_libraryB");
21818 pragma Export (C, u00003, "system__standard_libraryS");
21819 pragma Export (C, u00004, "adaS");
21820 pragma Export (C, u00005, "ada__text_ioB");
21821 pragma Export (C, u00006, "ada__text_ioS");
21822 pragma Export (C, u00007, "ada__exceptionsB");
21823 pragma Export (C, u00008, "ada__exceptionsS");
21824 pragma Export (C, u00009, "gnatS");
21825 pragma Export (C, u00010, "gnat__heap_sort_aB");
21826 pragma Export (C, u00011, "gnat__heap_sort_aS");
21827 pragma Export (C, u00012, "systemS");
21828 pragma Export (C, u00013, "system__exception_tableB");
21829 pragma Export (C, u00014, "system__exception_tableS");
21830 pragma Export (C, u00015, "gnat__htableB");
21831 pragma Export (C, u00016, "gnat__htableS");
21832 pragma Export (C, u00017, "system__exceptionsS");
21833 pragma Export (C, u00018, "system__machine_state_operationsB");
21834 pragma Export (C, u00019, "system__machine_state_operationsS");
21835 pragma Export (C, u00020, "system__machine_codeS");
21836 pragma Export (C, u00021, "system__storage_elementsB");
21837 pragma Export (C, u00022, "system__storage_elementsS");
21838 pragma Export (C, u00023, "system__secondary_stackB");
21839 pragma Export (C, u00024, "system__secondary_stackS");
21840 pragma Export (C, u00025, "system__parametersB");
21841 pragma Export (C, u00026, "system__parametersS");
21842 pragma Export (C, u00027, "system__soft_linksB");
21843 pragma Export (C, u00028, "system__soft_linksS");
21844 pragma Export (C, u00029, "system__stack_checkingB");
21845 pragma Export (C, u00030, "system__stack_checkingS");
21846 pragma Export (C, u00031, "system__tracebackB");
21847 pragma Export (C, u00032, "system__tracebackS");
21848 pragma Export (C, u00033, "ada__streamsS");
21849 pragma Export (C, u00034, "ada__tagsB");
21850 pragma Export (C, u00035, "ada__tagsS");
21851 pragma Export (C, u00036, "system__string_opsB");
21852 pragma Export (C, u00037, "system__string_opsS");
21853 pragma Export (C, u00038, "interfacesS");
21854 pragma Export (C, u00039, "interfaces__c_streamsB");
21855 pragma Export (C, u00040, "interfaces__c_streamsS");
21856 pragma Export (C, u00041, "system__file_ioB");
21857 pragma Export (C, u00042, "system__file_ioS");
21858 pragma Export (C, u00043, "ada__finalizationB");
21859 pragma Export (C, u00044, "ada__finalizationS");
21860 pragma Export (C, u00045, "system__finalization_rootB");
21861 pragma Export (C, u00046, "system__finalization_rootS");
21862 pragma Export (C, u00047, "system__finalization_implementationB");
21863 pragma Export (C, u00048, "system__finalization_implementationS");
21864 pragma Export (C, u00049, "system__string_ops_concat_3B");
21865 pragma Export (C, u00050, "system__string_ops_concat_3S");
21866 pragma Export (C, u00051, "system__stream_attributesB");
21867 pragma Export (C, u00052, "system__stream_attributesS");
21868 pragma Export (C, u00053, "ada__io_exceptionsS");
21869 pragma Export (C, u00054, "system__unsigned_typesS");
21870 pragma Export (C, u00055, "system__file_control_blockS");
21871 pragma Export (C, u00056, "ada__finalization__list_controllerB");
21872 pragma Export (C, u00057, "ada__finalization__list_controllerS");
21874 -- BEGIN ELABORATION ORDER
21877 -- gnat.heap_sort_a (spec)
21878 -- gnat.heap_sort_a (body)
21879 -- gnat.htable (spec)
21880 -- gnat.htable (body)
21881 -- interfaces (spec)
21883 -- system.machine_code (spec)
21884 -- system.parameters (spec)
21885 -- system.parameters (body)
21886 -- interfaces.c_streams (spec)
21887 -- interfaces.c_streams (body)
21888 -- system.standard_library (spec)
21889 -- ada.exceptions (spec)
21890 -- system.exception_table (spec)
21891 -- system.exception_table (body)
21892 -- ada.io_exceptions (spec)
21893 -- system.exceptions (spec)
21894 -- system.storage_elements (spec)
21895 -- system.storage_elements (body)
21896 -- system.machine_state_operations (spec)
21897 -- system.machine_state_operations (body)
21898 -- system.secondary_stack (spec)
21899 -- system.stack_checking (spec)
21900 -- system.soft_links (spec)
21901 -- system.soft_links (body)
21902 -- system.stack_checking (body)
21903 -- system.secondary_stack (body)
21904 -- system.standard_library (body)
21905 -- system.string_ops (spec)
21906 -- system.string_ops (body)
21909 -- ada.streams (spec)
21910 -- system.finalization_root (spec)
21911 -- system.finalization_root (body)
21912 -- system.string_ops_concat_3 (spec)
21913 -- system.string_ops_concat_3 (body)
21914 -- system.traceback (spec)
21915 -- system.traceback (body)
21916 -- ada.exceptions (body)
21917 -- system.unsigned_types (spec)
21918 -- system.stream_attributes (spec)
21919 -- system.stream_attributes (body)
21920 -- system.finalization_implementation (spec)
21921 -- system.finalization_implementation (body)
21922 -- ada.finalization (spec)
21923 -- ada.finalization (body)
21924 -- ada.finalization.list_controller (spec)
21925 -- ada.finalization.list_controller (body)
21926 -- system.file_control_block (spec)
21927 -- system.file_io (spec)
21928 -- system.file_io (body)
21929 -- ada.text_io (spec)
21930 -- ada.text_io (body)
21932 -- END ELABORATION ORDER
21936 -- The following source file name pragmas allow the generated file
21937 -- names to be unique for different main programs. They are needed
21938 -- since the package name will always be Ada_Main.
21940 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21941 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21943 -- Generated package body for Ada_Main starts here
21945 package body ada_main is
21947 -- The actual finalization is performed by calling the
21948 -- library routine in System.Standard_Library.Adafinal
21950 procedure Do_Finalize;
21951 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21958 procedure adainit is
21960 -- These booleans are set to True once the associated unit has
21961 -- been elaborated. It is also used to avoid elaborating the
21962 -- same unit twice.
21965 pragma Import (Ada, E040, "interfaces__c_streams_E");
21968 pragma Import (Ada, E008, "ada__exceptions_E");
21971 pragma Import (Ada, E014, "system__exception_table_E");
21974 pragma Import (Ada, E053, "ada__io_exceptions_E");
21977 pragma Import (Ada, E017, "system__exceptions_E");
21980 pragma Import (Ada, E024, "system__secondary_stack_E");
21983 pragma Import (Ada, E030, "system__stack_checking_E");
21986 pragma Import (Ada, E028, "system__soft_links_E");
21989 pragma Import (Ada, E035, "ada__tags_E");
21992 pragma Import (Ada, E033, "ada__streams_E");
21995 pragma Import (Ada, E046, "system__finalization_root_E");
21998 pragma Import (Ada, E048, "system__finalization_implementation_E");
22001 pragma Import (Ada, E044, "ada__finalization_E");
22004 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22007 pragma Import (Ada, E055, "system__file_control_block_E");
22010 pragma Import (Ada, E042, "system__file_io_E");
22013 pragma Import (Ada, E006, "ada__text_io_E");
22015 -- Set_Globals is a library routine that stores away the
22016 -- value of the indicated set of global values in global
22017 -- variables within the library.
22019 procedure Set_Globals
22020 (Main_Priority : Integer;
22021 Time_Slice_Value : Integer;
22022 WC_Encoding : Character;
22023 Locking_Policy : Character;
22024 Queuing_Policy : Character;
22025 Task_Dispatching_Policy : Character;
22026 Adafinal : System.Address;
22027 Unreserve_All_Interrupts : Integer;
22028 Exception_Tracebacks : Integer);
22029 @findex __gnat_set_globals
22030 pragma Import (C, Set_Globals, "__gnat_set_globals");
22032 -- SDP_Table_Build is a library routine used to build the
22033 -- exception tables. See unit Ada.Exceptions in files
22034 -- a-except.ads/adb for full details of how zero cost
22035 -- exception handling works. This procedure, the call to
22036 -- it, and the two following tables are all omitted if the
22037 -- build is in longjmp/setjmp exception mode.
22039 @findex SDP_Table_Build
22040 @findex Zero Cost Exceptions
22041 procedure SDP_Table_Build
22042 (SDP_Addresses : System.Address;
22043 SDP_Count : Natural;
22044 Elab_Addresses : System.Address;
22045 Elab_Addr_Count : Natural);
22046 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22048 -- Table of Unit_Exception_Table addresses. Used for zero
22049 -- cost exception handling to build the top level table.
22051 ST : aliased constant array (1 .. 23) of System.Address := (
22053 Ada.Text_Io'UET_Address,
22054 Ada.Exceptions'UET_Address,
22055 Gnat.Heap_Sort_A'UET_Address,
22056 System.Exception_Table'UET_Address,
22057 System.Machine_State_Operations'UET_Address,
22058 System.Secondary_Stack'UET_Address,
22059 System.Parameters'UET_Address,
22060 System.Soft_Links'UET_Address,
22061 System.Stack_Checking'UET_Address,
22062 System.Traceback'UET_Address,
22063 Ada.Streams'UET_Address,
22064 Ada.Tags'UET_Address,
22065 System.String_Ops'UET_Address,
22066 Interfaces.C_Streams'UET_Address,
22067 System.File_Io'UET_Address,
22068 Ada.Finalization'UET_Address,
22069 System.Finalization_Root'UET_Address,
22070 System.Finalization_Implementation'UET_Address,
22071 System.String_Ops_Concat_3'UET_Address,
22072 System.Stream_Attributes'UET_Address,
22073 System.File_Control_Block'UET_Address,
22074 Ada.Finalization.List_Controller'UET_Address);
22076 -- Table of addresses of elaboration routines. Used for
22077 -- zero cost exception handling to make sure these
22078 -- addresses are included in the top level procedure
22081 EA : aliased constant array (1 .. 23) of System.Address := (
22082 adainit'Code_Address,
22083 Do_Finalize'Code_Address,
22084 Ada.Exceptions'Elab_Spec'Address,
22085 System.Exceptions'Elab_Spec'Address,
22086 Interfaces.C_Streams'Elab_Spec'Address,
22087 System.Exception_Table'Elab_Body'Address,
22088 Ada.Io_Exceptions'Elab_Spec'Address,
22089 System.Stack_Checking'Elab_Spec'Address,
22090 System.Soft_Links'Elab_Body'Address,
22091 System.Secondary_Stack'Elab_Body'Address,
22092 Ada.Tags'Elab_Spec'Address,
22093 Ada.Tags'Elab_Body'Address,
22094 Ada.Streams'Elab_Spec'Address,
22095 System.Finalization_Root'Elab_Spec'Address,
22096 Ada.Exceptions'Elab_Body'Address,
22097 System.Finalization_Implementation'Elab_Spec'Address,
22098 System.Finalization_Implementation'Elab_Body'Address,
22099 Ada.Finalization'Elab_Spec'Address,
22100 Ada.Finalization.List_Controller'Elab_Spec'Address,
22101 System.File_Control_Block'Elab_Spec'Address,
22102 System.File_Io'Elab_Body'Address,
22103 Ada.Text_Io'Elab_Spec'Address,
22104 Ada.Text_Io'Elab_Body'Address);
22106 -- Start of processing for adainit
22110 -- Call SDP_Table_Build to build the top level procedure
22111 -- table for zero cost exception handling (omitted in
22112 -- longjmp/setjmp mode).
22114 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22116 -- Call Set_Globals to record various information for
22117 -- this partition. The values are derived by the binder
22118 -- from information stored in the ali files by the compiler.
22120 @findex __gnat_set_globals
22122 (Main_Priority => -1,
22123 -- Priority of main program, -1 if no pragma Priority used
22125 Time_Slice_Value => -1,
22126 -- Time slice from Time_Slice pragma, -1 if none used
22128 WC_Encoding => 'b',
22129 -- Wide_Character encoding used, default is brackets
22131 Locking_Policy => ' ',
22132 -- Locking_Policy used, default of space means not
22133 -- specified, otherwise it is the first character of
22134 -- the policy name.
22136 Queuing_Policy => ' ',
22137 -- Queuing_Policy used, default of space means not
22138 -- specified, otherwise it is the first character of
22139 -- the policy name.
22141 Task_Dispatching_Policy => ' ',
22142 -- Task_Dispatching_Policy used, default of space means
22143 -- not specified, otherwise first character of the
22146 Adafinal => System.Null_Address,
22147 -- Address of Adafinal routine, not used anymore
22149 Unreserve_All_Interrupts => 0,
22150 -- Set true if pragma Unreserve_All_Interrupts was used
22152 Exception_Tracebacks => 0);
22153 -- Indicates if exception tracebacks are enabled
22155 Elab_Final_Code := 1;
22157 -- Now we have the elaboration calls for all units in the partition.
22158 -- The Elab_Spec and Elab_Body attributes generate references to the
22159 -- implicit elaboration procedures generated by the compiler for
22160 -- each unit that requires elaboration.
22163 Interfaces.C_Streams'Elab_Spec;
22167 Ada.Exceptions'Elab_Spec;
22170 System.Exception_Table'Elab_Body;
22174 Ada.Io_Exceptions'Elab_Spec;
22178 System.Exceptions'Elab_Spec;
22182 System.Stack_Checking'Elab_Spec;
22185 System.Soft_Links'Elab_Body;
22190 System.Secondary_Stack'Elab_Body;
22194 Ada.Tags'Elab_Spec;
22197 Ada.Tags'Elab_Body;
22201 Ada.Streams'Elab_Spec;
22205 System.Finalization_Root'Elab_Spec;
22209 Ada.Exceptions'Elab_Body;
22213 System.Finalization_Implementation'Elab_Spec;
22216 System.Finalization_Implementation'Elab_Body;
22220 Ada.Finalization'Elab_Spec;
22224 Ada.Finalization.List_Controller'Elab_Spec;
22228 System.File_Control_Block'Elab_Spec;
22232 System.File_Io'Elab_Body;
22236 Ada.Text_Io'Elab_Spec;
22239 Ada.Text_Io'Elab_Body;
22243 Elab_Final_Code := 0;
22251 procedure adafinal is
22260 -- main is actually a function, as in the ANSI C standard,
22261 -- defined to return the exit status. The three parameters
22262 -- are the argument count, argument values and environment
22265 @findex Main Program
22268 argv : System.Address;
22269 envp : System.Address)
22272 -- The initialize routine performs low level system
22273 -- initialization using a standard library routine which
22274 -- sets up signal handling and performs any other
22275 -- required setup. The routine can be found in file
22278 @findex __gnat_initialize
22279 procedure initialize;
22280 pragma Import (C, initialize, "__gnat_initialize");
22282 -- The finalize routine performs low level system
22283 -- finalization using a standard library routine. The
22284 -- routine is found in file a-final.c and in the standard
22285 -- distribution is a dummy routine that does nothing, so
22286 -- really this is a hook for special user finalization.
22288 @findex __gnat_finalize
22289 procedure finalize;
22290 pragma Import (C, finalize, "__gnat_finalize");
22292 -- We get to the main program of the partition by using
22293 -- pragma Import because if we try to with the unit and
22294 -- call it Ada style, then not only do we waste time
22295 -- recompiling it, but also, we don't really know the right
22296 -- switches (e.g.@: identifier character set) to be used
22299 procedure Ada_Main_Program;
22300 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22302 -- Start of processing for main
22305 -- Save global variables
22311 -- Call low level system initialization
22315 -- Call our generated Ada initialization routine
22319 -- This is the point at which we want the debugger to get
22324 -- Now we call the main program of the partition
22328 -- Perform Ada finalization
22332 -- Perform low level system finalization
22336 -- Return the proper exit status
22337 return (gnat_exit_status);
22340 -- This section is entirely comments, so it has no effect on the
22341 -- compilation of the Ada_Main package. It provides the list of
22342 -- object files and linker options, as well as some standard
22343 -- libraries needed for the link. The gnatlink utility parses
22344 -- this b~hello.adb file to read these comment lines to generate
22345 -- the appropriate command line arguments for the call to the
22346 -- system linker. The BEGIN/END lines are used for sentinels for
22347 -- this parsing operation.
22349 -- The exact file names will of course depend on the environment,
22350 -- host/target and location of files on the host system.
22352 @findex Object file list
22353 -- BEGIN Object file/option list
22356 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22357 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22358 -- END Object file/option list
22364 The Ada code in the above example is exactly what is generated by the
22365 binder. We have added comments to more clearly indicate the function
22366 of each part of the generated @code{Ada_Main} package.
22368 The code is standard Ada in all respects, and can be processed by any
22369 tools that handle Ada. In particular, it is possible to use the debugger
22370 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22371 suppose that for reasons that you do not understand, your program is crashing
22372 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22373 you can place a breakpoint on the call:
22375 @smallexample @c ada
22376 Ada.Text_Io'Elab_Body;
22380 and trace the elaboration routine for this package to find out where
22381 the problem might be (more usually of course you would be debugging
22382 elaboration code in your own application).
22384 @node Elaboration Order Handling in GNAT
22385 @appendix Elaboration Order Handling in GNAT
22386 @cindex Order of elaboration
22387 @cindex Elaboration control
22390 * Elaboration Code::
22391 * Checking the Elaboration Order::
22392 * Controlling the Elaboration Order::
22393 * Controlling Elaboration in GNAT - Internal Calls::
22394 * Controlling Elaboration in GNAT - External Calls::
22395 * Default Behavior in GNAT - Ensuring Safety::
22396 * Treatment of Pragma Elaborate::
22397 * Elaboration Issues for Library Tasks::
22398 * Mixing Elaboration Models::
22399 * What to Do If the Default Elaboration Behavior Fails::
22400 * Elaboration for Access-to-Subprogram Values::
22401 * Summary of Procedures for Elaboration Control::
22402 * Other Elaboration Order Considerations::
22406 This chapter describes the handling of elaboration code in Ada and
22407 in GNAT, and discusses how the order of elaboration of program units can
22408 be controlled in GNAT, either automatically or with explicit programming
22411 @node Elaboration Code
22412 @section Elaboration Code
22415 Ada provides rather general mechanisms for executing code at elaboration
22416 time, that is to say before the main program starts executing. Such code arises
22420 @item Initializers for variables.
22421 Variables declared at the library level, in package specs or bodies, can
22422 require initialization that is performed at elaboration time, as in:
22423 @smallexample @c ada
22425 Sqrt_Half : Float := Sqrt (0.5);
22429 @item Package initialization code
22430 Code in a @code{BEGIN-END} section at the outer level of a package body is
22431 executed as part of the package body elaboration code.
22433 @item Library level task allocators
22434 Tasks that are declared using task allocators at the library level
22435 start executing immediately and hence can execute at elaboration time.
22439 Subprogram calls are possible in any of these contexts, which means that
22440 any arbitrary part of the program may be executed as part of the elaboration
22441 code. It is even possible to write a program which does all its work at
22442 elaboration time, with a null main program, although stylistically this
22443 would usually be considered an inappropriate way to structure
22446 An important concern arises in the context of elaboration code:
22447 we have to be sure that it is executed in an appropriate order. What we
22448 have is a series of elaboration code sections, potentially one section
22449 for each unit in the program. It is important that these execute
22450 in the correct order. Correctness here means that, taking the above
22451 example of the declaration of @code{Sqrt_Half},
22452 if some other piece of
22453 elaboration code references @code{Sqrt_Half},
22454 then it must run after the
22455 section of elaboration code that contains the declaration of
22458 There would never be any order of elaboration problem if we made a rule
22459 that whenever you @code{with} a unit, you must elaborate both the spec and body
22460 of that unit before elaborating the unit doing the @code{with}'ing:
22462 @smallexample @c ada
22466 package Unit_2 is @dots{}
22472 would require that both the body and spec of @code{Unit_1} be elaborated
22473 before the spec of @code{Unit_2}. However, a rule like that would be far too
22474 restrictive. In particular, it would make it impossible to have routines
22475 in separate packages that were mutually recursive.
22477 You might think that a clever enough compiler could look at the actual
22478 elaboration code and determine an appropriate correct order of elaboration,
22479 but in the general case, this is not possible. Consider the following
22482 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22484 the variable @code{Sqrt_1}, which is declared in the elaboration code
22485 of the body of @code{Unit_1}:
22487 @smallexample @c ada
22489 Sqrt_1 : Float := Sqrt (0.1);
22494 The elaboration code of the body of @code{Unit_1} also contains:
22496 @smallexample @c ada
22499 if expression_1 = 1 then
22500 Q := Unit_2.Func_2;
22507 @code{Unit_2} is exactly parallel,
22508 it has a procedure @code{Func_2} that references
22509 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22510 the body @code{Unit_2}:
22512 @smallexample @c ada
22514 Sqrt_2 : Float := Sqrt (0.1);
22519 The elaboration code of the body of @code{Unit_2} also contains:
22521 @smallexample @c ada
22524 if expression_2 = 2 then
22525 Q := Unit_1.Func_1;
22532 Now the question is, which of the following orders of elaboration is
22557 If you carefully analyze the flow here, you will see that you cannot tell
22558 at compile time the answer to this question.
22559 If @code{expression_1} is not equal to 1,
22560 and @code{expression_2} is not equal to 2,
22561 then either order is acceptable, because neither of the function calls is
22562 executed. If both tests evaluate to true, then neither order is acceptable
22563 and in fact there is no correct order.
22565 If one of the two expressions is true, and the other is false, then one
22566 of the above orders is correct, and the other is incorrect. For example,
22567 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22568 then the call to @code{Func_1}
22569 will occur, but not the call to @code{Func_2.}
22570 This means that it is essential
22571 to elaborate the body of @code{Unit_1} before
22572 the body of @code{Unit_2}, so the first
22573 order of elaboration is correct and the second is wrong.
22575 By making @code{expression_1} and @code{expression_2}
22576 depend on input data, or perhaps
22577 the time of day, we can make it impossible for the compiler or binder
22578 to figure out which of these expressions will be true, and hence it
22579 is impossible to guarantee a safe order of elaboration at run time.
22581 @node Checking the Elaboration Order
22582 @section Checking the Elaboration Order
22585 In some languages that involve the same kind of elaboration problems,
22586 e.g.@: Java and C++, the programmer is expected to worry about these
22587 ordering problems himself, and it is common to
22588 write a program in which an incorrect elaboration order gives
22589 surprising results, because it references variables before they
22591 Ada is designed to be a safe language, and a programmer-beware approach is
22592 clearly not sufficient. Consequently, the language provides three lines
22596 @item Standard rules
22597 Some standard rules restrict the possible choice of elaboration
22598 order. In particular, if you @code{with} a unit, then its spec is always
22599 elaborated before the unit doing the @code{with}. Similarly, a parent
22600 spec is always elaborated before the child spec, and finally
22601 a spec is always elaborated before its corresponding body.
22603 @item Dynamic elaboration checks
22604 @cindex Elaboration checks
22605 @cindex Checks, elaboration
22606 Dynamic checks are made at run time, so that if some entity is accessed
22607 before it is elaborated (typically by means of a subprogram call)
22608 then the exception (@code{Program_Error}) is raised.
22610 @item Elaboration control
22611 Facilities are provided for the programmer to specify the desired order
22615 Let's look at these facilities in more detail. First, the rules for
22616 dynamic checking. One possible rule would be simply to say that the
22617 exception is raised if you access a variable which has not yet been
22618 elaborated. The trouble with this approach is that it could require
22619 expensive checks on every variable reference. Instead Ada has two
22620 rules which are a little more restrictive, but easier to check, and
22624 @item Restrictions on calls
22625 A subprogram can only be called at elaboration time if its body
22626 has been elaborated. The rules for elaboration given above guarantee
22627 that the spec of the subprogram has been elaborated before the
22628 call, but not the body. If this rule is violated, then the
22629 exception @code{Program_Error} is raised.
22631 @item Restrictions on instantiations
22632 A generic unit can only be instantiated if the body of the generic
22633 unit has been elaborated. Again, the rules for elaboration given above
22634 guarantee that the spec of the generic unit has been elaborated
22635 before the instantiation, but not the body. If this rule is
22636 violated, then the exception @code{Program_Error} is raised.
22640 The idea is that if the body has been elaborated, then any variables
22641 it references must have been elaborated; by checking for the body being
22642 elaborated we guarantee that none of its references causes any
22643 trouble. As we noted above, this is a little too restrictive, because a
22644 subprogram that has no non-local references in its body may in fact be safe
22645 to call. However, it really would be unsafe to rely on this, because
22646 it would mean that the caller was aware of details of the implementation
22647 in the body. This goes against the basic tenets of Ada.
22649 A plausible implementation can be described as follows.
22650 A Boolean variable is associated with each subprogram
22651 and each generic unit. This variable is initialized to False, and is set to
22652 True at the point body is elaborated. Every call or instantiation checks the
22653 variable, and raises @code{Program_Error} if the variable is False.
22655 Note that one might think that it would be good enough to have one Boolean
22656 variable for each package, but that would not deal with cases of trying
22657 to call a body in the same package as the call
22658 that has not been elaborated yet.
22659 Of course a compiler may be able to do enough analysis to optimize away
22660 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22661 does such optimizations, but still the easiest conceptual model is to
22662 think of there being one variable per subprogram.
22664 @node Controlling the Elaboration Order
22665 @section Controlling the Elaboration Order
22668 In the previous section we discussed the rules in Ada which ensure
22669 that @code{Program_Error} is raised if an incorrect elaboration order is
22670 chosen. This prevents erroneous executions, but we need mechanisms to
22671 specify a correct execution and avoid the exception altogether.
22672 To achieve this, Ada provides a number of features for controlling
22673 the order of elaboration. We discuss these features in this section.
22675 First, there are several ways of indicating to the compiler that a given
22676 unit has no elaboration problems:
22679 @item packages that do not require a body
22680 A library package that does not require a body does not permit
22681 a body (this rule was introduced in Ada 95).
22682 Thus if we have a such a package, as in:
22684 @smallexample @c ada
22687 package Definitions is
22689 type m is new integer;
22691 type a is array (1 .. 10) of m;
22692 type b is array (1 .. 20) of m;
22700 A package that @code{with}'s @code{Definitions} may safely instantiate
22701 @code{Definitions.Subp} because the compiler can determine that there
22702 definitely is no package body to worry about in this case
22705 @cindex pragma Pure
22707 Places sufficient restrictions on a unit to guarantee that
22708 no call to any subprogram in the unit can result in an
22709 elaboration problem. This means that the compiler does not need
22710 to worry about the point of elaboration of such units, and in
22711 particular, does not need to check any calls to any subprograms
22714 @item pragma Preelaborate
22715 @findex Preelaborate
22716 @cindex pragma Preelaborate
22717 This pragma places slightly less stringent restrictions on a unit than
22719 but these restrictions are still sufficient to ensure that there
22720 are no elaboration problems with any calls to the unit.
22722 @item pragma Elaborate_Body
22723 @findex Elaborate_Body
22724 @cindex pragma Elaborate_Body
22725 This pragma requires that the body of a unit be elaborated immediately
22726 after its spec. Suppose a unit @code{A} has such a pragma,
22727 and unit @code{B} does
22728 a @code{with} of unit @code{A}. Recall that the standard rules require
22729 the spec of unit @code{A}
22730 to be elaborated before the @code{with}'ing unit; given the pragma in
22731 @code{A}, we also know that the body of @code{A}
22732 will be elaborated before @code{B}, so
22733 that calls to @code{A} are safe and do not need a check.
22738 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22740 @code{Elaborate_Body} does not guarantee that the program is
22741 free of elaboration problems, because it may not be possible
22742 to satisfy the requested elaboration order.
22743 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22745 marks @code{Unit_1} as @code{Elaborate_Body},
22746 and not @code{Unit_2,} then the order of
22747 elaboration will be:
22759 Now that means that the call to @code{Func_1} in @code{Unit_2}
22760 need not be checked,
22761 it must be safe. But the call to @code{Func_2} in
22762 @code{Unit_1} may still fail if
22763 @code{Expression_1} is equal to 1,
22764 and the programmer must still take
22765 responsibility for this not being the case.
22767 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22768 eliminated, except for calls entirely within a body, which are
22769 in any case fully under programmer control. However, using the pragma
22770 everywhere is not always possible.
22771 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22772 we marked both of them as having pragma @code{Elaborate_Body}, then
22773 clearly there would be no possible elaboration order.
22775 The above pragmas allow a server to guarantee safe use by clients, and
22776 clearly this is the preferable approach. Consequently a good rule
22777 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22778 and if this is not possible,
22779 mark them as @code{Elaborate_Body} if possible.
22780 As we have seen, there are situations where neither of these
22781 three pragmas can be used.
22782 So we also provide methods for clients to control the
22783 order of elaboration of the servers on which they depend:
22786 @item pragma Elaborate (unit)
22788 @cindex pragma Elaborate
22789 This pragma is placed in the context clause, after a @code{with} clause,
22790 and it requires that the body of the named unit be elaborated before
22791 the unit in which the pragma occurs. The idea is to use this pragma
22792 if the current unit calls at elaboration time, directly or indirectly,
22793 some subprogram in the named unit.
22795 @item pragma Elaborate_All (unit)
22796 @findex Elaborate_All
22797 @cindex pragma Elaborate_All
22798 This is a stronger version of the Elaborate pragma. Consider the
22802 Unit A @code{with}'s unit B and calls B.Func in elab code
22803 Unit B @code{with}'s unit C, and B.Func calls C.Func
22807 Now if we put a pragma @code{Elaborate (B)}
22808 in unit @code{A}, this ensures that the
22809 body of @code{B} is elaborated before the call, but not the
22810 body of @code{C}, so
22811 the call to @code{C.Func} could still cause @code{Program_Error} to
22814 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22815 not only that the body of the named unit be elaborated before the
22816 unit doing the @code{with}, but also the bodies of all units that the
22817 named unit uses, following @code{with} links transitively. For example,
22818 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22820 not only that the body of @code{B} be elaborated before @code{A},
22822 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22826 We are now in a position to give a usage rule in Ada for avoiding
22827 elaboration problems, at least if dynamic dispatching and access to
22828 subprogram values are not used. We will handle these cases separately
22831 The rule is simple. If a unit has elaboration code that can directly or
22832 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22833 a generic package in a @code{with}'ed unit,
22834 then if the @code{with}'ed unit does not have
22835 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22836 a pragma @code{Elaborate_All}
22837 for the @code{with}'ed unit. By following this rule a client is
22838 assured that calls can be made without risk of an exception.
22840 For generic subprogram instantiations, the rule can be relaxed to
22841 require only a pragma @code{Elaborate} since elaborating the body
22842 of a subprogram cannot cause any transitive elaboration (we are
22843 not calling the subprogram in this case, just elaborating its
22846 If this rule is not followed, then a program may be in one of four
22850 @item No order exists
22851 No order of elaboration exists which follows the rules, taking into
22852 account any @code{Elaborate}, @code{Elaborate_All},
22853 or @code{Elaborate_Body} pragmas. In
22854 this case, an Ada compiler must diagnose the situation at bind
22855 time, and refuse to build an executable program.
22857 @item One or more orders exist, all incorrect
22858 One or more acceptable elaboration orders exist, and all of them
22859 generate an elaboration order problem. In this case, the binder
22860 can build an executable program, but @code{Program_Error} will be raised
22861 when the program is run.
22863 @item Several orders exist, some right, some incorrect
22864 One or more acceptable elaboration orders exists, and some of them
22865 work, and some do not. The programmer has not controlled
22866 the order of elaboration, so the binder may or may not pick one of
22867 the correct orders, and the program may or may not raise an
22868 exception when it is run. This is the worst case, because it means
22869 that the program may fail when moved to another compiler, or even
22870 another version of the same compiler.
22872 @item One or more orders exists, all correct
22873 One ore more acceptable elaboration orders exist, and all of them
22874 work. In this case the program runs successfully. This state of
22875 affairs can be guaranteed by following the rule we gave above, but
22876 may be true even if the rule is not followed.
22880 Note that one additional advantage of following our rules on the use
22881 of @code{Elaborate} and @code{Elaborate_All}
22882 is that the program continues to stay in the ideal (all orders OK) state
22883 even if maintenance
22884 changes some bodies of some units. Conversely, if a program that does
22885 not follow this rule happens to be safe at some point, this state of affairs
22886 may deteriorate silently as a result of maintenance changes.
22888 You may have noticed that the above discussion did not mention
22889 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22890 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22891 code in the body makes calls to some other unit, so it is still necessary
22892 to use @code{Elaborate_All} on such units.
22894 @node Controlling Elaboration in GNAT - Internal Calls
22895 @section Controlling Elaboration in GNAT - Internal Calls
22898 In the case of internal calls, i.e., calls within a single package, the
22899 programmer has full control over the order of elaboration, and it is up
22900 to the programmer to elaborate declarations in an appropriate order. For
22903 @smallexample @c ada
22906 function One return Float;
22910 function One return Float is
22919 will obviously raise @code{Program_Error} at run time, because function
22920 One will be called before its body is elaborated. In this case GNAT will
22921 generate a warning that the call will raise @code{Program_Error}:
22927 2. function One return Float;
22929 4. Q : Float := One;
22931 >>> warning: cannot call "One" before body is elaborated
22932 >>> warning: Program_Error will be raised at run time
22935 6. function One return Float is
22948 Note that in this particular case, it is likely that the call is safe, because
22949 the function @code{One} does not access any global variables.
22950 Nevertheless in Ada, we do not want the validity of the check to depend on
22951 the contents of the body (think about the separate compilation case), so this
22952 is still wrong, as we discussed in the previous sections.
22954 The error is easily corrected by rearranging the declarations so that the
22955 body of @code{One} appears before the declaration containing the call
22956 (note that in Ada 95 and Ada 2005,
22957 declarations can appear in any order, so there is no restriction that
22958 would prevent this reordering, and if we write:
22960 @smallexample @c ada
22963 function One return Float;
22965 function One return Float is
22976 then all is well, no warning is generated, and no
22977 @code{Program_Error} exception
22979 Things are more complicated when a chain of subprograms is executed:
22981 @smallexample @c ada
22984 function A return Integer;
22985 function B return Integer;
22986 function C return Integer;
22988 function B return Integer is begin return A; end;
22989 function C return Integer is begin return B; end;
22993 function A return Integer is begin return 1; end;
22999 Now the call to @code{C}
23000 at elaboration time in the declaration of @code{X} is correct, because
23001 the body of @code{C} is already elaborated,
23002 and the call to @code{B} within the body of
23003 @code{C} is correct, but the call
23004 to @code{A} within the body of @code{B} is incorrect, because the body
23005 of @code{A} has not been elaborated, so @code{Program_Error}
23006 will be raised on the call to @code{A}.
23007 In this case GNAT will generate a
23008 warning that @code{Program_Error} may be
23009 raised at the point of the call. Let's look at the warning:
23015 2. function A return Integer;
23016 3. function B return Integer;
23017 4. function C return Integer;
23019 6. function B return Integer is begin return A; end;
23021 >>> warning: call to "A" before body is elaborated may
23022 raise Program_Error
23023 >>> warning: "B" called at line 7
23024 >>> warning: "C" called at line 9
23026 7. function C return Integer is begin return B; end;
23028 9. X : Integer := C;
23030 11. function A return Integer is begin return 1; end;
23040 Note that the message here says ``may raise'', instead of the direct case,
23041 where the message says ``will be raised''. That's because whether
23043 actually called depends in general on run-time flow of control.
23044 For example, if the body of @code{B} said
23046 @smallexample @c ada
23049 function B return Integer is
23051 if some-condition-depending-on-input-data then
23062 then we could not know until run time whether the incorrect call to A would
23063 actually occur, so @code{Program_Error} might
23064 or might not be raised. It is possible for a compiler to
23065 do a better job of analyzing bodies, to
23066 determine whether or not @code{Program_Error}
23067 might be raised, but it certainly
23068 couldn't do a perfect job (that would require solving the halting problem
23069 and is provably impossible), and because this is a warning anyway, it does
23070 not seem worth the effort to do the analysis. Cases in which it
23071 would be relevant are rare.
23073 In practice, warnings of either of the forms given
23074 above will usually correspond to
23075 real errors, and should be examined carefully and eliminated.
23076 In the rare case where a warning is bogus, it can be suppressed by any of
23077 the following methods:
23081 Compile with the @option{-gnatws} switch set
23084 Suppress @code{Elaboration_Check} for the called subprogram
23087 Use pragma @code{Warnings_Off} to turn warnings off for the call
23091 For the internal elaboration check case,
23092 GNAT by default generates the
23093 necessary run-time checks to ensure
23094 that @code{Program_Error} is raised if any
23095 call fails an elaboration check. Of course this can only happen if a
23096 warning has been issued as described above. The use of pragma
23097 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23098 some of these checks, meaning that it may be possible (but is not
23099 guaranteed) for a program to be able to call a subprogram whose body
23100 is not yet elaborated, without raising a @code{Program_Error} exception.
23102 @node Controlling Elaboration in GNAT - External Calls
23103 @section Controlling Elaboration in GNAT - External Calls
23106 The previous section discussed the case in which the execution of a
23107 particular thread of elaboration code occurred entirely within a
23108 single unit. This is the easy case to handle, because a programmer
23109 has direct and total control over the order of elaboration, and
23110 furthermore, checks need only be generated in cases which are rare
23111 and which the compiler can easily detect.
23112 The situation is more complex when separate compilation is taken into account.
23113 Consider the following:
23115 @smallexample @c ada
23119 function Sqrt (Arg : Float) return Float;
23122 package body Math is
23123 function Sqrt (Arg : Float) return Float is
23132 X : Float := Math.Sqrt (0.5);
23145 where @code{Main} is the main program. When this program is executed, the
23146 elaboration code must first be executed, and one of the jobs of the
23147 binder is to determine the order in which the units of a program are
23148 to be elaborated. In this case we have four units: the spec and body
23150 the spec of @code{Stuff} and the body of @code{Main}).
23151 In what order should the four separate sections of elaboration code
23154 There are some restrictions in the order of elaboration that the binder
23155 can choose. In particular, if unit U has a @code{with}
23156 for a package @code{X}, then you
23157 are assured that the spec of @code{X}
23158 is elaborated before U , but you are
23159 not assured that the body of @code{X}
23160 is elaborated before U.
23161 This means that in the above case, the binder is allowed to choose the
23172 but that's not good, because now the call to @code{Math.Sqrt}
23173 that happens during
23174 the elaboration of the @code{Stuff}
23175 spec happens before the body of @code{Math.Sqrt} is
23176 elaborated, and hence causes @code{Program_Error} exception to be raised.
23177 At first glance, one might say that the binder is misbehaving, because
23178 obviously you want to elaborate the body of something you @code{with}
23180 that is not a general rule that can be followed in all cases. Consider
23182 @smallexample @c ada
23185 package X is @dots{}
23187 package Y is @dots{}
23190 package body Y is @dots{}
23193 package body X is @dots{}
23199 This is a common arrangement, and, apart from the order of elaboration
23200 problems that might arise in connection with elaboration code, this works fine.
23201 A rule that says that you must first elaborate the body of anything you
23202 @code{with} cannot work in this case:
23203 the body of @code{X} @code{with}'s @code{Y},
23204 which means you would have to
23205 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23207 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23208 loop that cannot be broken.
23210 It is true that the binder can in many cases guess an order of elaboration
23211 that is unlikely to cause a @code{Program_Error}
23212 exception to be raised, and it tries to do so (in the
23213 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23215 elaborate the body of @code{Math} right after its spec, so all will be well).
23217 However, a program that blindly relies on the binder to be helpful can
23218 get into trouble, as we discussed in the previous sections, so
23220 provides a number of facilities for assisting the programmer in
23221 developing programs that are robust with respect to elaboration order.
23223 @node Default Behavior in GNAT - Ensuring Safety
23224 @section Default Behavior in GNAT - Ensuring Safety
23227 The default behavior in GNAT ensures elaboration safety. In its
23228 default mode GNAT implements the
23229 rule we previously described as the right approach. Let's restate it:
23233 @emph{If a unit has elaboration code that can directly or indirectly make a
23234 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23235 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23236 does not have pragma @code{Pure} or
23237 @code{Preelaborate}, then the client should have an
23238 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23240 @emph{In the case of instantiating a generic subprogram, it is always
23241 sufficient to have only an @code{Elaborate} pragma for the
23242 @code{with}'ed unit.}
23246 By following this rule a client is assured that calls and instantiations
23247 can be made without risk of an exception.
23249 In this mode GNAT traces all calls that are potentially made from
23250 elaboration code, and puts in any missing implicit @code{Elaborate}
23251 and @code{Elaborate_All} pragmas.
23252 The advantage of this approach is that no elaboration problems
23253 are possible if the binder can find an elaboration order that is
23254 consistent with these implicit @code{Elaborate} and
23255 @code{Elaborate_All} pragmas. The
23256 disadvantage of this approach is that no such order may exist.
23258 If the binder does not generate any diagnostics, then it means that it has
23259 found an elaboration order that is guaranteed to be safe. However, the binder
23260 may still be relying on implicitly generated @code{Elaborate} and
23261 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23264 If it is important to guarantee portability, then the compilations should
23267 (warn on elaboration problems) switch. This will cause warning messages
23268 to be generated indicating the missing @code{Elaborate} and
23269 @code{Elaborate_All} pragmas.
23270 Consider the following source program:
23272 @smallexample @c ada
23277 m : integer := k.r;
23284 where it is clear that there
23285 should be a pragma @code{Elaborate_All}
23286 for unit @code{k}. An implicit pragma will be generated, and it is
23287 likely that the binder will be able to honor it. However, if you want
23288 to port this program to some other Ada compiler than GNAT.
23289 it is safer to include the pragma explicitly in the source. If this
23290 unit is compiled with the
23292 switch, then the compiler outputs a warning:
23299 3. m : integer := k.r;
23301 >>> warning: call to "r" may raise Program_Error
23302 >>> warning: missing pragma Elaborate_All for "k"
23310 and these warnings can be used as a guide for supplying manually
23311 the missing pragmas. It is usually a bad idea to use this warning
23312 option during development. That's because it will warn you when
23313 you need to put in a pragma, but cannot warn you when it is time
23314 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23315 unnecessary dependencies and even false circularities.
23317 This default mode is more restrictive than the Ada Reference
23318 Manual, and it is possible to construct programs which will compile
23319 using the dynamic model described there, but will run into a
23320 circularity using the safer static model we have described.
23322 Of course any Ada compiler must be able to operate in a mode
23323 consistent with the requirements of the Ada Reference Manual,
23324 and in particular must have the capability of implementing the
23325 standard dynamic model of elaboration with run-time checks.
23327 In GNAT, this standard mode can be achieved either by the use of
23328 the @option{-gnatE} switch on the compiler (@command{gcc} or
23329 @command{gnatmake}) command, or by the use of the configuration pragma:
23331 @smallexample @c ada
23332 pragma Elaboration_Checks (DYNAMIC);
23336 Either approach will cause the unit affected to be compiled using the
23337 standard dynamic run-time elaboration checks described in the Ada
23338 Reference Manual. The static model is generally preferable, since it
23339 is clearly safer to rely on compile and link time checks rather than
23340 run-time checks. However, in the case of legacy code, it may be
23341 difficult to meet the requirements of the static model. This
23342 issue is further discussed in
23343 @ref{What to Do If the Default Elaboration Behavior Fails}.
23345 Note that the static model provides a strict subset of the allowed
23346 behavior and programs of the Ada Reference Manual, so if you do
23347 adhere to the static model and no circularities exist,
23348 then you are assured that your program will
23349 work using the dynamic model, providing that you remove any
23350 pragma Elaborate statements from the source.
23352 @node Treatment of Pragma Elaborate
23353 @section Treatment of Pragma Elaborate
23354 @cindex Pragma Elaborate
23357 The use of @code{pragma Elaborate}
23358 should generally be avoided in Ada 95 and Ada 2005 programs,
23359 since there is no guarantee that transitive calls
23360 will be properly handled. Indeed at one point, this pragma was placed
23361 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23363 Now that's a bit restrictive. In practice, the case in which
23364 @code{pragma Elaborate} is useful is when the caller knows that there
23365 are no transitive calls, or that the called unit contains all necessary
23366 transitive @code{pragma Elaborate} statements, and legacy code often
23367 contains such uses.
23369 Strictly speaking the static mode in GNAT should ignore such pragmas,
23370 since there is no assurance at compile time that the necessary safety
23371 conditions are met. In practice, this would cause GNAT to be incompatible
23372 with correctly written Ada 83 code that had all necessary
23373 @code{pragma Elaborate} statements in place. Consequently, we made the
23374 decision that GNAT in its default mode will believe that if it encounters
23375 a @code{pragma Elaborate} then the programmer knows what they are doing,
23376 and it will trust that no elaboration errors can occur.
23378 The result of this decision is two-fold. First to be safe using the
23379 static mode, you should remove all @code{pragma Elaborate} statements.
23380 Second, when fixing circularities in existing code, you can selectively
23381 use @code{pragma Elaborate} statements to convince the static mode of
23382 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23385 When using the static mode with @option{-gnatwl}, any use of
23386 @code{pragma Elaborate} will generate a warning about possible
23389 @node Elaboration Issues for Library Tasks
23390 @section Elaboration Issues for Library Tasks
23391 @cindex Library tasks, elaboration issues
23392 @cindex Elaboration of library tasks
23395 In this section we examine special elaboration issues that arise for
23396 programs that declare library level tasks.
23398 Generally the model of execution of an Ada program is that all units are
23399 elaborated, and then execution of the program starts. However, the
23400 declaration of library tasks definitely does not fit this model. The
23401 reason for this is that library tasks start as soon as they are declared
23402 (more precisely, as soon as the statement part of the enclosing package
23403 body is reached), that is to say before elaboration
23404 of the program is complete. This means that if such a task calls a
23405 subprogram, or an entry in another task, the callee may or may not be
23406 elaborated yet, and in the standard
23407 Reference Manual model of dynamic elaboration checks, you can even
23408 get timing dependent Program_Error exceptions, since there can be
23409 a race between the elaboration code and the task code.
23411 The static model of elaboration in GNAT seeks to avoid all such
23412 dynamic behavior, by being conservative, and the conservative
23413 approach in this particular case is to assume that all the code
23414 in a task body is potentially executed at elaboration time if
23415 a task is declared at the library level.
23417 This can definitely result in unexpected circularities. Consider
23418 the following example
23420 @smallexample @c ada
23426 type My_Int is new Integer;
23428 function Ident (M : My_Int) return My_Int;
23432 package body Decls is
23433 task body Lib_Task is
23439 function Ident (M : My_Int) return My_Int is
23447 procedure Put_Val (Arg : Decls.My_Int);
23451 package body Utils is
23452 procedure Put_Val (Arg : Decls.My_Int) is
23454 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23461 Decls.Lib_Task.Start;
23466 If the above example is compiled in the default static elaboration
23467 mode, then a circularity occurs. The circularity comes from the call
23468 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23469 this call occurs in elaboration code, we need an implicit pragma
23470 @code{Elaborate_All} for @code{Utils}. This means that not only must
23471 the spec and body of @code{Utils} be elaborated before the body
23472 of @code{Decls}, but also the spec and body of any unit that is
23473 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23474 the body of @code{Decls}. This is the transitive implication of
23475 pragma @code{Elaborate_All} and it makes sense, because in general
23476 the body of @code{Put_Val} might have a call to something in a
23477 @code{with'ed} unit.
23479 In this case, the body of Utils (actually its spec) @code{with's}
23480 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23481 must be elaborated before itself, in case there is a call from the
23482 body of @code{Utils}.
23484 Here is the exact chain of events we are worrying about:
23488 In the body of @code{Decls} a call is made from within the body of a library
23489 task to a subprogram in the package @code{Utils}. Since this call may
23490 occur at elaboration time (given that the task is activated at elaboration
23491 time), we have to assume the worst, i.e., that the
23492 call does happen at elaboration time.
23495 This means that the body and spec of @code{Util} must be elaborated before
23496 the body of @code{Decls} so that this call does not cause an access before
23500 Within the body of @code{Util}, specifically within the body of
23501 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23505 One such @code{with}'ed package is package @code{Decls}, so there
23506 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23507 In fact there is such a call in this example, but we would have to
23508 assume that there was such a call even if it were not there, since
23509 we are not supposed to write the body of @code{Decls} knowing what
23510 is in the body of @code{Utils}; certainly in the case of the
23511 static elaboration model, the compiler does not know what is in
23512 other bodies and must assume the worst.
23515 This means that the spec and body of @code{Decls} must also be
23516 elaborated before we elaborate the unit containing the call, but
23517 that unit is @code{Decls}! This means that the body of @code{Decls}
23518 must be elaborated before itself, and that's a circularity.
23522 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23523 the body of @code{Decls} you will get a true Ada Reference Manual
23524 circularity that makes the program illegal.
23526 In practice, we have found that problems with the static model of
23527 elaboration in existing code often arise from library tasks, so
23528 we must address this particular situation.
23530 Note that if we compile and run the program above, using the dynamic model of
23531 elaboration (that is to say use the @option{-gnatE} switch),
23532 then it compiles, binds,
23533 links, and runs, printing the expected result of 2. Therefore in some sense
23534 the circularity here is only apparent, and we need to capture
23535 the properties of this program that distinguish it from other library-level
23536 tasks that have real elaboration problems.
23538 We have four possible answers to this question:
23543 Use the dynamic model of elaboration.
23545 If we use the @option{-gnatE} switch, then as noted above, the program works.
23546 Why is this? If we examine the task body, it is apparent that the task cannot
23548 @code{accept} statement until after elaboration has been completed, because
23549 the corresponding entry call comes from the main program, not earlier.
23550 This is why the dynamic model works here. But that's really giving
23551 up on a precise analysis, and we prefer to take this approach only if we cannot
23553 problem in any other manner. So let us examine two ways to reorganize
23554 the program to avoid the potential elaboration problem.
23557 Split library tasks into separate packages.
23559 Write separate packages, so that library tasks are isolated from
23560 other declarations as much as possible. Let us look at a variation on
23563 @smallexample @c ada
23571 package body Decls1 is
23572 task body Lib_Task is
23580 type My_Int is new Integer;
23581 function Ident (M : My_Int) return My_Int;
23585 package body Decls2 is
23586 function Ident (M : My_Int) return My_Int is
23594 procedure Put_Val (Arg : Decls2.My_Int);
23598 package body Utils is
23599 procedure Put_Val (Arg : Decls2.My_Int) is
23601 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23608 Decls1.Lib_Task.Start;
23613 All we have done is to split @code{Decls} into two packages, one
23614 containing the library task, and one containing everything else. Now
23615 there is no cycle, and the program compiles, binds, links and executes
23616 using the default static model of elaboration.
23619 Declare separate task types.
23621 A significant part of the problem arises because of the use of the
23622 single task declaration form. This means that the elaboration of
23623 the task type, and the elaboration of the task itself (i.e.@: the
23624 creation of the task) happen at the same time. A good rule
23625 of style in Ada is to always create explicit task types. By
23626 following the additional step of placing task objects in separate
23627 packages from the task type declaration, many elaboration problems
23628 are avoided. Here is another modified example of the example program:
23630 @smallexample @c ada
23632 task type Lib_Task_Type is
23636 type My_Int is new Integer;
23638 function Ident (M : My_Int) return My_Int;
23642 package body Decls is
23643 task body Lib_Task_Type is
23649 function Ident (M : My_Int) return My_Int is
23657 procedure Put_Val (Arg : Decls.My_Int);
23661 package body Utils is
23662 procedure Put_Val (Arg : Decls.My_Int) is
23664 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23670 Lib_Task : Decls.Lib_Task_Type;
23676 Declst.Lib_Task.Start;
23681 What we have done here is to replace the @code{task} declaration in
23682 package @code{Decls} with a @code{task type} declaration. Then we
23683 introduce a separate package @code{Declst} to contain the actual
23684 task object. This separates the elaboration issues for
23685 the @code{task type}
23686 declaration, which causes no trouble, from the elaboration issues
23687 of the task object, which is also unproblematic, since it is now independent
23688 of the elaboration of @code{Utils}.
23689 This separation of concerns also corresponds to
23690 a generally sound engineering principle of separating declarations
23691 from instances. This version of the program also compiles, binds, links,
23692 and executes, generating the expected output.
23695 Use No_Entry_Calls_In_Elaboration_Code restriction.
23696 @cindex No_Entry_Calls_In_Elaboration_Code
23698 The previous two approaches described how a program can be restructured
23699 to avoid the special problems caused by library task bodies. in practice,
23700 however, such restructuring may be difficult to apply to existing legacy code,
23701 so we must consider solutions that do not require massive rewriting.
23703 Let us consider more carefully why our original sample program works
23704 under the dynamic model of elaboration. The reason is that the code
23705 in the task body blocks immediately on the @code{accept}
23706 statement. Now of course there is nothing to prohibit elaboration
23707 code from making entry calls (for example from another library level task),
23708 so we cannot tell in isolation that
23709 the task will not execute the accept statement during elaboration.
23711 However, in practice it is very unusual to see elaboration code
23712 make any entry calls, and the pattern of tasks starting
23713 at elaboration time and then immediately blocking on @code{accept} or
23714 @code{select} statements is very common. What this means is that
23715 the compiler is being too pessimistic when it analyzes the
23716 whole package body as though it might be executed at elaboration
23719 If we know that the elaboration code contains no entry calls, (a very safe
23720 assumption most of the time, that could almost be made the default
23721 behavior), then we can compile all units of the program under control
23722 of the following configuration pragma:
23725 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23729 This pragma can be placed in the @file{gnat.adc} file in the usual
23730 manner. If we take our original unmodified program and compile it
23731 in the presence of a @file{gnat.adc} containing the above pragma,
23732 then once again, we can compile, bind, link, and execute, obtaining
23733 the expected result. In the presence of this pragma, the compiler does
23734 not trace calls in a task body, that appear after the first @code{accept}
23735 or @code{select} statement, and therefore does not report a potential
23736 circularity in the original program.
23738 The compiler will check to the extent it can that the above
23739 restriction is not violated, but it is not always possible to do a
23740 complete check at compile time, so it is important to use this
23741 pragma only if the stated restriction is in fact met, that is to say
23742 no task receives an entry call before elaboration of all units is completed.
23746 @node Mixing Elaboration Models
23747 @section Mixing Elaboration Models
23749 So far, we have assumed that the entire program is either compiled
23750 using the dynamic model or static model, ensuring consistency. It
23751 is possible to mix the two models, but rules have to be followed
23752 if this mixing is done to ensure that elaboration checks are not
23755 The basic rule is that @emph{a unit compiled with the static model cannot
23756 be @code{with'ed} by a unit compiled with the dynamic model}. The
23757 reason for this is that in the static model, a unit assumes that
23758 its clients guarantee to use (the equivalent of) pragma
23759 @code{Elaborate_All} so that no elaboration checks are required
23760 in inner subprograms, and this assumption is violated if the
23761 client is compiled with dynamic checks.
23763 The precise rule is as follows. A unit that is compiled with dynamic
23764 checks can only @code{with} a unit that meets at least one of the
23765 following criteria:
23770 The @code{with'ed} unit is itself compiled with dynamic elaboration
23771 checks (that is with the @option{-gnatE} switch.
23774 The @code{with'ed} unit is an internal GNAT implementation unit from
23775 the System, Interfaces, Ada, or GNAT hierarchies.
23778 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23781 The @code{with'ing} unit (that is the client) has an explicit pragma
23782 @code{Elaborate_All} for the @code{with'ed} unit.
23787 If this rule is violated, that is if a unit with dynamic elaboration
23788 checks @code{with's} a unit that does not meet one of the above four
23789 criteria, then the binder (@code{gnatbind}) will issue a warning
23790 similar to that in the following example:
23793 warning: "x.ads" has dynamic elaboration checks and with's
23794 warning: "y.ads" which has static elaboration checks
23798 These warnings indicate that the rule has been violated, and that as a result
23799 elaboration checks may be missed in the resulting executable file.
23800 This warning may be suppressed using the @option{-ws} binder switch
23801 in the usual manner.
23803 One useful application of this mixing rule is in the case of a subsystem
23804 which does not itself @code{with} units from the remainder of the
23805 application. In this case, the entire subsystem can be compiled with
23806 dynamic checks to resolve a circularity in the subsystem, while
23807 allowing the main application that uses this subsystem to be compiled
23808 using the more reliable default static model.
23810 @node What to Do If the Default Elaboration Behavior Fails
23811 @section What to Do If the Default Elaboration Behavior Fails
23814 If the binder cannot find an acceptable order, it outputs detailed
23815 diagnostics. For example:
23821 error: elaboration circularity detected
23822 info: "proc (body)" must be elaborated before "pack (body)"
23823 info: reason: Elaborate_All probably needed in unit "pack (body)"
23824 info: recompile "pack (body)" with -gnatwl
23825 info: for full details
23826 info: "proc (body)"
23827 info: is needed by its spec:
23828 info: "proc (spec)"
23829 info: which is withed by:
23830 info: "pack (body)"
23831 info: "pack (body)" must be elaborated before "proc (body)"
23832 info: reason: pragma Elaborate in unit "proc (body)"
23838 In this case we have a cycle that the binder cannot break. On the one
23839 hand, there is an explicit pragma Elaborate in @code{proc} for
23840 @code{pack}. This means that the body of @code{pack} must be elaborated
23841 before the body of @code{proc}. On the other hand, there is elaboration
23842 code in @code{pack} that calls a subprogram in @code{proc}. This means
23843 that for maximum safety, there should really be a pragma
23844 Elaborate_All in @code{pack} for @code{proc} which would require that
23845 the body of @code{proc} be elaborated before the body of
23846 @code{pack}. Clearly both requirements cannot be satisfied.
23847 Faced with a circularity of this kind, you have three different options.
23850 @item Fix the program
23851 The most desirable option from the point of view of long-term maintenance
23852 is to rearrange the program so that the elaboration problems are avoided.
23853 One useful technique is to place the elaboration code into separate
23854 child packages. Another is to move some of the initialization code to
23855 explicitly called subprograms, where the program controls the order
23856 of initialization explicitly. Although this is the most desirable option,
23857 it may be impractical and involve too much modification, especially in
23858 the case of complex legacy code.
23860 @item Perform dynamic checks
23861 If the compilations are done using the
23863 (dynamic elaboration check) switch, then GNAT behaves in a quite different
23864 manner. Dynamic checks are generated for all calls that could possibly result
23865 in raising an exception. With this switch, the compiler does not generate
23866 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
23867 exactly as specified in the @cite{Ada Reference Manual}.
23868 The binder will generate
23869 an executable program that may or may not raise @code{Program_Error}, and then
23870 it is the programmer's job to ensure that it does not raise an exception. Note
23871 that it is important to compile all units with the switch, it cannot be used
23874 @item Suppress checks
23875 The drawback of dynamic checks is that they generate a
23876 significant overhead at run time, both in space and time. If you
23877 are absolutely sure that your program cannot raise any elaboration
23878 exceptions, and you still want to use the dynamic elaboration model,
23879 then you can use the configuration pragma
23880 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23881 example this pragma could be placed in the @file{gnat.adc} file.
23883 @item Suppress checks selectively
23884 When you know that certain calls or instantiations in elaboration code cannot
23885 possibly lead to an elaboration error, and the binder nevertheless complains
23886 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
23887 elaboration circularities, it is possible to remove those warnings locally and
23888 obtain a program that will bind. Clearly this can be unsafe, and it is the
23889 responsibility of the programmer to make sure that the resulting program has no
23890 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
23891 used with different granularity to suppress warnings and break elaboration
23896 Place the pragma that names the called subprogram in the declarative part
23897 that contains the call.
23900 Place the pragma in the declarative part, without naming an entity. This
23901 disables warnings on all calls in the corresponding declarative region.
23904 Place the pragma in the package spec that declares the called subprogram,
23905 and name the subprogram. This disables warnings on all elaboration calls to
23909 Place the pragma in the package spec that declares the called subprogram,
23910 without naming any entity. This disables warnings on all elaboration calls to
23911 all subprograms declared in this spec.
23913 @item Use Pragma Elaborate
23914 As previously described in section @xref{Treatment of Pragma Elaborate},
23915 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23916 that no elaboration checks are required on calls to the designated unit.
23917 There may be cases in which the caller knows that no transitive calls
23918 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23919 case where @code{pragma Elaborate_All} would cause a circularity.
23923 These five cases are listed in order of decreasing safety, and therefore
23924 require increasing programmer care in their application. Consider the
23927 @smallexample @c adanocomment
23929 function F1 return Integer;
23934 function F2 return Integer;
23935 function Pure (x : integer) return integer;
23936 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
23937 -- pragma Suppress (Elaboration_Check); -- (4)
23941 package body Pack1 is
23942 function F1 return Integer is
23946 Val : integer := Pack2.Pure (11); -- Elab. call (1)
23949 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
23950 -- pragma Suppress(Elaboration_Check); -- (2)
23952 X1 := Pack2.F2 + 1; -- Elab. call (2)
23957 package body Pack2 is
23958 function F2 return Integer is
23962 function Pure (x : integer) return integer is
23964 return x ** 3 - 3 * x;
23968 with Pack1, Ada.Text_IO;
23971 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23974 In the absence of any pragmas, an attempt to bind this program produces
23975 the following diagnostics:
23981 error: elaboration circularity detected
23982 info: "pack1 (body)" must be elaborated before "pack1 (body)"
23983 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
23984 info: recompile "pack1 (body)" with -gnatwl for full details
23985 info: "pack1 (body)"
23986 info: must be elaborated along with its spec:
23987 info: "pack1 (spec)"
23988 info: which is withed by:
23989 info: "pack2 (body)"
23990 info: which must be elaborated along with its spec:
23991 info: "pack2 (spec)"
23992 info: which is withed by:
23993 info: "pack1 (body)"
23996 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23997 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23998 F2 is safe, even though F2 calls F1, because the call appears after the
23999 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24000 remove the warning on the call. It is also possible to use pragma (2)
24001 because there are no other potentially unsafe calls in the block.
24004 The call to @code{Pure} is safe because this function does not depend on the
24005 state of @code{Pack2}. Therefore any call to this function is safe, and it
24006 is correct to place pragma (3) in the corresponding package spec.
24009 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24010 warnings on all calls to functions declared therein. Note that this is not
24011 necessarily safe, and requires more detailed examination of the subprogram
24012 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24013 be already elaborated.
24017 It is hard to generalize on which of these four approaches should be
24018 taken. Obviously if it is possible to fix the program so that the default
24019 treatment works, this is preferable, but this may not always be practical.
24020 It is certainly simple enough to use
24022 but the danger in this case is that, even if the GNAT binder
24023 finds a correct elaboration order, it may not always do so,
24024 and certainly a binder from another Ada compiler might not. A
24025 combination of testing and analysis (for which the warnings generated
24028 switch can be useful) must be used to ensure that the program is free
24029 of errors. One switch that is useful in this testing is the
24030 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24033 Normally the binder tries to find an order that has the best chance
24034 of avoiding elaboration problems. However, if this switch is used, the binder
24035 plays a devil's advocate role, and tries to choose the order that
24036 has the best chance of failing. If your program works even with this
24037 switch, then it has a better chance of being error free, but this is still
24040 For an example of this approach in action, consider the C-tests (executable
24041 tests) from the ACVC suite. If these are compiled and run with the default
24042 treatment, then all but one of them succeed without generating any error
24043 diagnostics from the binder. However, there is one test that fails, and
24044 this is not surprising, because the whole point of this test is to ensure
24045 that the compiler can handle cases where it is impossible to determine
24046 a correct order statically, and it checks that an exception is indeed
24047 raised at run time.
24049 This one test must be compiled and run using the
24051 switch, and then it passes. Alternatively, the entire suite can
24052 be run using this switch. It is never wrong to run with the dynamic
24053 elaboration switch if your code is correct, and we assume that the
24054 C-tests are indeed correct (it is less efficient, but efficiency is
24055 not a factor in running the ACVC tests.)
24057 @node Elaboration for Access-to-Subprogram Values
24058 @section Elaboration for Access-to-Subprogram Values
24059 @cindex Access-to-subprogram
24062 Access-to-subprogram types (introduced in Ada 95) complicate
24063 the handling of elaboration. The trouble is that it becomes
24064 impossible to tell at compile time which procedure
24065 is being called. This means that it is not possible for the binder
24066 to analyze the elaboration requirements in this case.
24068 If at the point at which the access value is created
24069 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24070 the body of the subprogram is
24071 known to have been elaborated, then the access value is safe, and its use
24072 does not require a check. This may be achieved by appropriate arrangement
24073 of the order of declarations if the subprogram is in the current unit,
24074 or, if the subprogram is in another unit, by using pragma
24075 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24076 on the referenced unit.
24078 If the referenced body is not known to have been elaborated at the point
24079 the access value is created, then any use of the access value must do a
24080 dynamic check, and this dynamic check will fail and raise a
24081 @code{Program_Error} exception if the body has not been elaborated yet.
24082 GNAT will generate the necessary checks, and in addition, if the
24084 switch is set, will generate warnings that such checks are required.
24086 The use of dynamic dispatching for tagged types similarly generates
24087 a requirement for dynamic checks, and premature calls to any primitive
24088 operation of a tagged type before the body of the operation has been
24089 elaborated, will result in the raising of @code{Program_Error}.
24091 @node Summary of Procedures for Elaboration Control
24092 @section Summary of Procedures for Elaboration Control
24093 @cindex Elaboration control
24096 First, compile your program with the default options, using none of
24097 the special elaboration control switches. If the binder successfully
24098 binds your program, then you can be confident that, apart from issues
24099 raised by the use of access-to-subprogram types and dynamic dispatching,
24100 the program is free of elaboration errors. If it is important that the
24101 program be portable, then use the
24103 switch to generate warnings about missing @code{Elaborate} or
24104 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24106 If the program fails to bind using the default static elaboration
24107 handling, then you can fix the program to eliminate the binder
24108 message, or recompile the entire program with the
24109 @option{-gnatE} switch to generate dynamic elaboration checks,
24110 and, if you are sure there really are no elaboration problems,
24111 use a global pragma @code{Suppress (Elaboration_Check)}.
24113 @node Other Elaboration Order Considerations
24114 @section Other Elaboration Order Considerations
24116 This section has been entirely concerned with the issue of finding a valid
24117 elaboration order, as defined by the Ada Reference Manual. In a case
24118 where several elaboration orders are valid, the task is to find one
24119 of the possible valid elaboration orders (and the static model in GNAT
24120 will ensure that this is achieved).
24122 The purpose of the elaboration rules in the Ada Reference Manual is to
24123 make sure that no entity is accessed before it has been elaborated. For
24124 a subprogram, this means that the spec and body must have been elaborated
24125 before the subprogram is called. For an object, this means that the object
24126 must have been elaborated before its value is read or written. A violation
24127 of either of these two requirements is an access before elaboration order,
24128 and this section has been all about avoiding such errors.
24130 In the case where more than one order of elaboration is possible, in the
24131 sense that access before elaboration errors are avoided, then any one of
24132 the orders is ``correct'' in the sense that it meets the requirements of
24133 the Ada Reference Manual, and no such error occurs.
24135 However, it may be the case for a given program, that there are
24136 constraints on the order of elaboration that come not from consideration
24137 of avoiding elaboration errors, but rather from extra-lingual logic
24138 requirements. Consider this example:
24140 @smallexample @c ada
24141 with Init_Constants;
24142 package Constants is
24147 package Init_Constants is
24148 procedure P; -- require a body
24149 end Init_Constants;
24152 package body Init_Constants is
24153 procedure P is begin null; end;
24157 end Init_Constants;
24161 Z : Integer := Constants.X + Constants.Y;
24165 with Text_IO; use Text_IO;
24168 Put_Line (Calc.Z'Img);
24173 In this example, there is more than one valid order of elaboration. For
24174 example both the following are correct orders:
24177 Init_Constants spec
24180 Init_Constants body
24185 Init_Constants spec
24186 Init_Constants body
24193 There is no language rule to prefer one or the other, both are correct
24194 from an order of elaboration point of view. But the programmatic effects
24195 of the two orders are very different. In the first, the elaboration routine
24196 of @code{Calc} initializes @code{Z} to zero, and then the main program
24197 runs with this value of zero. But in the second order, the elaboration
24198 routine of @code{Calc} runs after the body of Init_Constants has set
24199 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24202 One could perhaps by applying pretty clever non-artificial intelligence
24203 to the situation guess that it is more likely that the second order of
24204 elaboration is the one desired, but there is no formal linguistic reason
24205 to prefer one over the other. In fact in this particular case, GNAT will
24206 prefer the second order, because of the rule that bodies are elaborated
24207 as soon as possible, but it's just luck that this is what was wanted
24208 (if indeed the second order was preferred).
24210 If the program cares about the order of elaboration routines in a case like
24211 this, it is important to specify the order required. In this particular
24212 case, that could have been achieved by adding to the spec of Calc:
24214 @smallexample @c ada
24215 pragma Elaborate_All (Constants);
24219 which requires that the body (if any) and spec of @code{Constants},
24220 as well as the body and spec of any unit @code{with}'ed by
24221 @code{Constants} be elaborated before @code{Calc} is elaborated.
24223 Clearly no automatic method can always guess which alternative you require,
24224 and if you are working with legacy code that had constraints of this kind
24225 which were not properly specified by adding @code{Elaborate} or
24226 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24227 compilers can choose different orders.
24229 However, GNAT does attempt to diagnose the common situation where there
24230 are uninitialized variables in the visible part of a package spec, and the
24231 corresponding package body has an elaboration block that directly or
24232 indirectly initialized one or more of these variables. This is the situation
24233 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24234 a warning that suggests this addition if it detects this situation.
24236 The @code{gnatbind}
24237 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24238 out problems. This switch causes bodies to be elaborated as late as possible
24239 instead of as early as possible. In the example above, it would have forced
24240 the choice of the first elaboration order. If you get different results
24241 when using this switch, and particularly if one set of results is right,
24242 and one is wrong as far as you are concerned, it shows that you have some
24243 missing @code{Elaborate} pragmas. For the example above, we have the
24247 gnatmake -f -q main
24250 gnatmake -f -q main -bargs -p
24256 It is of course quite unlikely that both these results are correct, so
24257 it is up to you in a case like this to investigate the source of the
24258 difference, by looking at the two elaboration orders that are chosen,
24259 and figuring out which is correct, and then adding the necessary
24260 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24264 @c *******************************
24265 @node Conditional Compilation
24266 @appendix Conditional Compilation
24267 @c *******************************
24268 @cindex Conditional compilation
24271 It is often necessary to arrange for a single source program
24272 to serve multiple purposes, where it is compiled in different
24273 ways to achieve these different goals. Some examples of the
24274 need for this feature are
24277 @item Adapting a program to a different hardware environment
24278 @item Adapting a program to a different target architecture
24279 @item Turning debugging features on and off
24280 @item Arranging for a program to compile with different compilers
24284 In C, or C++, the typical approach would be to use the preprocessor
24285 that is defined as part of the language. The Ada language does not
24286 contain such a feature. This is not an oversight, but rather a very
24287 deliberate design decision, based on the experience that overuse of
24288 the preprocessing features in C and C++ can result in programs that
24289 are extremely difficult to maintain. For example, if we have ten
24290 switches that can be on or off, this means that there are a thousand
24291 separate programs, any one of which might not even be syntactically
24292 correct, and even if syntactically correct, the resulting program
24293 might not work correctly. Testing all combinations can quickly become
24296 Nevertheless, the need to tailor programs certainly exists, and in
24297 this Appendix we will discuss how this can
24298 be achieved using Ada in general, and GNAT in particular.
24301 * Use of Boolean Constants::
24302 * Debugging - A Special Case::
24303 * Conditionalizing Declarations::
24304 * Use of Alternative Implementations::
24308 @node Use of Boolean Constants
24309 @section Use of Boolean Constants
24312 In the case where the difference is simply which code
24313 sequence is executed, the cleanest solution is to use Boolean
24314 constants to control which code is executed.
24316 @smallexample @c ada
24318 FP_Initialize_Required : constant Boolean := True;
24320 if FP_Initialize_Required then
24327 Not only will the code inside the @code{if} statement not be executed if
24328 the constant Boolean is @code{False}, but it will also be completely
24329 deleted from the program.
24330 However, the code is only deleted after the @code{if} statement
24331 has been checked for syntactic and semantic correctness.
24332 (In contrast, with preprocessors the code is deleted before the
24333 compiler ever gets to see it, so it is not checked until the switch
24335 @cindex Preprocessors (contrasted with conditional compilation)
24337 Typically the Boolean constants will be in a separate package,
24340 @smallexample @c ada
24343 FP_Initialize_Required : constant Boolean := True;
24344 Reset_Available : constant Boolean := False;
24351 The @code{Config} package exists in multiple forms for the various targets,
24352 with an appropriate script selecting the version of @code{Config} needed.
24353 Then any other unit requiring conditional compilation can do a @code{with}
24354 of @code{Config} to make the constants visible.
24357 @node Debugging - A Special Case
24358 @section Debugging - A Special Case
24361 A common use of conditional code is to execute statements (for example
24362 dynamic checks, or output of intermediate results) under control of a
24363 debug switch, so that the debugging behavior can be turned on and off.
24364 This can be done using a Boolean constant to control whether the code
24367 @smallexample @c ada
24370 Put_Line ("got to the first stage!");
24378 @smallexample @c ada
24380 if Debugging and then Temperature > 999.0 then
24381 raise Temperature_Crazy;
24387 Since this is a common case, there are special features to deal with
24388 this in a convenient manner. For the case of tests, Ada 2005 has added
24389 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24390 @cindex pragma @code{Assert}
24391 on the @code{Assert} pragma that has always been available in GNAT, so this
24392 feature may be used with GNAT even if you are not using Ada 2005 features.
24393 The use of pragma @code{Assert} is described in
24394 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24395 example, the last test could be written:
24397 @smallexample @c ada
24398 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24404 @smallexample @c ada
24405 pragma Assert (Temperature <= 999.0);
24409 In both cases, if assertions are active and the temperature is excessive,
24410 the exception @code{Assert_Failure} will be raised, with the given string in
24411 the first case or a string indicating the location of the pragma in the second
24412 case used as the exception message.
24414 You can turn assertions on and off by using the @code{Assertion_Policy}
24416 @cindex pragma @code{Assertion_Policy}
24417 This is an Ada 2005 pragma which is implemented in all modes by
24418 GNAT, but only in the latest versions of GNAT which include Ada 2005
24419 capability. Alternatively, you can use the @option{-gnata} switch
24420 @cindex @option{-gnata} switch
24421 to enable assertions from the command line (this is recognized by all versions
24424 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24425 @code{Debug} can be used:
24426 @cindex pragma @code{Debug}
24428 @smallexample @c ada
24429 pragma Debug (Put_Line ("got to the first stage!"));
24433 If debug pragmas are enabled, the argument, which must be of the form of
24434 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24435 Only one call can be present, but of course a special debugging procedure
24436 containing any code you like can be included in the program and then
24437 called in a pragma @code{Debug} argument as needed.
24439 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24440 construct is that pragma @code{Debug} can appear in declarative contexts,
24441 such as at the very beginning of a procedure, before local declarations have
24444 Debug pragmas are enabled using either the @option{-gnata} switch that also
24445 controls assertions, or with a separate Debug_Policy pragma.
24446 @cindex pragma @code{Debug_Policy}
24447 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24448 in Ada 95 and Ada 83 programs as well), and is analogous to
24449 pragma @code{Assertion_Policy} to control assertions.
24451 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24452 and thus they can appear in @file{gnat.adc} if you are not using a
24453 project file, or in the file designated to contain configuration pragmas
24455 They then apply to all subsequent compilations. In practice the use of
24456 the @option{-gnata} switch is often the most convenient method of controlling
24457 the status of these pragmas.
24459 Note that a pragma is not a statement, so in contexts where a statement
24460 sequence is required, you can't just write a pragma on its own. You have
24461 to add a @code{null} statement.
24463 @smallexample @c ada
24466 @dots{} -- some statements
24468 pragma Assert (Num_Cases < 10);
24475 @node Conditionalizing Declarations
24476 @section Conditionalizing Declarations
24479 In some cases, it may be necessary to conditionalize declarations to meet
24480 different requirements. For example we might want a bit string whose length
24481 is set to meet some hardware message requirement.
24483 In some cases, it may be possible to do this using declare blocks controlled
24484 by conditional constants:
24486 @smallexample @c ada
24488 if Small_Machine then
24490 X : Bit_String (1 .. 10);
24496 X : Large_Bit_String (1 .. 1000);
24505 Note that in this approach, both declarations are analyzed by the
24506 compiler so this can only be used where both declarations are legal,
24507 even though one of them will not be used.
24509 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
24510 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24511 that are parameterized by these constants. For example
24513 @smallexample @c ada
24516 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24522 If @code{Bits_Per_Word} is set to 32, this generates either
24524 @smallexample @c ada
24527 Field1 at 0 range 0 .. 32;
24533 for the big endian case, or
24535 @smallexample @c ada
24538 Field1 at 0 range 10 .. 32;
24544 for the little endian case. Since a powerful subset of Ada expression
24545 notation is usable for creating static constants, clever use of this
24546 feature can often solve quite difficult problems in conditionalizing
24547 compilation (note incidentally that in Ada 95, the little endian
24548 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24549 need to define this one yourself).
24552 @node Use of Alternative Implementations
24553 @section Use of Alternative Implementations
24556 In some cases, none of the approaches described above are adequate. This
24557 can occur for example if the set of declarations required is radically
24558 different for two different configurations.
24560 In this situation, the official Ada way of dealing with conditionalizing
24561 such code is to write separate units for the different cases. As long as
24562 this does not result in excessive duplication of code, this can be done
24563 without creating maintenance problems. The approach is to share common
24564 code as far as possible, and then isolate the code and declarations
24565 that are different. Subunits are often a convenient method for breaking
24566 out a piece of a unit that is to be conditionalized, with separate files
24567 for different versions of the subunit for different targets, where the
24568 build script selects the right one to give to the compiler.
24569 @cindex Subunits (and conditional compilation)
24571 As an example, consider a situation where a new feature in Ada 2005
24572 allows something to be done in a really nice way. But your code must be able
24573 to compile with an Ada 95 compiler. Conceptually you want to say:
24575 @smallexample @c ada
24578 @dots{} neat Ada 2005 code
24580 @dots{} not quite as neat Ada 95 code
24586 where @code{Ada_2005} is a Boolean constant.
24588 But this won't work when @code{Ada_2005} is set to @code{False},
24589 since the @code{then} clause will be illegal for an Ada 95 compiler.
24590 (Recall that although such unreachable code would eventually be deleted
24591 by the compiler, it still needs to be legal. If it uses features
24592 introduced in Ada 2005, it will be illegal in Ada 95.)
24594 So instead we write
24596 @smallexample @c ada
24597 procedure Insert is separate;
24601 Then we have two files for the subunit @code{Insert}, with the two sets of
24603 If the package containing this is called @code{File_Queries}, then we might
24607 @item @file{file_queries-insert-2005.adb}
24608 @item @file{file_queries-insert-95.adb}
24612 and the build script renames the appropriate file to
24615 file_queries-insert.adb
24619 and then carries out the compilation.
24621 This can also be done with project files' naming schemes. For example:
24623 @smallexample @c project
24624 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
24628 Note also that with project files it is desirable to use a different extension
24629 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
24630 conflict may arise through another commonly used feature: to declare as part
24631 of the project a set of directories containing all the sources obeying the
24632 default naming scheme.
24634 The use of alternative units is certainly feasible in all situations,
24635 and for example the Ada part of the GNAT run-time is conditionalized
24636 based on the target architecture using this approach. As a specific example,
24637 consider the implementation of the AST feature in VMS. There is one
24645 which is the same for all architectures, and three bodies:
24649 used for all non-VMS operating systems
24650 @item s-asthan-vms-alpha.adb
24651 used for VMS on the Alpha
24652 @item s-asthan-vms-ia64.adb
24653 used for VMS on the ia64
24657 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
24658 this operating system feature is not available, and the two remaining
24659 versions interface with the corresponding versions of VMS to provide
24660 VMS-compatible AST handling. The GNAT build script knows the architecture
24661 and operating system, and automatically selects the right version,
24662 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
24664 Another style for arranging alternative implementations is through Ada's
24665 access-to-subprogram facility.
24666 In case some functionality is to be conditionally included,
24667 you can declare an access-to-procedure variable @code{Ref} that is initialized
24668 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
24670 In some library package, set @code{Ref} to @code{Proc'Access} for some
24671 procedure @code{Proc} that performs the relevant processing.
24672 The initialization only occurs if the library package is included in the
24674 The same idea can also be implemented using tagged types and dispatching
24678 @node Preprocessing
24679 @section Preprocessing
24680 @cindex Preprocessing
24683 Although it is quite possible to conditionalize code without the use of
24684 C-style preprocessing, as described earlier in this section, it is
24685 nevertheless convenient in some cases to use the C approach. Moreover,
24686 older Ada compilers have often provided some preprocessing capability,
24687 so legacy code may depend on this approach, even though it is not
24690 To accommodate such use, GNAT provides a preprocessor (modeled to a large
24691 extent on the various preprocessors that have been used
24692 with legacy code on other compilers, to enable easier transition).
24694 The preprocessor may be used in two separate modes. It can be used quite
24695 separately from the compiler, to generate a separate output source file
24696 that is then fed to the compiler as a separate step. This is the
24697 @code{gnatprep} utility, whose use is fully described in
24698 @ref{Preprocessing Using gnatprep}.
24699 @cindex @code{gnatprep}
24701 The preprocessing language allows such constructs as
24705 #if DEBUG or PRIORITY > 4 then
24706 bunch of declarations
24708 completely different bunch of declarations
24714 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
24715 defined either on the command line or in a separate file.
24717 The other way of running the preprocessor is even closer to the C style and
24718 often more convenient. In this approach the preprocessing is integrated into
24719 the compilation process. The compiler is fed the preprocessor input which
24720 includes @code{#if} lines etc, and then the compiler carries out the
24721 preprocessing internally and processes the resulting output.
24722 For more details on this approach, see @ref{Integrated Preprocessing}.
24725 @c *******************************
24726 @node Inline Assembler
24727 @appendix Inline Assembler
24728 @c *******************************
24731 If you need to write low-level software that interacts directly
24732 with the hardware, Ada provides two ways to incorporate assembly
24733 language code into your program. First, you can import and invoke
24734 external routines written in assembly language, an Ada feature fully
24735 supported by GNAT@. However, for small sections of code it may be simpler
24736 or more efficient to include assembly language statements directly
24737 in your Ada source program, using the facilities of the implementation-defined
24738 package @code{System.Machine_Code}, which incorporates the gcc
24739 Inline Assembler. The Inline Assembler approach offers a number of advantages,
24740 including the following:
24743 @item No need to use non-Ada tools
24744 @item Consistent interface over different targets
24745 @item Automatic usage of the proper calling conventions
24746 @item Access to Ada constants and variables
24747 @item Definition of intrinsic routines
24748 @item Possibility of inlining a subprogram comprising assembler code
24749 @item Code optimizer can take Inline Assembler code into account
24752 This chapter presents a series of examples to show you how to use
24753 the Inline Assembler. Although it focuses on the Intel x86,
24754 the general approach applies also to other processors.
24755 It is assumed that you are familiar with Ada
24756 and with assembly language programming.
24759 * Basic Assembler Syntax::
24760 * A Simple Example of Inline Assembler::
24761 * Output Variables in Inline Assembler::
24762 * Input Variables in Inline Assembler::
24763 * Inlining Inline Assembler Code::
24764 * Other Asm Functionality::
24767 @c ---------------------------------------------------------------------------
24768 @node Basic Assembler Syntax
24769 @section Basic Assembler Syntax
24772 The assembler used by GNAT and gcc is based not on the Intel assembly
24773 language, but rather on a language that descends from the AT&T Unix
24774 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24775 The following table summarizes the main features of @emph{as} syntax
24776 and points out the differences from the Intel conventions.
24777 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24778 pre-processor) documentation for further information.
24781 @item Register names
24782 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24784 Intel: No extra punctuation; for example @code{eax}
24786 @item Immediate operand
24787 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24789 Intel: No extra punctuation; for example @code{4}
24792 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24794 Intel: No extra punctuation; for example @code{loc}
24796 @item Memory contents
24797 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24799 Intel: Square brackets; for example @code{[loc]}
24801 @item Register contents
24802 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24804 Intel: Square brackets; for example @code{[eax]}
24806 @item Hexadecimal numbers
24807 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24809 Intel: Trailing ``h''; for example @code{A0h}
24812 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24815 Intel: Implicit, deduced by assembler; for example @code{mov}
24817 @item Instruction repetition
24818 gcc / @emph{as}: Split into two lines; for example
24824 Intel: Keep on one line; for example @code{rep stosl}
24826 @item Order of operands
24827 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24829 Intel: Destination first; for example @code{mov eax, 4}
24832 @c ---------------------------------------------------------------------------
24833 @node A Simple Example of Inline Assembler
24834 @section A Simple Example of Inline Assembler
24837 The following example will generate a single assembly language statement,
24838 @code{nop}, which does nothing. Despite its lack of run-time effect,
24839 the example will be useful in illustrating the basics of
24840 the Inline Assembler facility.
24842 @smallexample @c ada
24844 with System.Machine_Code; use System.Machine_Code;
24845 procedure Nothing is
24852 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24853 here it takes one parameter, a @emph{template string} that must be a static
24854 expression and that will form the generated instruction.
24855 @code{Asm} may be regarded as a compile-time procedure that parses
24856 the template string and additional parameters (none here),
24857 from which it generates a sequence of assembly language instructions.
24859 The examples in this chapter will illustrate several of the forms
24860 for invoking @code{Asm}; a complete specification of the syntax
24861 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
24864 Under the standard GNAT conventions, the @code{Nothing} procedure
24865 should be in a file named @file{nothing.adb}.
24866 You can build the executable in the usual way:
24870 However, the interesting aspect of this example is not its run-time behavior
24871 but rather the generated assembly code.
24872 To see this output, invoke the compiler as follows:
24874 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24876 where the options are:
24880 compile only (no bind or link)
24882 generate assembler listing
24883 @item -fomit-frame-pointer
24884 do not set up separate stack frames
24886 do not add runtime checks
24889 This gives a human-readable assembler version of the code. The resulting
24890 file will have the same name as the Ada source file, but with a @code{.s}
24891 extension. In our example, the file @file{nothing.s} has the following
24896 .file "nothing.adb"
24898 ___gnu_compiled_ada:
24901 .globl __ada_nothing
24913 The assembly code you included is clearly indicated by
24914 the compiler, between the @code{#APP} and @code{#NO_APP}
24915 delimiters. The character before the 'APP' and 'NOAPP'
24916 can differ on different targets. For example, GNU/Linux uses '#APP' while
24917 on NT you will see '/APP'.
24919 If you make a mistake in your assembler code (such as using the
24920 wrong size modifier, or using a wrong operand for the instruction) GNAT
24921 will report this error in a temporary file, which will be deleted when
24922 the compilation is finished. Generating an assembler file will help
24923 in such cases, since you can assemble this file separately using the
24924 @emph{as} assembler that comes with gcc.
24926 Assembling the file using the command
24929 as @file{nothing.s}
24932 will give you error messages whose lines correspond to the assembler
24933 input file, so you can easily find and correct any mistakes you made.
24934 If there are no errors, @emph{as} will generate an object file
24935 @file{nothing.out}.
24937 @c ---------------------------------------------------------------------------
24938 @node Output Variables in Inline Assembler
24939 @section Output Variables in Inline Assembler
24942 The examples in this section, showing how to access the processor flags,
24943 illustrate how to specify the destination operands for assembly language
24946 @smallexample @c ada
24948 with Interfaces; use Interfaces;
24949 with Ada.Text_IO; use Ada.Text_IO;
24950 with System.Machine_Code; use System.Machine_Code;
24951 procedure Get_Flags is
24952 Flags : Unsigned_32;
24955 Asm ("pushfl" & LF & HT & -- push flags on stack
24956 "popl %%eax" & LF & HT & -- load eax with flags
24957 "movl %%eax, %0", -- store flags in variable
24958 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24959 Put_Line ("Flags register:" & Flags'Img);
24964 In order to have a nicely aligned assembly listing, we have separated
24965 multiple assembler statements in the Asm template string with linefeed
24966 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24967 The resulting section of the assembly output file is:
24974 movl %eax, -40(%ebp)
24979 It would have been legal to write the Asm invocation as:
24982 Asm ("pushfl popl %%eax movl %%eax, %0")
24985 but in the generated assembler file, this would come out as:
24989 pushfl popl %eax movl %eax, -40(%ebp)
24993 which is not so convenient for the human reader.
24995 We use Ada comments
24996 at the end of each line to explain what the assembler instructions
24997 actually do. This is a useful convention.
24999 When writing Inline Assembler instructions, you need to precede each register
25000 and variable name with a percent sign. Since the assembler already requires
25001 a percent sign at the beginning of a register name, you need two consecutive
25002 percent signs for such names in the Asm template string, thus @code{%%eax}.
25003 In the generated assembly code, one of the percent signs will be stripped off.
25005 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25006 variables: operands you later define using @code{Input} or @code{Output}
25007 parameters to @code{Asm}.
25008 An output variable is illustrated in
25009 the third statement in the Asm template string:
25013 The intent is to store the contents of the eax register in a variable that can
25014 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
25015 necessarily work, since the compiler might optimize by using a register
25016 to hold Flags, and the expansion of the @code{movl} instruction would not be
25017 aware of this optimization. The solution is not to store the result directly
25018 but rather to advise the compiler to choose the correct operand form;
25019 that is the purpose of the @code{%0} output variable.
25021 Information about the output variable is supplied in the @code{Outputs}
25022 parameter to @code{Asm}:
25024 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25027 The output is defined by the @code{Asm_Output} attribute of the target type;
25028 the general format is
25030 Type'Asm_Output (constraint_string, variable_name)
25033 The constraint string directs the compiler how
25034 to store/access the associated variable. In the example
25036 Unsigned_32'Asm_Output ("=m", Flags);
25038 the @code{"m"} (memory) constraint tells the compiler that the variable
25039 @code{Flags} should be stored in a memory variable, thus preventing
25040 the optimizer from keeping it in a register. In contrast,
25042 Unsigned_32'Asm_Output ("=r", Flags);
25044 uses the @code{"r"} (register) constraint, telling the compiler to
25045 store the variable in a register.
25047 If the constraint is preceded by the equal character (@strong{=}), it tells
25048 the compiler that the variable will be used to store data into it.
25050 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25051 allowing the optimizer to choose whatever it deems best.
25053 There are a fairly large number of constraints, but the ones that are
25054 most useful (for the Intel x86 processor) are the following:
25060 global (i.e.@: can be stored anywhere)
25078 use one of eax, ebx, ecx or edx
25080 use one of eax, ebx, ecx, edx, esi or edi
25083 The full set of constraints is described in the gcc and @emph{as}
25084 documentation; note that it is possible to combine certain constraints
25085 in one constraint string.
25087 You specify the association of an output variable with an assembler operand
25088 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25090 @smallexample @c ada
25092 Asm ("pushfl" & LF & HT & -- push flags on stack
25093 "popl %%eax" & LF & HT & -- load eax with flags
25094 "movl %%eax, %0", -- store flags in variable
25095 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25099 @code{%0} will be replaced in the expanded code by the appropriate operand,
25101 the compiler decided for the @code{Flags} variable.
25103 In general, you may have any number of output variables:
25106 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25108 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25109 of @code{Asm_Output} attributes
25113 @smallexample @c ada
25115 Asm ("movl %%eax, %0" & LF & HT &
25116 "movl %%ebx, %1" & LF & HT &
25118 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
25119 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
25120 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
25124 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25125 in the Ada program.
25127 As a variation on the @code{Get_Flags} example, we can use the constraints
25128 string to direct the compiler to store the eax register into the @code{Flags}
25129 variable, instead of including the store instruction explicitly in the
25130 @code{Asm} template string:
25132 @smallexample @c ada
25134 with Interfaces; use Interfaces;
25135 with Ada.Text_IO; use Ada.Text_IO;
25136 with System.Machine_Code; use System.Machine_Code;
25137 procedure Get_Flags_2 is
25138 Flags : Unsigned_32;
25141 Asm ("pushfl" & LF & HT & -- push flags on stack
25142 "popl %%eax", -- save flags in eax
25143 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25144 Put_Line ("Flags register:" & Flags'Img);
25150 The @code{"a"} constraint tells the compiler that the @code{Flags}
25151 variable will come from the eax register. Here is the resulting code:
25159 movl %eax,-40(%ebp)
25164 The compiler generated the store of eax into Flags after
25165 expanding the assembler code.
25167 Actually, there was no need to pop the flags into the eax register;
25168 more simply, we could just pop the flags directly into the program variable:
25170 @smallexample @c ada
25172 with Interfaces; use Interfaces;
25173 with Ada.Text_IO; use Ada.Text_IO;
25174 with System.Machine_Code; use System.Machine_Code;
25175 procedure Get_Flags_3 is
25176 Flags : Unsigned_32;
25179 Asm ("pushfl" & LF & HT & -- push flags on stack
25180 "pop %0", -- save flags in Flags
25181 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25182 Put_Line ("Flags register:" & Flags'Img);
25187 @c ---------------------------------------------------------------------------
25188 @node Input Variables in Inline Assembler
25189 @section Input Variables in Inline Assembler
25192 The example in this section illustrates how to specify the source operands
25193 for assembly language statements.
25194 The program simply increments its input value by 1:
25196 @smallexample @c ada
25198 with Interfaces; use Interfaces;
25199 with Ada.Text_IO; use Ada.Text_IO;
25200 with System.Machine_Code; use System.Machine_Code;
25201 procedure Increment is
25203 function Incr (Value : Unsigned_32) return Unsigned_32 is
25204 Result : Unsigned_32;
25207 Inputs => Unsigned_32'Asm_Input ("a", Value),
25208 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25212 Value : Unsigned_32;
25216 Put_Line ("Value before is" & Value'Img);
25217 Value := Incr (Value);
25218 Put_Line ("Value after is" & Value'Img);
25223 The @code{Outputs} parameter to @code{Asm} specifies
25224 that the result will be in the eax register and that it is to be stored
25225 in the @code{Result} variable.
25227 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25228 but with an @code{Asm_Input} attribute.
25229 The @code{"="} constraint, indicating an output value, is not present.
25231 You can have multiple input variables, in the same way that you can have more
25232 than one output variable.
25234 The parameter count (%0, %1) etc, now starts at the first input
25235 statement, and continues with the output statements.
25236 When both parameters use the same variable, the
25237 compiler will treat them as the same %n operand, which is the case here.
25239 Just as the @code{Outputs} parameter causes the register to be stored into the
25240 target variable after execution of the assembler statements, so does the
25241 @code{Inputs} parameter cause its variable to be loaded into the register
25242 before execution of the assembler statements.
25244 Thus the effect of the @code{Asm} invocation is:
25246 @item load the 32-bit value of @code{Value} into eax
25247 @item execute the @code{incl %eax} instruction
25248 @item store the contents of eax into the @code{Result} variable
25251 The resulting assembler file (with @option{-O2} optimization) contains:
25254 _increment__incr.1:
25267 @c ---------------------------------------------------------------------------
25268 @node Inlining Inline Assembler Code
25269 @section Inlining Inline Assembler Code
25272 For a short subprogram such as the @code{Incr} function in the previous
25273 section, the overhead of the call and return (creating / deleting the stack
25274 frame) can be significant, compared to the amount of code in the subprogram
25275 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25276 which directs the compiler to expand invocations of the subprogram at the
25277 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25278 Here is the resulting program:
25280 @smallexample @c ada
25282 with Interfaces; use Interfaces;
25283 with Ada.Text_IO; use Ada.Text_IO;
25284 with System.Machine_Code; use System.Machine_Code;
25285 procedure Increment_2 is
25287 function Incr (Value : Unsigned_32) return Unsigned_32 is
25288 Result : Unsigned_32;
25291 Inputs => Unsigned_32'Asm_Input ("a", Value),
25292 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25295 pragma Inline (Increment);
25297 Value : Unsigned_32;
25301 Put_Line ("Value before is" & Value'Img);
25302 Value := Increment (Value);
25303 Put_Line ("Value after is" & Value'Img);
25308 Compile the program with both optimization (@option{-O2}) and inlining
25309 (@option{-gnatn}) enabled.
25311 The @code{Incr} function is still compiled as usual, but at the
25312 point in @code{Increment} where our function used to be called:
25317 call _increment__incr.1
25322 the code for the function body directly appears:
25335 thus saving the overhead of stack frame setup and an out-of-line call.
25337 @c ---------------------------------------------------------------------------
25338 @node Other Asm Functionality
25339 @section Other @code{Asm} Functionality
25342 This section describes two important parameters to the @code{Asm}
25343 procedure: @code{Clobber}, which identifies register usage;
25344 and @code{Volatile}, which inhibits unwanted optimizations.
25347 * The Clobber Parameter::
25348 * The Volatile Parameter::
25351 @c ---------------------------------------------------------------------------
25352 @node The Clobber Parameter
25353 @subsection The @code{Clobber} Parameter
25356 One of the dangers of intermixing assembly language and a compiled language
25357 such as Ada is that the compiler needs to be aware of which registers are
25358 being used by the assembly code. In some cases, such as the earlier examples,
25359 the constraint string is sufficient to indicate register usage (e.g.,
25361 the eax register). But more generally, the compiler needs an explicit
25362 identification of the registers that are used by the Inline Assembly
25365 Using a register that the compiler doesn't know about
25366 could be a side effect of an instruction (like @code{mull}
25367 storing its result in both eax and edx).
25368 It can also arise from explicit register usage in your
25369 assembly code; for example:
25372 Asm ("movl %0, %%ebx" & LF & HT &
25374 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25375 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25379 where the compiler (since it does not analyze the @code{Asm} template string)
25380 does not know you are using the ebx register.
25382 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25383 to identify the registers that will be used by your assembly code:
25387 Asm ("movl %0, %%ebx" & LF & HT &
25389 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25390 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25395 The Clobber parameter is a static string expression specifying the
25396 register(s) you are using. Note that register names are @emph{not} prefixed
25397 by a percent sign. Also, if more than one register is used then their names
25398 are separated by commas; e.g., @code{"eax, ebx"}
25400 The @code{Clobber} parameter has several additional uses:
25402 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25403 @item Use ``register'' name @code{memory} if you changed a memory location
25406 @c ---------------------------------------------------------------------------
25407 @node The Volatile Parameter
25408 @subsection The @code{Volatile} Parameter
25409 @cindex Volatile parameter
25412 Compiler optimizations in the presence of Inline Assembler may sometimes have
25413 unwanted effects. For example, when an @code{Asm} invocation with an input
25414 variable is inside a loop, the compiler might move the loading of the input
25415 variable outside the loop, regarding it as a one-time initialization.
25417 If this effect is not desired, you can disable such optimizations by setting
25418 the @code{Volatile} parameter to @code{True}; for example:
25420 @smallexample @c ada
25422 Asm ("movl %0, %%ebx" & LF & HT &
25424 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25425 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25431 By default, @code{Volatile} is set to @code{False} unless there is no
25432 @code{Outputs} parameter.
25434 Although setting @code{Volatile} to @code{True} prevents unwanted
25435 optimizations, it will also disable other optimizations that might be
25436 important for efficiency. In general, you should set @code{Volatile}
25437 to @code{True} only if the compiler's optimizations have created
25439 @c END OF INLINE ASSEMBLER CHAPTER
25440 @c ===============================
25442 @c ***********************************
25443 @c * Compatibility and Porting Guide *
25444 @c ***********************************
25445 @node Compatibility and Porting Guide
25446 @appendix Compatibility and Porting Guide
25449 This chapter describes the compatibility issues that may arise between
25450 GNAT and other Ada compilation systems (including those for Ada 83),
25451 and shows how GNAT can expedite porting
25452 applications developed in other Ada environments.
25455 * Compatibility with Ada 83::
25456 * Compatibility between Ada 95 and Ada 2005::
25457 * Implementation-dependent characteristics::
25458 * Compatibility with Other Ada Systems::
25459 * Representation Clauses::
25461 @c Brief section is only in non-VMS version
25462 @c Full chapter is in VMS version
25463 * Compatibility with HP Ada 83::
25466 * Transitioning to 64-Bit GNAT for OpenVMS::
25470 @node Compatibility with Ada 83
25471 @section Compatibility with Ada 83
25472 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25475 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
25476 particular, the design intention was that the difficulties associated
25477 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25478 that occur when moving from one Ada 83 system to another.
25480 However, there are a number of points at which there are minor
25481 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
25482 full details of these issues,
25483 and should be consulted for a complete treatment.
25485 following subsections treat the most likely issues to be encountered.
25488 * Legal Ada 83 programs that are illegal in Ada 95::
25489 * More deterministic semantics::
25490 * Changed semantics::
25491 * Other language compatibility issues::
25494 @node Legal Ada 83 programs that are illegal in Ada 95
25495 @subsection Legal Ada 83 programs that are illegal in Ada 95
25497 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25498 Ada 95 and thus also in Ada 2005:
25501 @item Character literals
25502 Some uses of character literals are ambiguous. Since Ada 95 has introduced
25503 @code{Wide_Character} as a new predefined character type, some uses of
25504 character literals that were legal in Ada 83 are illegal in Ada 95.
25506 @smallexample @c ada
25507 for Char in 'A' .. 'Z' loop @dots{} end loop;
25511 The problem is that @code{'A'} and @code{'Z'} could be from either
25512 @code{Character} or @code{Wide_Character}. The simplest correction
25513 is to make the type explicit; e.g.:
25514 @smallexample @c ada
25515 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25518 @item New reserved words
25519 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25520 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25521 Existing Ada 83 code using any of these identifiers must be edited to
25522 use some alternative name.
25524 @item Freezing rules
25525 The rules in Ada 95 are slightly different with regard to the point at
25526 which entities are frozen, and representation pragmas and clauses are
25527 not permitted past the freeze point. This shows up most typically in
25528 the form of an error message complaining that a representation item
25529 appears too late, and the appropriate corrective action is to move
25530 the item nearer to the declaration of the entity to which it refers.
25532 A particular case is that representation pragmas
25535 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25537 cannot be applied to a subprogram body. If necessary, a separate subprogram
25538 declaration must be introduced to which the pragma can be applied.
25540 @item Optional bodies for library packages
25541 In Ada 83, a package that did not require a package body was nevertheless
25542 allowed to have one. This lead to certain surprises in compiling large
25543 systems (situations in which the body could be unexpectedly ignored by the
25544 binder). In Ada 95, if a package does not require a body then it is not
25545 permitted to have a body. To fix this problem, simply remove a redundant
25546 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25547 into the spec that makes the body required. One approach is to add a private
25548 part to the package declaration (if necessary), and define a parameterless
25549 procedure called @code{Requires_Body}, which must then be given a dummy
25550 procedure body in the package body, which then becomes required.
25551 Another approach (assuming that this does not introduce elaboration
25552 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25553 since one effect of this pragma is to require the presence of a package body.
25555 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25556 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25557 @code{Constraint_Error}.
25558 This means that it is illegal to have separate exception handlers for
25559 the two exceptions. The fix is simply to remove the handler for the
25560 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25561 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25563 @item Indefinite subtypes in generics
25564 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25565 as the actual for a generic formal private type, but then the instantiation
25566 would be illegal if there were any instances of declarations of variables
25567 of this type in the generic body. In Ada 95, to avoid this clear violation
25568 of the methodological principle known as the ``contract model'',
25569 the generic declaration explicitly indicates whether
25570 or not such instantiations are permitted. If a generic formal parameter
25571 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25572 type name, then it can be instantiated with indefinite types, but no
25573 stand-alone variables can be declared of this type. Any attempt to declare
25574 such a variable will result in an illegality at the time the generic is
25575 declared. If the @code{(<>)} notation is not used, then it is illegal
25576 to instantiate the generic with an indefinite type.
25577 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25578 It will show up as a compile time error, and
25579 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25582 @node More deterministic semantics
25583 @subsection More deterministic semantics
25587 Conversions from real types to integer types round away from 0. In Ada 83
25588 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
25589 implementation freedom was intended to support unbiased rounding in
25590 statistical applications, but in practice it interfered with portability.
25591 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25592 is required. Numeric code may be affected by this change in semantics.
25593 Note, though, that this issue is no worse than already existed in Ada 83
25594 when porting code from one vendor to another.
25597 The Real-Time Annex introduces a set of policies that define the behavior of
25598 features that were implementation dependent in Ada 83, such as the order in
25599 which open select branches are executed.
25602 @node Changed semantics
25603 @subsection Changed semantics
25606 The worst kind of incompatibility is one where a program that is legal in
25607 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25608 possible in Ada 83. Fortunately this is extremely rare, but the one
25609 situation that you should be alert to is the change in the predefined type
25610 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25613 @item Range of type @code{Character}
25614 The range of @code{Standard.Character} is now the full 256 characters
25615 of Latin-1, whereas in most Ada 83 implementations it was restricted
25616 to 128 characters. Although some of the effects of
25617 this change will be manifest in compile-time rejection of legal
25618 Ada 83 programs it is possible for a working Ada 83 program to have
25619 a different effect in Ada 95, one that was not permitted in Ada 83.
25620 As an example, the expression
25621 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25622 delivers @code{255} as its value.
25623 In general, you should look at the logic of any
25624 character-processing Ada 83 program and see whether it needs to be adapted
25625 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
25626 character handling package that may be relevant if code needs to be adapted
25627 to account for the additional Latin-1 elements.
25628 The desirable fix is to
25629 modify the program to accommodate the full character set, but in some cases
25630 it may be convenient to define a subtype or derived type of Character that
25631 covers only the restricted range.
25635 @node Other language compatibility issues
25636 @subsection Other language compatibility issues
25639 @item @option{-gnat83} switch
25640 All implementations of GNAT provide a switch that causes GNAT to operate
25641 in Ada 83 mode. In this mode, some but not all compatibility problems
25642 of the type described above are handled automatically. For example, the
25643 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
25644 as identifiers as in Ada 83.
25646 in practice, it is usually advisable to make the necessary modifications
25647 to the program to remove the need for using this switch.
25648 See @ref{Compiling Different Versions of Ada}.
25650 @item Support for removed Ada 83 pragmas and attributes
25651 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
25652 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
25653 compilers are allowed, but not required, to implement these missing
25654 elements. In contrast with some other compilers, GNAT implements all
25655 such pragmas and attributes, eliminating this compatibility concern. These
25656 include @code{pragma Interface} and the floating point type attributes
25657 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25661 @node Compatibility between Ada 95 and Ada 2005
25662 @section Compatibility between Ada 95 and Ada 2005
25663 @cindex Compatibility between Ada 95 and Ada 2005
25666 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
25667 a number of incompatibilities. Several are enumerated below;
25668 for a complete description please see the
25669 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
25670 @cite{Rationale for Ada 2005}.
25673 @item New reserved words.
25674 The words @code{interface}, @code{overriding} and @code{synchronized} are
25675 reserved in Ada 2005.
25676 A pre-Ada 2005 program that uses any of these as an identifier will be
25679 @item New declarations in predefined packages.
25680 A number of packages in the predefined environment contain new declarations:
25681 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
25682 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
25683 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
25684 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
25685 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
25686 If an Ada 95 program does a @code{with} and @code{use} of any of these
25687 packages, the new declarations may cause name clashes.
25689 @item Access parameters.
25690 A nondispatching subprogram with an access parameter cannot be renamed
25691 as a dispatching operation. This was permitted in Ada 95.
25693 @item Access types, discriminants, and constraints.
25694 Rule changes in this area have led to some incompatibilities; for example,
25695 constrained subtypes of some access types are not permitted in Ada 2005.
25697 @item Aggregates for limited types.
25698 The allowance of aggregates for limited types in Ada 2005 raises the
25699 possibility of ambiguities in legal Ada 95 programs, since additional types
25700 now need to be considered in expression resolution.
25702 @item Fixed-point multiplication and division.
25703 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
25704 were legal in Ada 95 and invoked the predefined versions of these operations,
25706 The ambiguity may be resolved either by applying a type conversion to the
25707 expression, or by explicitly invoking the operation from package
25710 @item Return-by-reference types.
25711 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
25712 can declare a function returning a value from an anonymous access type.
25716 @node Implementation-dependent characteristics
25717 @section Implementation-dependent characteristics
25719 Although the Ada language defines the semantics of each construct as
25720 precisely as practical, in some situations (for example for reasons of
25721 efficiency, or where the effect is heavily dependent on the host or target
25722 platform) the implementation is allowed some freedom. In porting Ada 83
25723 code to GNAT, you need to be aware of whether / how the existing code
25724 exercised such implementation dependencies. Such characteristics fall into
25725 several categories, and GNAT offers specific support in assisting the
25726 transition from certain Ada 83 compilers.
25729 * Implementation-defined pragmas::
25730 * Implementation-defined attributes::
25732 * Elaboration order::
25733 * Target-specific aspects::
25736 @node Implementation-defined pragmas
25737 @subsection Implementation-defined pragmas
25740 Ada compilers are allowed to supplement the language-defined pragmas, and
25741 these are a potential source of non-portability. All GNAT-defined pragmas
25742 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
25743 Reference Manual}, and these include several that are specifically
25744 intended to correspond to other vendors' Ada 83 pragmas.
25745 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25746 For compatibility with HP Ada 83, GNAT supplies the pragmas
25747 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25748 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25749 and @code{Volatile}.
25750 Other relevant pragmas include @code{External} and @code{Link_With}.
25751 Some vendor-specific
25752 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25754 avoiding compiler rejection of units that contain such pragmas; they are not
25755 relevant in a GNAT context and hence are not otherwise implemented.
25757 @node Implementation-defined attributes
25758 @subsection Implementation-defined attributes
25760 Analogous to pragmas, the set of attributes may be extended by an
25761 implementation. All GNAT-defined attributes are described in
25762 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
25763 Manual}, and these include several that are specifically intended
25764 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
25765 the attribute @code{VADS_Size} may be useful. For compatibility with HP
25766 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25770 @subsection Libraries
25772 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
25773 code uses vendor-specific libraries then there are several ways to manage
25774 this in Ada 95 or Ada 2005:
25777 If the source code for the libraries (specs and bodies) are
25778 available, then the libraries can be migrated in the same way as the
25781 If the source code for the specs but not the bodies are
25782 available, then you can reimplement the bodies.
25784 Some features introduced by Ada 95 obviate the need for library support. For
25785 example most Ada 83 vendors supplied a package for unsigned integers. The
25786 Ada 95 modular type feature is the preferred way to handle this need, so
25787 instead of migrating or reimplementing the unsigned integer package it may
25788 be preferable to retrofit the application using modular types.
25791 @node Elaboration order
25792 @subsection Elaboration order
25794 The implementation can choose any elaboration order consistent with the unit
25795 dependency relationship. This freedom means that some orders can result in
25796 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25797 to invoke a subprogram its body has been elaborated, or to instantiate a
25798 generic before the generic body has been elaborated. By default GNAT
25799 attempts to choose a safe order (one that will not encounter access before
25800 elaboration problems) by implicitly inserting @code{Elaborate} or
25801 @code{Elaborate_All} pragmas where
25802 needed. However, this can lead to the creation of elaboration circularities
25803 and a resulting rejection of the program by gnatbind. This issue is
25804 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25805 In brief, there are several
25806 ways to deal with this situation:
25810 Modify the program to eliminate the circularities, e.g.@: by moving
25811 elaboration-time code into explicitly-invoked procedures
25813 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25814 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25815 @code{Elaborate_All}
25816 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25817 (by selectively suppressing elaboration checks via pragma
25818 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25821 @node Target-specific aspects
25822 @subsection Target-specific aspects
25824 Low-level applications need to deal with machine addresses, data
25825 representations, interfacing with assembler code, and similar issues. If
25826 such an Ada 83 application is being ported to different target hardware (for
25827 example where the byte endianness has changed) then you will need to
25828 carefully examine the program logic; the porting effort will heavily depend
25829 on the robustness of the original design. Moreover, Ada 95 (and thus
25830 Ada 2005) are sometimes
25831 incompatible with typical Ada 83 compiler practices regarding implicit
25832 packing, the meaning of the Size attribute, and the size of access values.
25833 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25835 @node Compatibility with Other Ada Systems
25836 @section Compatibility with Other Ada Systems
25839 If programs avoid the use of implementation dependent and
25840 implementation defined features, as documented in the @cite{Ada
25841 Reference Manual}, there should be a high degree of portability between
25842 GNAT and other Ada systems. The following are specific items which
25843 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
25844 compilers, but do not affect porting code to GNAT@.
25845 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
25846 the following issues may or may not arise for Ada 2005 programs
25847 when other compilers appear.)
25850 @item Ada 83 Pragmas and Attributes
25851 Ada 95 compilers are allowed, but not required, to implement the missing
25852 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25853 GNAT implements all such pragmas and attributes, eliminating this as
25854 a compatibility concern, but some other Ada 95 compilers reject these
25855 pragmas and attributes.
25857 @item Specialized Needs Annexes
25858 GNAT implements the full set of special needs annexes. At the
25859 current time, it is the only Ada 95 compiler to do so. This means that
25860 programs making use of these features may not be portable to other Ada
25861 95 compilation systems.
25863 @item Representation Clauses
25864 Some other Ada 95 compilers implement only the minimal set of
25865 representation clauses required by the Ada 95 reference manual. GNAT goes
25866 far beyond this minimal set, as described in the next section.
25869 @node Representation Clauses
25870 @section Representation Clauses
25873 The Ada 83 reference manual was quite vague in describing both the minimal
25874 required implementation of representation clauses, and also their precise
25875 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
25876 minimal set of capabilities required is still quite limited.
25878 GNAT implements the full required set of capabilities in
25879 Ada 95 and Ada 2005, but also goes much further, and in particular
25880 an effort has been made to be compatible with existing Ada 83 usage to the
25881 greatest extent possible.
25883 A few cases exist in which Ada 83 compiler behavior is incompatible with
25884 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
25885 intentional or accidental dependence on specific implementation dependent
25886 characteristics of these Ada 83 compilers. The following is a list of
25887 the cases most likely to arise in existing Ada 83 code.
25890 @item Implicit Packing
25891 Some Ada 83 compilers allowed a Size specification to cause implicit
25892 packing of an array or record. This could cause expensive implicit
25893 conversions for change of representation in the presence of derived
25894 types, and the Ada design intends to avoid this possibility.
25895 Subsequent AI's were issued to make it clear that such implicit
25896 change of representation in response to a Size clause is inadvisable,
25897 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
25898 Reference Manuals as implementation advice that is followed by GNAT@.
25899 The problem will show up as an error
25900 message rejecting the size clause. The fix is simply to provide
25901 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25902 a Component_Size clause.
25904 @item Meaning of Size Attribute
25905 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
25906 the minimal number of bits required to hold values of the type. For example,
25907 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
25908 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
25909 some 32 in this situation. This problem will usually show up as a compile
25910 time error, but not always. It is a good idea to check all uses of the
25911 'Size attribute when porting Ada 83 code. The GNAT specific attribute
25912 Object_Size can provide a useful way of duplicating the behavior of
25913 some Ada 83 compiler systems.
25915 @item Size of Access Types
25916 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25917 and that therefore it will be the same size as a System.Address value. This
25918 assumption is true for GNAT in most cases with one exception. For the case of
25919 a pointer to an unconstrained array type (where the bounds may vary from one
25920 value of the access type to another), the default is to use a ``fat pointer'',
25921 which is represented as two separate pointers, one to the bounds, and one to
25922 the array. This representation has a number of advantages, including improved
25923 efficiency. However, it may cause some difficulties in porting existing Ada 83
25924 code which makes the assumption that, for example, pointers fit in 32 bits on
25925 a machine with 32-bit addressing.
25927 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25928 access types in this case (where the designated type is an unconstrained array
25929 type). These thin pointers are indeed the same size as a System.Address value.
25930 To specify a thin pointer, use a size clause for the type, for example:
25932 @smallexample @c ada
25933 type X is access all String;
25934 for X'Size use Standard'Address_Size;
25938 which will cause the type X to be represented using a single pointer.
25939 When using this representation, the bounds are right behind the array.
25940 This representation is slightly less efficient, and does not allow quite
25941 such flexibility in the use of foreign pointers or in using the
25942 Unrestricted_Access attribute to create pointers to non-aliased objects.
25943 But for any standard portable use of the access type it will work in
25944 a functionally correct manner and allow porting of existing code.
25945 Note that another way of forcing a thin pointer representation
25946 is to use a component size clause for the element size in an array,
25947 or a record representation clause for an access field in a record.
25951 @c This brief section is only in the non-VMS version
25952 @c The complete chapter on HP Ada is in the VMS version
25953 @node Compatibility with HP Ada 83
25954 @section Compatibility with HP Ada 83
25957 The VMS version of GNAT fully implements all the pragmas and attributes
25958 provided by HP Ada 83, as well as providing the standard HP Ada 83
25959 libraries, including Starlet. In addition, data layouts and parameter
25960 passing conventions are highly compatible. This means that porting
25961 existing HP Ada 83 code to GNAT in VMS systems should be easier than
25962 most other porting efforts. The following are some of the most
25963 significant differences between GNAT and HP Ada 83.
25966 @item Default floating-point representation
25967 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
25968 it is VMS format. GNAT does implement the necessary pragmas
25969 (Long_Float, Float_Representation) for changing this default.
25972 The package System in GNAT exactly corresponds to the definition in the
25973 Ada 95 reference manual, which means that it excludes many of the
25974 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
25975 that contains the additional definitions, and a special pragma,
25976 Extend_System allows this package to be treated transparently as an
25977 extension of package System.
25980 The definitions provided by Aux_DEC are exactly compatible with those
25981 in the HP Ada 83 version of System, with one exception.
25982 HP Ada provides the following declarations:
25984 @smallexample @c ada
25985 TO_ADDRESS (INTEGER)
25986 TO_ADDRESS (UNSIGNED_LONGWORD)
25987 TO_ADDRESS (@i{universal_integer})
25991 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
25992 an extension to Ada 83 not strictly compatible with the reference manual.
25993 In GNAT, we are constrained to be exactly compatible with the standard,
25994 and this means we cannot provide this capability. In HP Ada 83, the
25995 point of this definition is to deal with a call like:
25997 @smallexample @c ada
25998 TO_ADDRESS (16#12777#);
26002 Normally, according to the Ada 83 standard, one would expect this to be
26003 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26004 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
26005 definition using @i{universal_integer} takes precedence.
26007 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26008 is not possible to be 100% compatible. Since there are many programs using
26009 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26010 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26011 declarations provided in the GNAT version of AUX_Dec are:
26013 @smallexample @c ada
26014 function To_Address (X : Integer) return Address;
26015 pragma Pure_Function (To_Address);
26017 function To_Address_Long (X : Unsigned_Longword)
26019 pragma Pure_Function (To_Address_Long);
26023 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26024 change the name to TO_ADDRESS_LONG@.
26026 @item Task_Id values
26027 The Task_Id values assigned will be different in the two systems, and GNAT
26028 does not provide a specified value for the Task_Id of the environment task,
26029 which in GNAT is treated like any other declared task.
26033 For full details on these and other less significant compatibility issues,
26034 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26035 Overview and Comparison on HP Platforms}.
26037 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26038 attributes are recognized, although only a subset of them can sensibly
26039 be implemented. The description of pragmas in @ref{Implementation
26040 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26041 indicates whether or not they are applicable to non-VMS systems.
26045 @node Transitioning to 64-Bit GNAT for OpenVMS
26046 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26049 This section is meant to assist users of pre-2006 @value{EDITION}
26050 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26051 the version of the GNAT technology supplied in 2006 and later for
26052 OpenVMS on both Alpha and I64.
26055 * Introduction to transitioning::
26056 * Migration of 32 bit code::
26057 * Taking advantage of 64 bit addressing::
26058 * Technical details::
26061 @node Introduction to transitioning
26062 @subsection Introduction
26065 64-bit @value{EDITION} for Open VMS has been designed to meet
26070 Providing a full conforming implementation of Ada 95 and Ada 2005
26073 Allowing maximum backward compatibility, thus easing migration of existing
26077 Supplying a path for exploiting the full 64-bit address range
26081 Ada's strong typing semantics has made it
26082 impractical to have different 32-bit and 64-bit modes. As soon as
26083 one object could possibly be outside the 32-bit address space, this
26084 would make it necessary for the @code{System.Address} type to be 64 bits.
26085 In particular, this would cause inconsistencies if 32-bit code is
26086 called from 64-bit code that raises an exception.
26088 This issue has been resolved by always using 64-bit addressing
26089 at the system level, but allowing for automatic conversions between
26090 32-bit and 64-bit addresses where required. Thus users who
26091 do not currently require 64-bit addressing capabilities, can
26092 recompile their code with only minimal changes (and indeed
26093 if the code is written in portable Ada, with no assumptions about
26094 the size of the @code{Address} type, then no changes at all are necessary).
26096 this approach provides a simple, gradual upgrade path to future
26097 use of larger memories than available for 32-bit systems.
26098 Also, newly written applications or libraries will by default
26099 be fully compatible with future systems exploiting 64-bit
26100 addressing capabilities.
26102 @ref{Migration of 32 bit code}, will focus on porting applications
26103 that do not require more than 2 GB of
26104 addressable memory. This code will be referred to as
26105 @emph{32-bit code}.
26106 For applications intending to exploit the full 64-bit address space,
26107 @ref{Taking advantage of 64 bit addressing},
26108 will consider further changes that may be required.
26109 Such code will be referred to below as @emph{64-bit code}.
26111 @node Migration of 32 bit code
26112 @subsection Migration of 32-bit code
26116 * Access types and 32/64-bit allocation::
26117 * Unchecked conversions::
26118 * Predefined constants::
26119 * Interfacing with C::
26120 * 32/64-bit descriptors::
26121 * Experience with source compatibility::
26124 @node Address types
26125 @subsubsection Address types
26128 To solve the problem of mixing 64-bit and 32-bit addressing,
26129 while maintaining maximum backward compatibility, the following
26130 approach has been taken:
26134 @code{System.Address} always has a size of 64 bits
26135 @cindex @code{System.Address} size
26136 @cindex @code{Address} size
26139 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26140 @cindex @code{System.Short_Address} size
26141 @cindex @code{Short_Address} size
26145 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26146 a @code{Short_Address}
26147 may be used where an @code{Address} is required, and vice versa, without
26148 needing explicit type conversions.
26149 By virtue of the Open VMS parameter passing conventions,
26151 and exported subprograms that have 32-bit address parameters are
26152 compatible with those that have 64-bit address parameters.
26153 (See @ref{Making code 64 bit clean} for details.)
26155 The areas that may need attention are those where record types have
26156 been defined that contain components of the type @code{System.Address}, and
26157 where objects of this type are passed to code expecting a record layout with
26160 Different compilers on different platforms cannot be
26161 expected to represent the same type in the same way,
26162 since alignment constraints
26163 and other system-dependent properties affect the compiler's decision.
26164 For that reason, Ada code
26165 generally uses representation clauses to specify the expected
26166 layout where required.
26168 If such a representation clause uses 32 bits for a component having
26169 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26170 will detect that error and produce a specific diagnostic message.
26171 The developer should then determine whether the representation
26172 should be 64 bits or not and make either of two changes:
26173 change the size to 64 bits and leave the type as @code{System.Address}, or
26174 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26175 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26176 required in any code setting or accessing the field; the compiler will
26177 automatically perform any needed conversions between address
26180 @node Access types and 32/64-bit allocation
26181 @subsubsection Access types and 32/64-bit allocation
26182 @cindex 32-bit allocation
26183 @cindex 64-bit allocation
26186 By default, objects designated by access values are always allocated in
26187 the 64-bit address space, and access values themselves are represented
26188 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
26189 is required (for example if the address of an allocated object is assigned
26190 to a @code{Short_Address} variable), then several alternatives are available:
26194 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26195 definition is @code{access T} versus @code{access all T} or
26196 @code{access constant T}), may be declared with a @code{'Size} representation
26197 clause that establishes the size as 32 bits.
26198 In such circumstances allocations for that type will
26199 be from the 32-bit heap. Such a clause is not permitted
26200 for a general access type (declared with @code{access all} or
26201 @code{access constant}) as values of such types must be able to refer
26202 to any object of the designated type, including objects residing outside
26203 the 32-bit address range. Existing @w{Ada 83} code will not contain such
26204 type definitions, however, since general access types were introduced
26208 Switches for @command{GNAT BIND} control whether the internal GNAT
26209 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26210 @cindex @code{__gnat_malloc}
26211 The switches are respectively @option{-H64} (the default) and
26213 @cindex @option{-H32} (@command{gnatbind})
26214 @cindex @option{-H64} (@command{gnatbind})
26217 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26218 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26219 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26220 If this variable is left
26221 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26222 then the default (64-bit) allocation is used.
26223 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26224 then 32-bit allocation is used. The gnatbind qualifiers described above
26225 override this logical name.
26228 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26229 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26230 at a low level to convert explicit calls to @code{malloc} and related
26231 functions from the C run-time library so that they perform allocations
26232 in the 32-bit heap.
26233 Since all internal allocations from GNAT use @code{__gnat_malloc},
26234 this switch is not required unless the program makes explicit calls on
26235 @code{malloc} (or related functions) from interfaced C code.
26239 @node Unchecked conversions
26240 @subsubsection Unchecked conversions
26243 In the case of an @code{Unchecked_Conversion} where the source type is a
26244 64-bit access type or the type @code{System.Address}, and the target
26245 type is a 32-bit type, the compiler will generate a warning.
26246 Even though the generated code will still perform the required
26247 conversions, it is highly recommended in these cases to use
26248 respectively a 32-bit access type or @code{System.Short_Address}
26249 as the source type.
26251 @node Predefined constants
26252 @subsubsection Predefined constants
26255 The following table shows the correspondence between pre-2006 versions of
26256 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26259 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26260 @item @b{Constant} @tab @b{Old} @tab @b{New}
26261 @item @code{System.Word_Size} @tab 32 @tab 64
26262 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
26263 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
26264 @item @code{System.Address_Size} @tab 32 @tab 64
26268 If you need to refer to the specific
26269 memory size of a 32-bit implementation, instead of the
26270 actual memory size, use @code{System.Short_Memory_Size}
26271 rather than @code{System.Memory_Size}.
26272 Similarly, references to @code{System.Address_Size} may need
26273 to be replaced by @code{System.Short_Address'Size}.
26274 The program @command{gnatfind} may be useful for locating
26275 references to the above constants, so that you can verify that they
26278 @node Interfacing with C
26279 @subsubsection Interfacing with C
26282 In order to minimize the impact of the transition to 64-bit addresses on
26283 legacy programs, some fundamental types in the @code{Interfaces.C}
26284 package hierarchy continue to be represented in 32 bits.
26285 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26286 This eases integration with the default HP C layout choices, for example
26287 as found in the system routines in @code{DECC$SHR.EXE}.
26288 Because of this implementation choice, the type fully compatible with
26289 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26290 Depending on the context the compiler will issue a
26291 warning or an error when type @code{Address} is used, alerting the user to a
26292 potential problem. Otherwise 32-bit programs that use
26293 @code{Interfaces.C} should normally not require code modifications
26295 The other issue arising with C interfacing concerns pragma @code{Convention}.
26296 For VMS 64-bit systems, there is an issue of the appropriate default size
26297 of C convention pointers in the absence of an explicit size clause. The HP
26298 C compiler can choose either 32 or 64 bits depending on compiler options.
26299 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26300 clause is given. This proves a better choice for porting 32-bit legacy
26301 applications. In order to have a 64-bit representation, it is necessary to
26302 specify a size representation clause. For example:
26304 @smallexample @c ada
26305 type int_star is access Interfaces.C.int;
26306 pragma Convention(C, int_star);
26307 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
26310 @node 32/64-bit descriptors
26311 @subsubsection 32/64-bit descriptors
26314 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
26315 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26316 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26317 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26318 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26320 If the configuration pragma @code{Short_Descriptors} is supplied, then
26321 all descriptors will be 32 bits.
26322 @cindex pragma @code{Short_Descriptors}
26324 @node Experience with source compatibility
26325 @subsubsection Experience with source compatibility
26328 The Security Server and STARLET on I64 provide an interesting ``test case''
26329 for source compatibility issues, since it is in such system code
26330 where assumptions about @code{Address} size might be expected to occur.
26331 Indeed, there were a small number of occasions in the Security Server
26332 file @file{jibdef.ads}
26333 where a representation clause for a record type specified
26334 32 bits for a component of type @code{Address}.
26335 All of these errors were detected by the compiler.
26336 The repair was obvious and immediate; to simply replace @code{Address} by
26337 @code{Short_Address}.
26339 In the case of STARLET, there were several record types that should
26340 have had representation clauses but did not. In these record types
26341 there was an implicit assumption that an @code{Address} value occupied
26343 These compiled without error, but their usage resulted in run-time error
26344 returns from STARLET system calls.
26345 Future GNAT technology enhancements may include a tool that detects and flags
26346 these sorts of potential source code porting problems.
26348 @c ****************************************
26349 @node Taking advantage of 64 bit addressing
26350 @subsection Taking advantage of 64-bit addressing
26353 * Making code 64 bit clean::
26354 * Allocating memory from the 64 bit storage pool::
26355 * Restrictions on use of 64 bit objects::
26356 * STARLET and other predefined libraries::
26359 @node Making code 64 bit clean
26360 @subsubsection Making code 64-bit clean
26363 In order to prevent problems that may occur when (parts of) a
26364 system start using memory outside the 32-bit address range,
26365 we recommend some additional guidelines:
26369 For imported subprograms that take parameters of the
26370 type @code{System.Address}, ensure that these subprograms can
26371 indeed handle 64-bit addresses. If not, or when in doubt,
26372 change the subprogram declaration to specify
26373 @code{System.Short_Address} instead.
26376 Resolve all warnings related to size mismatches in
26377 unchecked conversions. Failing to do so causes
26378 erroneous execution if the source object is outside
26379 the 32-bit address space.
26382 (optional) Explicitly use the 32-bit storage pool
26383 for access types used in a 32-bit context, or use
26384 generic access types where possible
26385 (@pxref{Restrictions on use of 64 bit objects}).
26389 If these rules are followed, the compiler will automatically insert
26390 any necessary checks to ensure that no addresses or access values
26391 passed to 32-bit code ever refer to objects outside the 32-bit
26393 Any attempt to do this will raise @code{Constraint_Error}.
26395 @node Allocating memory from the 64 bit storage pool
26396 @subsubsection Allocating memory from the 64-bit storage pool
26399 By default, all allocations -- for both pool-specific and general
26400 access types -- use the 64-bit storage pool. To override
26401 this default, for an individual access type or globally, see
26402 @ref{Access types and 32/64-bit allocation}.
26404 @node Restrictions on use of 64 bit objects
26405 @subsubsection Restrictions on use of 64-bit objects
26408 Taking the address of an object allocated from a 64-bit storage pool,
26409 and then passing this address to a subprogram expecting
26410 @code{System.Short_Address},
26411 or assigning it to a variable of type @code{Short_Address}, will cause
26412 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26413 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26414 no exception is raised and execution
26415 will become erroneous.
26417 @node STARLET and other predefined libraries
26418 @subsubsection STARLET and other predefined libraries
26421 All code that comes as part of GNAT is 64-bit clean, but the
26422 restrictions given in @ref{Restrictions on use of 64 bit objects},
26423 still apply. Look at the package
26424 specs to see in which contexts objects allocated
26425 in 64-bit address space are acceptable.
26427 @node Technical details
26428 @subsection Technical details
26431 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26432 Ada standard with respect to the type of @code{System.Address}. Previous
26433 versions of GNAT Pro have defined this type as private and implemented it as a
26436 In order to allow defining @code{System.Short_Address} as a proper subtype,
26437 and to match the implicit sign extension in parameter passing,
26438 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26439 visible (i.e., non-private) integer type.
26440 Standard operations on the type, such as the binary operators ``+'', ``-'',
26441 etc., that take @code{Address} operands and return an @code{Address} result,
26442 have been hidden by declaring these
26443 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26444 ambiguities that would otherwise result from overloading.
26445 (Note that, although @code{Address} is a visible integer type,
26446 good programming practice dictates against exploiting the type's
26447 integer properties such as literals, since this will compromise
26450 Defining @code{Address} as a visible integer type helps achieve
26451 maximum compatibility for existing Ada code,
26452 without sacrificing the capabilities of the 64-bit architecture.
26455 @c ************************************************
26457 @node Microsoft Windows Topics
26458 @appendix Microsoft Windows Topics
26464 This chapter describes topics that are specific to the Microsoft Windows
26465 platforms (NT, 2000, and XP Professional).
26468 * Using GNAT on Windows::
26469 * Using a network installation of GNAT::
26470 * CONSOLE and WINDOWS subsystems::
26471 * Temporary Files::
26472 * Mixed-Language Programming on Windows::
26473 * Windows Calling Conventions::
26474 * Introduction to Dynamic Link Libraries (DLLs)::
26475 * Using DLLs with GNAT::
26476 * Building DLLs with GNAT Project files::
26477 * Building DLLs with GNAT::
26478 * Building DLLs with gnatdll::
26479 * GNAT and Windows Resources::
26480 * Debugging a DLL::
26481 * Setting Stack Size from gnatlink::
26482 * Setting Heap Size from gnatlink::
26485 @node Using GNAT on Windows
26486 @section Using GNAT on Windows
26489 One of the strengths of the GNAT technology is that its tool set
26490 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26491 @code{gdb} debugger, etc.) is used in the same way regardless of the
26494 On Windows this tool set is complemented by a number of Microsoft-specific
26495 tools that have been provided to facilitate interoperability with Windows
26496 when this is required. With these tools:
26501 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26505 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26506 relocatable and non-relocatable DLLs are supported).
26509 You can build Ada DLLs for use in other applications. These applications
26510 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26511 relocatable and non-relocatable Ada DLLs are supported.
26514 You can include Windows resources in your Ada application.
26517 You can use or create COM/DCOM objects.
26521 Immediately below are listed all known general GNAT-for-Windows restrictions.
26522 Other restrictions about specific features like Windows Resources and DLLs
26523 are listed in separate sections below.
26528 It is not possible to use @code{GetLastError} and @code{SetLastError}
26529 when tasking, protected records, or exceptions are used. In these
26530 cases, in order to implement Ada semantics, the GNAT run-time system
26531 calls certain Win32 routines that set the last error variable to 0 upon
26532 success. It should be possible to use @code{GetLastError} and
26533 @code{SetLastError} when tasking, protected record, and exception
26534 features are not used, but it is not guaranteed to work.
26537 It is not possible to link against Microsoft libraries except for
26538 import libraries. Interfacing must be done by the mean of DLLs.
26541 When the compilation environment is located on FAT32 drives, users may
26542 experience recompilations of the source files that have not changed if
26543 Daylight Saving Time (DST) state has changed since the last time files
26544 were compiled. NTFS drives do not have this problem.
26547 No components of the GNAT toolset use any entries in the Windows
26548 registry. The only entries that can be created are file associations and
26549 PATH settings, provided the user has chosen to create them at installation
26550 time, as well as some minimal book-keeping information needed to correctly
26551 uninstall or integrate different GNAT products.
26554 @node Using a network installation of GNAT
26555 @section Using a network installation of GNAT
26558 Make sure the system on which GNAT is installed is accessible from the
26559 current machine, i.e., the install location is shared over the network.
26560 Shared resources are accessed on Windows by means of UNC paths, which
26561 have the format @code{\\server\sharename\path}
26563 In order to use such a network installation, simply add the UNC path of the
26564 @file{bin} directory of your GNAT installation in front of your PATH. For
26565 example, if GNAT is installed in @file{\GNAT} directory of a share location
26566 called @file{c-drive} on a machine @file{LOKI}, the following command will
26569 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26571 Be aware that every compilation using the network installation results in the
26572 transfer of large amounts of data across the network and will likely cause
26573 serious performance penalty.
26575 @node CONSOLE and WINDOWS subsystems
26576 @section CONSOLE and WINDOWS subsystems
26577 @cindex CONSOLE Subsystem
26578 @cindex WINDOWS Subsystem
26582 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26583 (which is the default subsystem) will always create a console when
26584 launching the application. This is not something desirable when the
26585 application has a Windows GUI. To get rid of this console the
26586 application must be using the @code{WINDOWS} subsystem. To do so
26587 the @option{-mwindows} linker option must be specified.
26590 $ gnatmake winprog -largs -mwindows
26593 @node Temporary Files
26594 @section Temporary Files
26595 @cindex Temporary files
26598 It is possible to control where temporary files gets created by setting
26599 the @env{TMP} environment variable. The file will be created:
26602 @item Under the directory pointed to by the @env{TMP} environment variable if
26603 this directory exists.
26605 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
26606 set (or not pointing to a directory) and if this directory exists.
26608 @item Under the current working directory otherwise.
26612 This allows you to determine exactly where the temporary
26613 file will be created. This is particularly useful in networked
26614 environments where you may not have write access to some
26617 @node Mixed-Language Programming on Windows
26618 @section Mixed-Language Programming on Windows
26621 Developing pure Ada applications on Windows is no different than on
26622 other GNAT-supported platforms. However, when developing or porting an
26623 application that contains a mix of Ada and C/C++, the choice of your
26624 Windows C/C++ development environment conditions your overall
26625 interoperability strategy.
26627 If you use @command{gcc} to compile the non-Ada part of your application,
26628 there are no Windows-specific restrictions that affect the overall
26629 interoperability with your Ada code. If you do want to use the
26630 Microsoft tools for your non-Ada code, you have two choices:
26634 Encapsulate your non-Ada code in a DLL to be linked with your Ada
26635 application. In this case, use the Microsoft or whatever environment to
26636 build the DLL and use GNAT to build your executable
26637 (@pxref{Using DLLs with GNAT}).
26640 Or you can encapsulate your Ada code in a DLL to be linked with the
26641 other part of your application. In this case, use GNAT to build the DLL
26642 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
26643 or whatever environment to build your executable.
26646 @node Windows Calling Conventions
26647 @section Windows Calling Conventions
26651 This section pertain only to Win32. On Win64 there is a single native
26652 calling convention. All convention specifiers are ignored on this
26656 * C Calling Convention::
26657 * Stdcall Calling Convention::
26658 * Win32 Calling Convention::
26659 * DLL Calling Convention::
26663 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26664 (callee), there are several ways to push @code{G}'s parameters on the
26665 stack and there are several possible scenarios to clean up the stack
26666 upon @code{G}'s return. A calling convention is an agreed upon software
26667 protocol whereby the responsibilities between the caller (@code{F}) and
26668 the callee (@code{G}) are clearly defined. Several calling conventions
26669 are available for Windows:
26673 @code{C} (Microsoft defined)
26676 @code{Stdcall} (Microsoft defined)
26679 @code{Win32} (GNAT specific)
26682 @code{DLL} (GNAT specific)
26685 @node C Calling Convention
26686 @subsection @code{C} Calling Convention
26689 This is the default calling convention used when interfacing to C/C++
26690 routines compiled with either @command{gcc} or Microsoft Visual C++.
26692 In the @code{C} calling convention subprogram parameters are pushed on the
26693 stack by the caller from right to left. The caller itself is in charge of
26694 cleaning up the stack after the call. In addition, the name of a routine
26695 with @code{C} calling convention is mangled by adding a leading underscore.
26697 The name to use on the Ada side when importing (or exporting) a routine
26698 with @code{C} calling convention is the name of the routine. For
26699 instance the C function:
26702 int get_val (long);
26706 should be imported from Ada as follows:
26708 @smallexample @c ada
26710 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26711 pragma Import (C, Get_Val, External_Name => "get_val");
26716 Note that in this particular case the @code{External_Name} parameter could
26717 have been omitted since, when missing, this parameter is taken to be the
26718 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26719 is missing, as in the above example, this parameter is set to be the
26720 @code{External_Name} with a leading underscore.
26722 When importing a variable defined in C, you should always use the @code{C}
26723 calling convention unless the object containing the variable is part of a
26724 DLL (in which case you should use the @code{Stdcall} calling
26725 convention, @pxref{Stdcall Calling Convention}).
26727 @node Stdcall Calling Convention
26728 @subsection @code{Stdcall} Calling Convention
26731 This convention, which was the calling convention used for Pascal
26732 programs, is used by Microsoft for all the routines in the Win32 API for
26733 efficiency reasons. It must be used to import any routine for which this
26734 convention was specified.
26736 In the @code{Stdcall} calling convention subprogram parameters are pushed
26737 on the stack by the caller from right to left. The callee (and not the
26738 caller) is in charge of cleaning the stack on routine exit. In addition,
26739 the name of a routine with @code{Stdcall} calling convention is mangled by
26740 adding a leading underscore (as for the @code{C} calling convention) and a
26741 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
26742 bytes) of the parameters passed to the routine.
26744 The name to use on the Ada side when importing a C routine with a
26745 @code{Stdcall} calling convention is the name of the C routine. The leading
26746 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
26747 the compiler. For instance the Win32 function:
26750 @b{APIENTRY} int get_val (long);
26754 should be imported from Ada as follows:
26756 @smallexample @c ada
26758 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26759 pragma Import (Stdcall, Get_Val);
26760 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26765 As for the @code{C} calling convention, when the @code{External_Name}
26766 parameter is missing, it is taken to be the name of the Ada entity in lower
26767 case. If instead of writing the above import pragma you write:
26769 @smallexample @c ada
26771 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26772 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26777 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26778 of specifying the @code{External_Name} parameter you specify the
26779 @code{Link_Name} as in the following example:
26781 @smallexample @c ada
26783 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26784 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26789 then the imported routine is @code{retrieve_val}, that is, there is no
26790 decoration at all. No leading underscore and no Stdcall suffix
26791 @code{@@}@code{@var{nn}}.
26794 This is especially important as in some special cases a DLL's entry
26795 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
26796 name generated for a call has it.
26799 It is also possible to import variables defined in a DLL by using an
26800 import pragma for a variable. As an example, if a DLL contains a
26801 variable defined as:
26808 then, to access this variable from Ada you should write:
26810 @smallexample @c ada
26812 My_Var : Interfaces.C.int;
26813 pragma Import (Stdcall, My_Var);
26818 Note that to ease building cross-platform bindings this convention
26819 will be handled as a @code{C} calling convention on non-Windows platforms.
26821 @node Win32 Calling Convention
26822 @subsection @code{Win32} Calling Convention
26825 This convention, which is GNAT-specific is fully equivalent to the
26826 @code{Stdcall} calling convention described above.
26828 @node DLL Calling Convention
26829 @subsection @code{DLL} Calling Convention
26832 This convention, which is GNAT-specific is fully equivalent to the
26833 @code{Stdcall} calling convention described above.
26835 @node Introduction to Dynamic Link Libraries (DLLs)
26836 @section Introduction to Dynamic Link Libraries (DLLs)
26840 A Dynamically Linked Library (DLL) is a library that can be shared by
26841 several applications running under Windows. A DLL can contain any number of
26842 routines and variables.
26844 One advantage of DLLs is that you can change and enhance them without
26845 forcing all the applications that depend on them to be relinked or
26846 recompiled. However, you should be aware than all calls to DLL routines are
26847 slower since, as you will understand below, such calls are indirect.
26849 To illustrate the remainder of this section, suppose that an application
26850 wants to use the services of a DLL @file{API.dll}. To use the services
26851 provided by @file{API.dll} you must statically link against the DLL or
26852 an import library which contains a jump table with an entry for each
26853 routine and variable exported by the DLL. In the Microsoft world this
26854 import library is called @file{API.lib}. When using GNAT this import
26855 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
26856 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26858 After you have linked your application with the DLL or the import library
26859 and you run your application, here is what happens:
26863 Your application is loaded into memory.
26866 The DLL @file{API.dll} is mapped into the address space of your
26867 application. This means that:
26871 The DLL will use the stack of the calling thread.
26874 The DLL will use the virtual address space of the calling process.
26877 The DLL will allocate memory from the virtual address space of the calling
26881 Handles (pointers) can be safely exchanged between routines in the DLL
26882 routines and routines in the application using the DLL.
26886 The entries in the jump table (from the import library @file{libAPI.dll.a}
26887 or @file{API.lib} or automatically created when linking against a DLL)
26888 which is part of your application are initialized with the addresses
26889 of the routines and variables in @file{API.dll}.
26892 If present in @file{API.dll}, routines @code{DllMain} or
26893 @code{DllMainCRTStartup} are invoked. These routines typically contain
26894 the initialization code needed for the well-being of the routines and
26895 variables exported by the DLL.
26899 There is an additional point which is worth mentioning. In the Windows
26900 world there are two kind of DLLs: relocatable and non-relocatable
26901 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26902 in the target application address space. If the addresses of two
26903 non-relocatable DLLs overlap and these happen to be used by the same
26904 application, a conflict will occur and the application will run
26905 incorrectly. Hence, when possible, it is always preferable to use and
26906 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26907 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26908 User's Guide) removes the debugging symbols from the DLL but the DLL can
26909 still be relocated.
26911 As a side note, an interesting difference between Microsoft DLLs and
26912 Unix shared libraries, is the fact that on most Unix systems all public
26913 routines are exported by default in a Unix shared library, while under
26914 Windows it is possible (but not required) to list exported routines in
26915 a definition file (@pxref{The Definition File}).
26917 @node Using DLLs with GNAT
26918 @section Using DLLs with GNAT
26921 * Creating an Ada Spec for the DLL Services::
26922 * Creating an Import Library::
26926 To use the services of a DLL, say @file{API.dll}, in your Ada application
26931 The Ada spec for the routines and/or variables you want to access in
26932 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26933 header files provided with the DLL.
26936 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
26937 mentioned an import library is a statically linked library containing the
26938 import table which will be filled at load time to point to the actual
26939 @file{API.dll} routines. Sometimes you don't have an import library for the
26940 DLL you want to use. The following sections will explain how to build
26941 one. Note that this is optional.
26944 The actual DLL, @file{API.dll}.
26948 Once you have all the above, to compile an Ada application that uses the
26949 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26950 you simply issue the command
26953 $ gnatmake my_ada_app -largs -lAPI
26957 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
26958 tells the GNAT linker to look for an import library. The linker will
26959 look for a library name in this specific order:
26962 @item @file{libAPI.dll.a}
26963 @item @file{API.dll.a}
26964 @item @file{libAPI.a}
26965 @item @file{API.lib}
26966 @item @file{libAPI.dll}
26967 @item @file{API.dll}
26970 The first three are the GNU style import libraries. The third is the
26971 Microsoft style import libraries. The last two are the actual DLL names.
26973 Note that if the Ada package spec for @file{API.dll} contains the
26976 @smallexample @c ada
26977 pragma Linker_Options ("-lAPI");
26981 you do not have to add @option{-largs -lAPI} at the end of the
26982 @command{gnatmake} command.
26984 If any one of the items above is missing you will have to create it
26985 yourself. The following sections explain how to do so using as an
26986 example a fictitious DLL called @file{API.dll}.
26988 @node Creating an Ada Spec for the DLL Services
26989 @subsection Creating an Ada Spec for the DLL Services
26992 A DLL typically comes with a C/C++ header file which provides the
26993 definitions of the routines and variables exported by the DLL. The Ada
26994 equivalent of this header file is a package spec that contains definitions
26995 for the imported entities. If the DLL you intend to use does not come with
26996 an Ada spec you have to generate one such spec yourself. For example if
26997 the header file of @file{API.dll} is a file @file{api.h} containing the
26998 following two definitions:
27010 then the equivalent Ada spec could be:
27012 @smallexample @c ada
27015 with Interfaces.C.Strings;
27020 function Get (Str : C.Strings.Chars_Ptr) return C.int;
27023 pragma Import (C, Get);
27024 pragma Import (DLL, Some_Var);
27031 Note that a variable is
27032 @strong{always imported with a DLL convention}. A function
27033 can have @code{C} or @code{Stdcall} convention.
27034 (@pxref{Windows Calling Conventions}).
27036 @node Creating an Import Library
27037 @subsection Creating an Import Library
27038 @cindex Import library
27041 * The Definition File::
27042 * GNAT-Style Import Library::
27043 * Microsoft-Style Import Library::
27047 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27048 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27049 with @file{API.dll} you can skip this section. You can also skip this
27050 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27051 as in this case it is possible to link directly against the
27052 DLL. Otherwise read on.
27054 @node The Definition File
27055 @subsubsection The Definition File
27056 @cindex Definition file
27060 As previously mentioned, and unlike Unix systems, the list of symbols
27061 that are exported from a DLL must be provided explicitly in Windows.
27062 The main goal of a definition file is precisely that: list the symbols
27063 exported by a DLL. A definition file (usually a file with a @code{.def}
27064 suffix) has the following structure:
27069 @r{[}LIBRARY @var{name}@r{]}
27070 @r{[}DESCRIPTION @var{string}@r{]}
27080 @item LIBRARY @var{name}
27081 This section, which is optional, gives the name of the DLL.
27083 @item DESCRIPTION @var{string}
27084 This section, which is optional, gives a description string that will be
27085 embedded in the import library.
27088 This section gives the list of exported symbols (procedures, functions or
27089 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27090 section of @file{API.def} looks like:
27104 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27105 (@pxref{Windows Calling Conventions}) for a Stdcall
27106 calling convention function in the exported symbols list.
27109 There can actually be other sections in a definition file, but these
27110 sections are not relevant to the discussion at hand.
27112 @node GNAT-Style Import Library
27113 @subsubsection GNAT-Style Import Library
27116 To create a static import library from @file{API.dll} with the GNAT tools
27117 you should proceed as follows:
27121 Create the definition file @file{API.def} (@pxref{The Definition File}).
27122 For that use the @code{dll2def} tool as follows:
27125 $ dll2def API.dll > API.def
27129 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27130 to standard output the list of entry points in the DLL. Note that if
27131 some routines in the DLL have the @code{Stdcall} convention
27132 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27133 suffix then you'll have to edit @file{api.def} to add it, and specify
27134 @option{-k} to @command{gnatdll} when creating the import library.
27137 Here are some hints to find the right @code{@@}@var{nn} suffix.
27141 If you have the Microsoft import library (.lib), it is possible to get
27142 the right symbols by using Microsoft @code{dumpbin} tool (see the
27143 corresponding Microsoft documentation for further details).
27146 $ dumpbin /exports api.lib
27150 If you have a message about a missing symbol at link time the compiler
27151 tells you what symbol is expected. You just have to go back to the
27152 definition file and add the right suffix.
27156 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27157 (@pxref{Using gnatdll}) as follows:
27160 $ gnatdll -e API.def -d API.dll
27164 @code{gnatdll} takes as input a definition file @file{API.def} and the
27165 name of the DLL containing the services listed in the definition file
27166 @file{API.dll}. The name of the static import library generated is
27167 computed from the name of the definition file as follows: if the
27168 definition file name is @var{xyz}@code{.def}, the import library name will
27169 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27170 @option{-e} could have been removed because the name of the definition
27171 file (before the ``@code{.def}'' suffix) is the same as the name of the
27172 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27175 @node Microsoft-Style Import Library
27176 @subsubsection Microsoft-Style Import Library
27179 With GNAT you can either use a GNAT-style or Microsoft-style import
27180 library. A Microsoft import library is needed only if you plan to make an
27181 Ada DLL available to applications developed with Microsoft
27182 tools (@pxref{Mixed-Language Programming on Windows}).
27184 To create a Microsoft-style import library for @file{API.dll} you
27185 should proceed as follows:
27189 Create the definition file @file{API.def} from the DLL. For this use either
27190 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27191 tool (see the corresponding Microsoft documentation for further details).
27194 Build the actual import library using Microsoft's @code{lib} utility:
27197 $ lib -machine:IX86 -def:API.def -out:API.lib
27201 If you use the above command the definition file @file{API.def} must
27202 contain a line giving the name of the DLL:
27209 See the Microsoft documentation for further details about the usage of
27213 @node Building DLLs with GNAT Project files
27214 @section Building DLLs with GNAT Project files
27215 @cindex DLLs, building
27218 There is nothing specific to Windows in the build process.
27219 @pxref{Library Projects}.
27222 Due to a system limitation, it is not possible under Windows to create threads
27223 when inside the @code{DllMain} routine which is used for auto-initialization
27224 of shared libraries, so it is not possible to have library level tasks in SALs.
27226 @node Building DLLs with GNAT
27227 @section Building DLLs with GNAT
27228 @cindex DLLs, building
27231 This section explain how to build DLLs using the GNAT built-in DLL
27232 support. With the following procedure it is straight forward to build
27233 and use DLLs with GNAT.
27237 @item building object files
27239 The first step is to build all objects files that are to be included
27240 into the DLL. This is done by using the standard @command{gnatmake} tool.
27242 @item building the DLL
27244 To build the DLL you must use @command{gcc}'s @option{-shared} and
27245 @option{-shared-libgcc} options. It is quite simple to use this method:
27248 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
27251 It is important to note that in this case all symbols found in the
27252 object files are automatically exported. It is possible to restrict
27253 the set of symbols to export by passing to @command{gcc} a definition
27254 file, @pxref{The Definition File}. For example:
27257 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
27260 If you use a definition file you must export the elaboration procedures
27261 for every package that required one. Elaboration procedures are named
27262 using the package name followed by "_E".
27264 @item preparing DLL to be used
27266 For the DLL to be used by client programs the bodies must be hidden
27267 from it and the .ali set with read-only attribute. This is very important
27268 otherwise GNAT will recompile all packages and will not actually use
27269 the code in the DLL. For example:
27273 $ copy *.ads *.ali api.dll apilib
27274 $ attrib +R apilib\*.ali
27279 At this point it is possible to use the DLL by directly linking
27280 against it. Note that you must use the GNAT shared runtime when using
27281 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27285 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27288 @node Building DLLs with gnatdll
27289 @section Building DLLs with gnatdll
27290 @cindex DLLs, building
27293 * Limitations When Using Ada DLLs from Ada::
27294 * Exporting Ada Entities::
27295 * Ada DLLs and Elaboration::
27296 * Ada DLLs and Finalization::
27297 * Creating a Spec for Ada DLLs::
27298 * Creating the Definition File::
27303 Note that it is preferred to use GNAT Project files
27304 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27305 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27307 This section explains how to build DLLs containing Ada code using
27308 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27309 remainder of this section.
27311 The steps required to build an Ada DLL that is to be used by Ada as well as
27312 non-Ada applications are as follows:
27316 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27317 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27318 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27319 skip this step if you plan to use the Ada DLL only from Ada applications.
27322 Your Ada code must export an initialization routine which calls the routine
27323 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27324 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27325 routine exported by the Ada DLL must be invoked by the clients of the DLL
27326 to initialize the DLL.
27329 When useful, the DLL should also export a finalization routine which calls
27330 routine @code{adafinal} generated by @command{gnatbind} to perform the
27331 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27332 The finalization routine exported by the Ada DLL must be invoked by the
27333 clients of the DLL when the DLL services are no further needed.
27336 You must provide a spec for the services exported by the Ada DLL in each
27337 of the programming languages to which you plan to make the DLL available.
27340 You must provide a definition file listing the exported entities
27341 (@pxref{The Definition File}).
27344 Finally you must use @code{gnatdll} to produce the DLL and the import
27345 library (@pxref{Using gnatdll}).
27349 Note that a relocatable DLL stripped using the @code{strip}
27350 binutils tool will not be relocatable anymore. To build a DLL without
27351 debug information pass @code{-largs -s} to @code{gnatdll}. This
27352 restriction does not apply to a DLL built using a Library Project.
27353 @pxref{Library Projects}.
27355 @node Limitations When Using Ada DLLs from Ada
27356 @subsection Limitations When Using Ada DLLs from Ada
27359 When using Ada DLLs from Ada applications there is a limitation users
27360 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27361 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27362 each Ada DLL includes the services of the GNAT run time that are necessary
27363 to the Ada code inside the DLL. As a result, when an Ada program uses an
27364 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27365 one in the main program.
27367 It is therefore not possible to exchange GNAT run-time objects between the
27368 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27369 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27372 It is completely safe to exchange plain elementary, array or record types,
27373 Windows object handles, etc.
27375 @node Exporting Ada Entities
27376 @subsection Exporting Ada Entities
27377 @cindex Export table
27380 Building a DLL is a way to encapsulate a set of services usable from any
27381 application. As a result, the Ada entities exported by a DLL should be
27382 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27383 any Ada name mangling. As an example here is an Ada package
27384 @code{API}, spec and body, exporting two procedures, a function, and a
27387 @smallexample @c ada
27390 with Interfaces.C; use Interfaces;
27392 Count : C.int := 0;
27393 function Factorial (Val : C.int) return C.int;
27395 procedure Initialize_API;
27396 procedure Finalize_API;
27397 -- Initialization & Finalization routines. More in the next section.
27399 pragma Export (C, Initialize_API);
27400 pragma Export (C, Finalize_API);
27401 pragma Export (C, Count);
27402 pragma Export (C, Factorial);
27408 @smallexample @c ada
27411 package body API is
27412 function Factorial (Val : C.int) return C.int is
27415 Count := Count + 1;
27416 for K in 1 .. Val loop
27422 procedure Initialize_API is
27424 pragma Import (C, Adainit);
27427 end Initialize_API;
27429 procedure Finalize_API is
27430 procedure Adafinal;
27431 pragma Import (C, Adafinal);
27441 If the Ada DLL you are building will only be used by Ada applications
27442 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27443 convention. As an example, the previous package could be written as
27446 @smallexample @c ada
27450 Count : Integer := 0;
27451 function Factorial (Val : Integer) return Integer;
27453 procedure Initialize_API;
27454 procedure Finalize_API;
27455 -- Initialization and Finalization routines.
27461 @smallexample @c ada
27464 package body API is
27465 function Factorial (Val : Integer) return Integer is
27466 Fact : Integer := 1;
27468 Count := Count + 1;
27469 for K in 1 .. Val loop
27476 -- The remainder of this package body is unchanged.
27483 Note that if you do not export the Ada entities with a @code{C} or
27484 @code{Stdcall} convention you will have to provide the mangled Ada names
27485 in the definition file of the Ada DLL
27486 (@pxref{Creating the Definition File}).
27488 @node Ada DLLs and Elaboration
27489 @subsection Ada DLLs and Elaboration
27490 @cindex DLLs and elaboration
27493 The DLL that you are building contains your Ada code as well as all the
27494 routines in the Ada library that are needed by it. The first thing a
27495 user of your DLL must do is elaborate the Ada code
27496 (@pxref{Elaboration Order Handling in GNAT}).
27498 To achieve this you must export an initialization routine
27499 (@code{Initialize_API} in the previous example), which must be invoked
27500 before using any of the DLL services. This elaboration routine must call
27501 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27502 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27503 @code{Initialize_Api} for an example. Note that the GNAT binder is
27504 automatically invoked during the DLL build process by the @code{gnatdll}
27505 tool (@pxref{Using gnatdll}).
27507 When a DLL is loaded, Windows systematically invokes a routine called
27508 @code{DllMain}. It would therefore be possible to call @code{adainit}
27509 directly from @code{DllMain} without having to provide an explicit
27510 initialization routine. Unfortunately, it is not possible to call
27511 @code{adainit} from the @code{DllMain} if your program has library level
27512 tasks because access to the @code{DllMain} entry point is serialized by
27513 the system (that is, only a single thread can execute ``through'' it at a
27514 time), which means that the GNAT run time will deadlock waiting for the
27515 newly created task to complete its initialization.
27517 @node Ada DLLs and Finalization
27518 @subsection Ada DLLs and Finalization
27519 @cindex DLLs and finalization
27522 When the services of an Ada DLL are no longer needed, the client code should
27523 invoke the DLL finalization routine, if available. The DLL finalization
27524 routine is in charge of releasing all resources acquired by the DLL. In the
27525 case of the Ada code contained in the DLL, this is achieved by calling
27526 routine @code{adafinal} generated by the GNAT binder
27527 (@pxref{Binding with Non-Ada Main Programs}).
27528 See the body of @code{Finalize_Api} for an
27529 example. As already pointed out the GNAT binder is automatically invoked
27530 during the DLL build process by the @code{gnatdll} tool
27531 (@pxref{Using gnatdll}).
27533 @node Creating a Spec for Ada DLLs
27534 @subsection Creating a Spec for Ada DLLs
27537 To use the services exported by the Ada DLL from another programming
27538 language (e.g.@: C), you have to translate the specs of the exported Ada
27539 entities in that language. For instance in the case of @code{API.dll},
27540 the corresponding C header file could look like:
27545 extern int *_imp__count;
27546 #define count (*_imp__count)
27547 int factorial (int);
27553 It is important to understand that when building an Ada DLL to be used by
27554 other Ada applications, you need two different specs for the packages
27555 contained in the DLL: one for building the DLL and the other for using
27556 the DLL. This is because the @code{DLL} calling convention is needed to
27557 use a variable defined in a DLL, but when building the DLL, the variable
27558 must have either the @code{Ada} or @code{C} calling convention. As an
27559 example consider a DLL comprising the following package @code{API}:
27561 @smallexample @c ada
27565 Count : Integer := 0;
27567 -- Remainder of the package omitted.
27574 After producing a DLL containing package @code{API}, the spec that
27575 must be used to import @code{API.Count} from Ada code outside of the
27578 @smallexample @c ada
27583 pragma Import (DLL, Count);
27589 @node Creating the Definition File
27590 @subsection Creating the Definition File
27593 The definition file is the last file needed to build the DLL. It lists
27594 the exported symbols. As an example, the definition file for a DLL
27595 containing only package @code{API} (where all the entities are exported
27596 with a @code{C} calling convention) is:
27611 If the @code{C} calling convention is missing from package @code{API},
27612 then the definition file contains the mangled Ada names of the above
27613 entities, which in this case are:
27622 api__initialize_api
27627 @node Using gnatdll
27628 @subsection Using @code{gnatdll}
27632 * gnatdll Example::
27633 * gnatdll behind the Scenes::
27638 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27639 and non-Ada sources that make up your DLL have been compiled.
27640 @code{gnatdll} is actually in charge of two distinct tasks: build the
27641 static import library for the DLL and the actual DLL. The form of the
27642 @code{gnatdll} command is
27646 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27647 @c Expanding @ovar macro inline (explanation in macro def comments)
27648 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27653 where @var{list-of-files} is a list of ALI and object files. The object
27654 file list must be the exact list of objects corresponding to the non-Ada
27655 sources whose services are to be included in the DLL. The ALI file list
27656 must be the exact list of ALI files for the corresponding Ada sources
27657 whose services are to be included in the DLL. If @var{list-of-files} is
27658 missing, only the static import library is generated.
27661 You may specify any of the following switches to @code{gnatdll}:
27664 @c @item -a@ovar{address}
27665 @c Expanding @ovar macro inline (explanation in macro def comments)
27666 @item -a@r{[}@var{address}@r{]}
27667 @cindex @option{-a} (@code{gnatdll})
27668 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27669 specified the default address @var{0x11000000} will be used. By default,
27670 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27671 advise the reader to build relocatable DLL.
27673 @item -b @var{address}
27674 @cindex @option{-b} (@code{gnatdll})
27675 Set the relocatable DLL base address. By default the address is
27678 @item -bargs @var{opts}
27679 @cindex @option{-bargs} (@code{gnatdll})
27680 Binder options. Pass @var{opts} to the binder.
27682 @item -d @var{dllfile}
27683 @cindex @option{-d} (@code{gnatdll})
27684 @var{dllfile} is the name of the DLL. This switch must be present for
27685 @code{gnatdll} to do anything. The name of the generated import library is
27686 obtained algorithmically from @var{dllfile} as shown in the following
27687 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27688 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
27689 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27690 as shown in the following example:
27691 if @var{dllfile} is @code{xyz.dll}, the definition
27692 file used is @code{xyz.def}.
27694 @item -e @var{deffile}
27695 @cindex @option{-e} (@code{gnatdll})
27696 @var{deffile} is the name of the definition file.
27699 @cindex @option{-g} (@code{gnatdll})
27700 Generate debugging information. This information is stored in the object
27701 file and copied from there to the final DLL file by the linker,
27702 where it can be read by the debugger. You must use the
27703 @option{-g} switch if you plan on using the debugger or the symbolic
27707 @cindex @option{-h} (@code{gnatdll})
27708 Help mode. Displays @code{gnatdll} switch usage information.
27711 @cindex @option{-I} (@code{gnatdll})
27712 Direct @code{gnatdll} to search the @var{dir} directory for source and
27713 object files needed to build the DLL.
27714 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27717 @cindex @option{-k} (@code{gnatdll})
27718 Removes the @code{@@}@var{nn} suffix from the import library's exported
27719 names, but keeps them for the link names. You must specify this
27720 option if you want to use a @code{Stdcall} function in a DLL for which
27721 the @code{@@}@var{nn} suffix has been removed. This is the case for most
27722 of the Windows NT DLL for example. This option has no effect when
27723 @option{-n} option is specified.
27725 @item -l @var{file}
27726 @cindex @option{-l} (@code{gnatdll})
27727 The list of ALI and object files used to build the DLL are listed in
27728 @var{file}, instead of being given in the command line. Each line in
27729 @var{file} contains the name of an ALI or object file.
27732 @cindex @option{-n} (@code{gnatdll})
27733 No Import. Do not create the import library.
27736 @cindex @option{-q} (@code{gnatdll})
27737 Quiet mode. Do not display unnecessary messages.
27740 @cindex @option{-v} (@code{gnatdll})
27741 Verbose mode. Display extra information.
27743 @item -largs @var{opts}
27744 @cindex @option{-largs} (@code{gnatdll})
27745 Linker options. Pass @var{opts} to the linker.
27748 @node gnatdll Example
27749 @subsubsection @code{gnatdll} Example
27752 As an example the command to build a relocatable DLL from @file{api.adb}
27753 once @file{api.adb} has been compiled and @file{api.def} created is
27756 $ gnatdll -d api.dll api.ali
27760 The above command creates two files: @file{libapi.dll.a} (the import
27761 library) and @file{api.dll} (the actual DLL). If you want to create
27762 only the DLL, just type:
27765 $ gnatdll -d api.dll -n api.ali
27769 Alternatively if you want to create just the import library, type:
27772 $ gnatdll -d api.dll
27775 @node gnatdll behind the Scenes
27776 @subsubsection @code{gnatdll} behind the Scenes
27779 This section details the steps involved in creating a DLL. @code{gnatdll}
27780 does these steps for you. Unless you are interested in understanding what
27781 goes on behind the scenes, you should skip this section.
27783 We use the previous example of a DLL containing the Ada package @code{API},
27784 to illustrate the steps necessary to build a DLL. The starting point is a
27785 set of objects that will make up the DLL and the corresponding ALI
27786 files. In the case of this example this means that @file{api.o} and
27787 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27792 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27793 the information necessary to generate relocation information for the
27799 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27804 In addition to the base file, the @command{gnatlink} command generates an
27805 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27806 asks @command{gnatlink} to generate the routines @code{DllMain} and
27807 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27808 is loaded into memory.
27811 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27812 export table (@file{api.exp}). The export table contains the relocation
27813 information in a form which can be used during the final link to ensure
27814 that the Windows loader is able to place the DLL anywhere in memory.
27818 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27819 --output-exp api.exp
27824 @code{gnatdll} builds the base file using the new export table. Note that
27825 @command{gnatbind} must be called once again since the binder generated file
27826 has been deleted during the previous call to @command{gnatlink}.
27831 $ gnatlink api -o api.jnk api.exp -mdll
27832 -Wl,--base-file,api.base
27837 @code{gnatdll} builds the new export table using the new base file and
27838 generates the DLL import library @file{libAPI.dll.a}.
27842 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27843 --output-exp api.exp --output-lib libAPI.a
27848 Finally @code{gnatdll} builds the relocatable DLL using the final export
27854 $ gnatlink api api.exp -o api.dll -mdll
27859 @node Using dlltool
27860 @subsubsection Using @code{dlltool}
27863 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27864 DLLs and static import libraries. This section summarizes the most
27865 common @code{dlltool} switches. The form of the @code{dlltool} command
27869 @c $ dlltool @ovar{switches}
27870 @c Expanding @ovar macro inline (explanation in macro def comments)
27871 $ dlltool @r{[}@var{switches}@r{]}
27875 @code{dlltool} switches include:
27878 @item --base-file @var{basefile}
27879 @cindex @option{--base-file} (@command{dlltool})
27880 Read the base file @var{basefile} generated by the linker. This switch
27881 is used to create a relocatable DLL.
27883 @item --def @var{deffile}
27884 @cindex @option{--def} (@command{dlltool})
27885 Read the definition file.
27887 @item --dllname @var{name}
27888 @cindex @option{--dllname} (@command{dlltool})
27889 Gives the name of the DLL. This switch is used to embed the name of the
27890 DLL in the static import library generated by @code{dlltool} with switch
27891 @option{--output-lib}.
27894 @cindex @option{-k} (@command{dlltool})
27895 Kill @code{@@}@var{nn} from exported names
27896 (@pxref{Windows Calling Conventions}
27897 for a discussion about @code{Stdcall}-style symbols.
27900 @cindex @option{--help} (@command{dlltool})
27901 Prints the @code{dlltool} switches with a concise description.
27903 @item --output-exp @var{exportfile}
27904 @cindex @option{--output-exp} (@command{dlltool})
27905 Generate an export file @var{exportfile}. The export file contains the
27906 export table (list of symbols in the DLL) and is used to create the DLL.
27908 @item --output-lib @var{libfile}
27909 @cindex @option{--output-lib} (@command{dlltool})
27910 Generate a static import library @var{libfile}.
27913 @cindex @option{-v} (@command{dlltool})
27916 @item --as @var{assembler-name}
27917 @cindex @option{--as} (@command{dlltool})
27918 Use @var{assembler-name} as the assembler. The default is @code{as}.
27921 @node GNAT and Windows Resources
27922 @section GNAT and Windows Resources
27923 @cindex Resources, windows
27926 * Building Resources::
27927 * Compiling Resources::
27928 * Using Resources::
27932 Resources are an easy way to add Windows specific objects to your
27933 application. The objects that can be added as resources include:
27942 @item string tables
27952 @item version information
27955 For example, a version information resource can be defined as follow and
27956 embedded into an executable or DLL:
27958 A version information resource can be used to embed information into an
27959 executable or a DLL. These information can be viewed using the file properties
27960 from the Windows Explorer. Here is an example of a version information
27966 FILEVERSION 1,0,0,0
27967 PRODUCTVERSION 1,0,0,0
27969 BLOCK "StringFileInfo"
27973 VALUE "CompanyName", "My Company Name"
27974 VALUE "FileDescription", "My application"
27975 VALUE "FileVersion", "1.0"
27976 VALUE "InternalName", "my_app"
27977 VALUE "LegalCopyright", "My Name"
27978 VALUE "OriginalFilename", "my_app.exe"
27979 VALUE "ProductName", "My App"
27980 VALUE "ProductVersion", "1.0"
27984 BLOCK "VarFileInfo"
27986 VALUE "Translation", 0x809, 1252
27992 The value @code{0809} (langID) is for the U.K English language and
27993 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
27997 This section explains how to build, compile and use resources. Note that this
27998 section does not cover all resource objects, for a complete description see
27999 the corresponding Microsoft documentation.
28001 @node Building Resources
28002 @subsection Building Resources
28003 @cindex Resources, building
28006 A resource file is an ASCII file. By convention resource files have an
28007 @file{.rc} extension.
28008 The easiest way to build a resource file is to use Microsoft tools
28009 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28010 @code{dlgedit.exe} to build dialogs.
28011 It is always possible to build an @file{.rc} file yourself by writing a
28014 It is not our objective to explain how to write a resource file. A
28015 complete description of the resource script language can be found in the
28016 Microsoft documentation.
28018 @node Compiling Resources
28019 @subsection Compiling Resources
28022 @cindex Resources, compiling
28025 This section describes how to build a GNAT-compatible (COFF) object file
28026 containing the resources. This is done using the Resource Compiler
28027 @code{windres} as follows:
28030 $ windres -i myres.rc -o myres.o
28034 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28035 file. You can specify an alternate preprocessor (usually named
28036 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28037 parameter. A list of all possible options may be obtained by entering
28038 the command @code{windres} @option{--help}.
28040 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28041 to produce a @file{.res} file (binary resource file). See the
28042 corresponding Microsoft documentation for further details. In this case
28043 you need to use @code{windres} to translate the @file{.res} file to a
28044 GNAT-compatible object file as follows:
28047 $ windres -i myres.res -o myres.o
28050 @node Using Resources
28051 @subsection Using Resources
28052 @cindex Resources, using
28055 To include the resource file in your program just add the
28056 GNAT-compatible object file for the resource(s) to the linker
28057 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28061 $ gnatmake myprog -largs myres.o
28064 @node Debugging a DLL
28065 @section Debugging a DLL
28066 @cindex DLL debugging
28069 * Program and DLL Both Built with GCC/GNAT::
28070 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28074 Debugging a DLL is similar to debugging a standard program. But
28075 we have to deal with two different executable parts: the DLL and the
28076 program that uses it. We have the following four possibilities:
28080 The program and the DLL are built with @code{GCC/GNAT}.
28082 The program is built with foreign tools and the DLL is built with
28085 The program is built with @code{GCC/GNAT} and the DLL is built with
28090 In this section we address only cases one and two above.
28091 There is no point in trying to debug
28092 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28093 information in it. To do so you must use a debugger compatible with the
28094 tools suite used to build the DLL.
28096 @node Program and DLL Both Built with GCC/GNAT
28097 @subsection Program and DLL Both Built with GCC/GNAT
28100 This is the simplest case. Both the DLL and the program have @code{GDB}
28101 compatible debugging information. It is then possible to break anywhere in
28102 the process. Let's suppose here that the main procedure is named
28103 @code{ada_main} and that in the DLL there is an entry point named
28107 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28108 program must have been built with the debugging information (see GNAT -g
28109 switch). Here are the step-by-step instructions for debugging it:
28112 @item Launch @code{GDB} on the main program.
28118 @item Start the program and stop at the beginning of the main procedure
28125 This step is required to be able to set a breakpoint inside the DLL. As long
28126 as the program is not run, the DLL is not loaded. This has the
28127 consequence that the DLL debugging information is also not loaded, so it is not
28128 possible to set a breakpoint in the DLL.
28130 @item Set a breakpoint inside the DLL
28133 (gdb) break ada_dll
28140 At this stage a breakpoint is set inside the DLL. From there on
28141 you can use the standard approach to debug the whole program
28142 (@pxref{Running and Debugging Ada Programs}).
28145 @c This used to work, probably because the DLLs were non-relocatable
28146 @c keep this section around until the problem is sorted out.
28148 To break on the @code{DllMain} routine it is not possible to follow
28149 the procedure above. At the time the program stop on @code{ada_main}
28150 the @code{DllMain} routine as already been called. Either you can use
28151 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28154 @item Launch @code{GDB} on the main program.
28160 @item Load DLL symbols
28163 (gdb) add-sym api.dll
28166 @item Set a breakpoint inside the DLL
28169 (gdb) break ada_dll.adb:45
28172 Note that at this point it is not possible to break using the routine symbol
28173 directly as the program is not yet running. The solution is to break
28174 on the proper line (break in @file{ada_dll.adb} line 45).
28176 @item Start the program
28185 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28186 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28189 * Debugging the DLL Directly::
28190 * Attaching to a Running Process::
28194 In this case things are slightly more complex because it is not possible to
28195 start the main program and then break at the beginning to load the DLL and the
28196 associated DLL debugging information. It is not possible to break at the
28197 beginning of the program because there is no @code{GDB} debugging information,
28198 and therefore there is no direct way of getting initial control. This
28199 section addresses this issue by describing some methods that can be used
28200 to break somewhere in the DLL to debug it.
28203 First suppose that the main procedure is named @code{main} (this is for
28204 example some C code built with Microsoft Visual C) and that there is a
28205 DLL named @code{test.dll} containing an Ada entry point named
28209 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28210 been built with debugging information (see GNAT -g option).
28212 @node Debugging the DLL Directly
28213 @subsubsection Debugging the DLL Directly
28217 Find out the executable starting address
28220 $ objdump --file-header main.exe
28223 The starting address is reported on the last line. For example:
28226 main.exe: file format pei-i386
28227 architecture: i386, flags 0x0000010a:
28228 EXEC_P, HAS_DEBUG, D_PAGED
28229 start address 0x00401010
28233 Launch the debugger on the executable.
28240 Set a breakpoint at the starting address, and launch the program.
28243 $ (gdb) break *0x00401010
28247 The program will stop at the given address.
28250 Set a breakpoint on a DLL subroutine.
28253 (gdb) break ada_dll.adb:45
28256 Or if you want to break using a symbol on the DLL, you need first to
28257 select the Ada language (language used by the DLL).
28260 (gdb) set language ada
28261 (gdb) break ada_dll
28265 Continue the program.
28272 This will run the program until it reaches the breakpoint that has been
28273 set. From that point you can use the standard way to debug a program
28274 as described in (@pxref{Running and Debugging Ada Programs}).
28279 It is also possible to debug the DLL by attaching to a running process.
28281 @node Attaching to a Running Process
28282 @subsubsection Attaching to a Running Process
28283 @cindex DLL debugging, attach to process
28286 With @code{GDB} it is always possible to debug a running process by
28287 attaching to it. It is possible to debug a DLL this way. The limitation
28288 of this approach is that the DLL must run long enough to perform the
28289 attach operation. It may be useful for instance to insert a time wasting
28290 loop in the code of the DLL to meet this criterion.
28294 @item Launch the main program @file{main.exe}.
28300 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28301 that the process PID for @file{main.exe} is 208.
28309 @item Attach to the running process to be debugged.
28315 @item Load the process debugging information.
28318 (gdb) symbol-file main.exe
28321 @item Break somewhere in the DLL.
28324 (gdb) break ada_dll
28327 @item Continue process execution.
28336 This last step will resume the process execution, and stop at
28337 the breakpoint we have set. From there you can use the standard
28338 approach to debug a program as described in
28339 (@pxref{Running and Debugging Ada Programs}).
28341 @node Setting Stack Size from gnatlink
28342 @section Setting Stack Size from @command{gnatlink}
28345 It is possible to specify the program stack size at link time. On modern
28346 versions of Windows, starting with XP, this is mostly useful to set the size of
28347 the main stack (environment task). The other task stacks are set with pragma
28348 Storage_Size or with the @command{gnatbind -d} command.
28350 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28351 reserve size of individual tasks, the link-time stack size applies to all
28352 tasks, and pragma Storage_Size has no effect.
28353 In particular, Stack Overflow checks are made against this
28354 link-time specified size.
28356 This setting can be done with
28357 @command{gnatlink} using either:
28361 @item using @option{-Xlinker} linker option
28364 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28367 This sets the stack reserve size to 0x10000 bytes and the stack commit
28368 size to 0x1000 bytes.
28370 @item using @option{-Wl} linker option
28373 $ gnatlink hello -Wl,--stack=0x1000000
28376 This sets the stack reserve size to 0x1000000 bytes. Note that with
28377 @option{-Wl} option it is not possible to set the stack commit size
28378 because the coma is a separator for this option.
28382 @node Setting Heap Size from gnatlink
28383 @section Setting Heap Size from @command{gnatlink}
28386 Under Windows systems, it is possible to specify the program heap size from
28387 @command{gnatlink} using either:
28391 @item using @option{-Xlinker} linker option
28394 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28397 This sets the heap reserve size to 0x10000 bytes and the heap commit
28398 size to 0x1000 bytes.
28400 @item using @option{-Wl} linker option
28403 $ gnatlink hello -Wl,--heap=0x1000000
28406 This sets the heap reserve size to 0x1000000 bytes. Note that with
28407 @option{-Wl} option it is not possible to set the heap commit size
28408 because the coma is a separator for this option.
28414 @c **********************************
28415 @c * GNU Free Documentation License *
28416 @c **********************************
28418 @c GNU Free Documentation License
28420 @node Index,,GNU Free Documentation License, Top
28426 @c Put table of contents at end, otherwise it precedes the "title page" in
28427 @c the .txt version
28428 @c Edit the pdf file to move the contents to the beginning, after the title