1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2011, Free Software Foundation, Inc. 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.
4133 @item ^-gnateI^/MULTI_UNIT_INDEX=^@var{nnn}
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 @var{nnn}. @var{nnn} needs to be a positive number and need
4137 to 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 compatibility issues.}
5784 @cindex @option{-gnatwy} (@command{gcc})
5785 @cindex Ada compatibility issues warnings
5786 For the most part, newer versions of Ada are upwards compatible
5787 with older versions. For example, Ada 2005 programs will almost
5788 always work when compiled as Ada 2012.
5789 However there are some exceptions (for example the fact that
5790 @code{some} is now a reserved word in Ada 2012). This
5791 switch activates several warnings to help in identifying
5792 and correcting such incompatibilities. The default is that
5793 these warnings are generated. Note that at one point Ada 2005
5794 was called Ada 0Y, hence the choice of character.
5795 This warning can also be turned on using @option{-gnatwa}.
5798 @emph{Disable warnings for Ada compatibility issues.}
5799 @cindex @option{-gnatwY} (@command{gcc})
5800 @cindex Ada compatibility issues warnings
5801 This switch suppresses the warnings intended to help in identifying
5802 incompatibilities between Ada language versions.
5805 @emph{Activate warnings on unchecked conversions.}
5806 @cindex @option{-gnatwz} (@command{gcc})
5807 @cindex Unchecked_Conversion warnings
5808 This switch activates warnings for unchecked conversions
5809 where the types are known at compile time to have different
5811 is that such warnings are generated. Warnings are also
5812 generated for subprogram pointers with different conventions,
5813 and, on VMS only, for data pointers with different conventions.
5814 This warning can also be turned on using @option{-gnatwa}.
5817 @emph{Suppress warnings on unchecked conversions.}
5818 @cindex @option{-gnatwZ} (@command{gcc})
5819 This switch suppresses warnings for unchecked conversions
5820 where the types are known at compile time to have different
5821 sizes or conventions.
5823 @item ^-Wunused^WARNINGS=UNUSED^
5824 @cindex @option{-Wunused}
5825 The warnings controlled by the @option{-gnatw} switch are generated by
5826 the front end of the compiler. The @option{GCC} back end can provide
5827 additional warnings and they are controlled by the @option{-W} switch.
5828 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5829 warnings for entities that are declared but not referenced.
5831 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5832 @cindex @option{-Wuninitialized}
5833 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5834 the back end warning for uninitialized variables. This switch must be
5835 used in conjunction with an optimization level greater than zero.
5837 @item -Wstack-usage=@var{len}
5838 @cindex @option{-Wstack-usage}
5839 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5840 See @ref{Static Stack Usage Analysis} for details.
5842 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5843 @cindex @option{-Wall}
5844 This switch enables most warnings from the @option{GCC} back end.
5845 The code generator detects a number of warning situations that are missed
5846 by the @option{GNAT} front end, and this switch can be used to activate them.
5847 The use of this switch also sets the default front end warning mode to
5848 @option{-gnatwa}, that is, most front end warnings activated as well.
5850 @item ^-w^/NO_BACK_END_WARNINGS^
5852 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5853 The use of this switch also sets the default front end warning mode to
5854 @option{-gnatws}, that is, front end warnings suppressed as well.
5860 A string of warning parameters can be used in the same parameter. For example:
5867 will turn on all optional warnings except for elaboration pragma warnings,
5868 and also specify that warnings should be treated as errors.
5870 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5895 @node Debugging and Assertion Control
5896 @subsection Debugging and Assertion Control
5900 @cindex @option{-gnata} (@command{gcc})
5906 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5907 are ignored. This switch, where @samp{a} stands for assert, causes
5908 @code{Assert} and @code{Debug} pragmas to be activated.
5910 The pragmas have the form:
5914 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5915 @var{static-string-expression}@r{]})
5916 @b{pragma} Debug (@var{procedure call})
5921 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5922 If the result is @code{True}, the pragma has no effect (other than
5923 possible side effects from evaluating the expression). If the result is
5924 @code{False}, the exception @code{Assert_Failure} declared in the package
5925 @code{System.Assertions} is
5926 raised (passing @var{static-string-expression}, if present, as the
5927 message associated with the exception). If no string expression is
5928 given the default is a string giving the file name and line number
5931 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5932 @code{pragma Debug} may appear within a declaration sequence, allowing
5933 debugging procedures to be called between declarations.
5936 @item /DEBUG@r{[}=debug-level@r{]}
5938 Specifies how much debugging information is to be included in
5939 the resulting object file where 'debug-level' is one of the following:
5942 Include both debugger symbol records and traceback
5944 This is the default setting.
5946 Include both debugger symbol records and traceback in
5949 Excludes both debugger symbol records and traceback
5950 the object file. Same as /NODEBUG.
5952 Includes only debugger symbol records in the object
5953 file. Note that this doesn't include traceback information.
5958 @node Validity Checking
5959 @subsection Validity Checking
5960 @findex Validity Checking
5963 The Ada Reference Manual defines the concept of invalid values (see
5964 RM 13.9.1). The primary source of invalid values is uninitialized
5965 variables. A scalar variable that is left uninitialized may contain
5966 an invalid value; the concept of invalid does not apply to access or
5969 It is an error to read an invalid value, but the RM does not require
5970 run-time checks to detect such errors, except for some minimal
5971 checking to prevent erroneous execution (i.e. unpredictable
5972 behavior). This corresponds to the @option{-gnatVd} switch below,
5973 which is the default. For example, by default, if the expression of a
5974 case statement is invalid, it will raise Constraint_Error rather than
5975 causing a wild jump, and if an array index on the left-hand side of an
5976 assignment is invalid, it will raise Constraint_Error rather than
5977 overwriting an arbitrary memory location.
5979 The @option{-gnatVa} may be used to enable additional validity checks,
5980 which are not required by the RM. These checks are often very
5981 expensive (which is why the RM does not require them). These checks
5982 are useful in tracking down uninitialized variables, but they are
5983 not usually recommended for production builds.
5985 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5986 control; you can enable whichever validity checks you desire. However,
5987 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5988 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5989 sufficient for non-debugging use.
5991 The @option{-gnatB} switch tells the compiler to assume that all
5992 values are valid (that is, within their declared subtype range)
5993 except in the context of a use of the Valid attribute. This means
5994 the compiler can generate more efficient code, since the range
5995 of values is better known at compile time. However, an uninitialized
5996 variable can cause wild jumps and memory corruption in this mode.
5998 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5999 checking mode as described below.
6001 The @code{x} argument is a string of letters that
6002 indicate validity checks that are performed or not performed in addition
6003 to the default checks required by Ada as described above.
6006 The options allowed for this qualifier
6007 indicate validity checks that are performed or not performed in addition
6008 to the default checks required by Ada as described above.
6014 @emph{All validity checks.}
6015 @cindex @option{-gnatVa} (@command{gcc})
6016 All validity checks are turned on.
6018 That is, @option{-gnatVa} is
6019 equivalent to @option{gnatVcdfimorst}.
6023 @emph{Validity checks for copies.}
6024 @cindex @option{-gnatVc} (@command{gcc})
6025 The right hand side of assignments, and the initializing values of
6026 object declarations are validity checked.
6029 @emph{Default (RM) validity checks.}
6030 @cindex @option{-gnatVd} (@command{gcc})
6031 Some validity checks are done by default following normal Ada semantics
6033 A check is done in case statements that the expression is within the range
6034 of the subtype. If it is not, Constraint_Error is raised.
6035 For assignments to array components, a check is done that the expression used
6036 as index is within the range. If it is not, Constraint_Error is raised.
6037 Both these validity checks may be turned off using switch @option{-gnatVD}.
6038 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6039 switch @option{-gnatVd} will leave the checks turned on.
6040 Switch @option{-gnatVD} should be used only if you are sure that all such
6041 expressions have valid values. If you use this switch and invalid values
6042 are present, then the program is erroneous, and wild jumps or memory
6043 overwriting may occur.
6046 @emph{Validity checks for elementary components.}
6047 @cindex @option{-gnatVe} (@command{gcc})
6048 In the absence of this switch, assignments to record or array components are
6049 not validity checked, even if validity checks for assignments generally
6050 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6051 require valid data, but assignment of individual components does. So for
6052 example, there is a difference between copying the elements of an array with a
6053 slice assignment, compared to assigning element by element in a loop. This
6054 switch allows you to turn off validity checking for components, even when they
6055 are assigned component by component.
6058 @emph{Validity checks for floating-point values.}
6059 @cindex @option{-gnatVf} (@command{gcc})
6060 In the absence of this switch, validity checking occurs only for discrete
6061 values. If @option{-gnatVf} is specified, then validity checking also applies
6062 for floating-point values, and NaNs and infinities are considered invalid,
6063 as well as out of range values for constrained types. Note that this means
6064 that standard IEEE infinity mode is not allowed. The exact contexts
6065 in which floating-point values are checked depends on the setting of other
6066 options. For example,
6067 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6068 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6069 (the order does not matter) specifies that floating-point parameters of mode
6070 @code{in} should be validity checked.
6073 @emph{Validity checks for @code{in} mode parameters}
6074 @cindex @option{-gnatVi} (@command{gcc})
6075 Arguments for parameters of mode @code{in} are validity checked in function
6076 and procedure calls at the point of call.
6079 @emph{Validity checks for @code{in out} mode parameters.}
6080 @cindex @option{-gnatVm} (@command{gcc})
6081 Arguments for parameters of mode @code{in out} are validity checked in
6082 procedure calls at the point of call. The @code{'m'} here stands for
6083 modify, since this concerns parameters that can be modified by the call.
6084 Note that there is no specific option to test @code{out} parameters,
6085 but any reference within the subprogram will be tested in the usual
6086 manner, and if an invalid value is copied back, any reference to it
6087 will be subject to validity checking.
6090 @emph{No validity checks.}
6091 @cindex @option{-gnatVn} (@command{gcc})
6092 This switch turns off all validity checking, including the default checking
6093 for case statements and left hand side subscripts. Note that the use of
6094 the switch @option{-gnatp} suppresses all run-time checks, including
6095 validity checks, and thus implies @option{-gnatVn}. When this switch
6096 is used, it cancels any other @option{-gnatV} previously issued.
6099 @emph{Validity checks for operator and attribute operands.}
6100 @cindex @option{-gnatVo} (@command{gcc})
6101 Arguments for predefined operators and attributes are validity checked.
6102 This includes all operators in package @code{Standard},
6103 the shift operators defined as intrinsic in package @code{Interfaces}
6104 and operands for attributes such as @code{Pos}. Checks are also made
6105 on individual component values for composite comparisons, and on the
6106 expressions in type conversions and qualified expressions. Checks are
6107 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6110 @emph{Validity checks for parameters.}
6111 @cindex @option{-gnatVp} (@command{gcc})
6112 This controls the treatment of parameters within a subprogram (as opposed
6113 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6114 of parameters on a call. If either of these call options is used, then
6115 normally an assumption is made within a subprogram that the input arguments
6116 have been validity checking at the point of call, and do not need checking
6117 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6118 is not made, and parameters are not assumed to be valid, so their validity
6119 will be checked (or rechecked) within the subprogram.
6122 @emph{Validity checks for function returns.}
6123 @cindex @option{-gnatVr} (@command{gcc})
6124 The expression in @code{return} statements in functions is validity
6128 @emph{Validity checks for subscripts.}
6129 @cindex @option{-gnatVs} (@command{gcc})
6130 All subscripts expressions are checked for validity, whether they appear
6131 on the right side or left side (in default mode only left side subscripts
6132 are validity checked).
6135 @emph{Validity checks for tests.}
6136 @cindex @option{-gnatVt} (@command{gcc})
6137 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6138 statements are checked, as well as guard expressions in entry calls.
6143 The @option{-gnatV} switch may be followed by
6144 ^a string of letters^a list of options^
6145 to turn on a series of validity checking options.
6147 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6148 specifies that in addition to the default validity checking, copies and
6149 function return expressions are to be validity checked.
6150 In order to make it easier
6151 to specify the desired combination of effects,
6153 the upper case letters @code{CDFIMORST} may
6154 be used to turn off the corresponding lower case option.
6157 the prefix @code{NO} on an option turns off the corresponding validity
6160 @item @code{NOCOPIES}
6161 @item @code{NODEFAULT}
6162 @item @code{NOFLOATS}
6163 @item @code{NOIN_PARAMS}
6164 @item @code{NOMOD_PARAMS}
6165 @item @code{NOOPERANDS}
6166 @item @code{NORETURNS}
6167 @item @code{NOSUBSCRIPTS}
6168 @item @code{NOTESTS}
6172 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6173 turns on all validity checking options except for
6174 checking of @code{@b{in out}} procedure arguments.
6176 The specification of additional validity checking generates extra code (and
6177 in the case of @option{-gnatVa} the code expansion can be substantial).
6178 However, these additional checks can be very useful in detecting
6179 uninitialized variables, incorrect use of unchecked conversion, and other
6180 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6181 is useful in conjunction with the extra validity checking, since this
6182 ensures that wherever possible uninitialized variables have invalid values.
6184 See also the pragma @code{Validity_Checks} which allows modification of
6185 the validity checking mode at the program source level, and also allows for
6186 temporary disabling of validity checks.
6188 @node Style Checking
6189 @subsection Style Checking
6190 @findex Style checking
6193 The @option{-gnaty^x^(option,option,@dots{})^} switch
6194 @cindex @option{-gnaty} (@command{gcc})
6195 causes the compiler to
6196 enforce specified style rules. A limited set of style rules has been used
6197 in writing the GNAT sources themselves. This switch allows user programs
6198 to activate all or some of these checks. If the source program fails a
6199 specified style check, an appropriate message is given, preceded by
6200 the character sequence ``(style)''. This message does not prevent
6201 successful compilation (unless the @option{-gnatwe} switch is used).
6203 Note that this is by no means intended to be a general facility for
6204 checking arbitrary coding standards. It is simply an embedding of the
6205 style rules we have chosen for the GNAT sources. If you are starting
6206 a project which does not have established style standards, you may
6207 find it useful to adopt the entire set of GNAT coding standards, or
6208 some subset of them. If you already have an established set of coding
6209 standards, then it may be that selected style checking options do
6210 indeed correspond to choices you have made, but for general checking
6211 of an existing set of coding rules, you should look to the gnatcheck
6212 tool, which is designed for that purpose.
6215 @code{(option,option,@dots{})} is a sequence of keywords
6218 The string @var{x} is a sequence of letters or digits
6220 indicating the particular style
6221 checks to be performed. The following checks are defined:
6226 @emph{Specify indentation level.}
6227 If a digit from 1-9 appears
6228 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6229 then proper indentation is checked, with the digit indicating the
6230 indentation level required. A value of zero turns off this style check.
6231 The general style of required indentation is as specified by
6232 the examples in the Ada Reference Manual. Full line comments must be
6233 aligned with the @code{--} starting on a column that is a multiple of
6234 the alignment level, or they may be aligned the same way as the following
6235 non-blank line (this is useful when full line comments appear in the middle
6239 @emph{Check attribute casing.}
6240 Attribute names, including the case of keywords such as @code{digits}
6241 used as attributes names, must be written in mixed case, that is, the
6242 initial letter and any letter following an underscore must be uppercase.
6243 All other letters must be lowercase.
6245 @item ^A^ARRAY_INDEXES^
6246 @emph{Use of array index numbers in array attributes.}
6247 When using the array attributes First, Last, Range,
6248 or Length, the index number must be omitted for one-dimensional arrays
6249 and is required for multi-dimensional arrays.
6252 @emph{Blanks not allowed at statement end.}
6253 Trailing blanks are not allowed at the end of statements. The purpose of this
6254 rule, together with h (no horizontal tabs), is to enforce a canonical format
6255 for the use of blanks to separate source tokens.
6257 @item ^B^BOOLEAN_OPERATORS^
6258 @emph{Check Boolean operators.}
6259 The use of AND/OR operators is not permitted except in the cases of modular
6260 operands, array operands, and simple stand-alone boolean variables or
6261 boolean constants. In all other cases AND THEN/OR ELSE are required.
6263 @item ^c^COMMENTS^ (double space)
6264 @emph{Check comments, double space.}
6265 Comments must meet the following set of rules:
6270 The ``@code{--}'' that starts the column must either start in column one,
6271 or else at least one blank must precede this sequence.
6274 Comments that follow other tokens on a line must have at least one blank
6275 following the ``@code{--}'' at the start of the comment.
6278 Full line comments must have at least two blanks following the
6279 ``@code{--}'' that starts the comment, with the following exceptions.
6282 A line consisting only of the ``@code{--}'' characters, possibly preceded
6283 by blanks is permitted.
6286 A comment starting with ``@code{--x}'' where @code{x} is a special character
6288 This allows proper processing of the output generated by specialized tools
6289 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6291 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6292 special character is defined as being in one of the ASCII ranges
6293 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6294 Note that this usage is not permitted
6295 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6298 A line consisting entirely of minus signs, possibly preceded by blanks, is
6299 permitted. This allows the construction of box comments where lines of minus
6300 signs are used to form the top and bottom of the box.
6303 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6304 least one blank follows the initial ``@code{--}''. Together with the preceding
6305 rule, this allows the construction of box comments, as shown in the following
6308 ---------------------------
6309 -- This is a box comment --
6310 -- with two text lines. --
6311 ---------------------------
6315 @item ^C^COMMENTS1^ (single space)
6316 @emph{Check comments, single space.}
6317 This is identical to @code{^c^COMMENTS^} except that only one space
6318 is required following the @code{--} of a comment instead of two.
6320 @item ^d^DOS_LINE_ENDINGS^
6321 @emph{Check no DOS line terminators present.}
6322 All lines must be terminated by a single ASCII.LF
6323 character (in particular the DOS line terminator sequence CR/LF is not
6327 @emph{Check end/exit labels.}
6328 Optional labels on @code{end} statements ending subprograms and on
6329 @code{exit} statements exiting named loops, are required to be present.
6332 @emph{No form feeds or vertical tabs.}
6333 Neither form feeds nor vertical tab characters are permitted
6337 @emph{GNAT style mode}
6338 The set of style check switches is set to match that used by the GNAT sources.
6339 This may be useful when developing code that is eventually intended to be
6340 incorporated into GNAT. For further details, see GNAT sources.
6343 @emph{No horizontal tabs.}
6344 Horizontal tab characters are not permitted in the source text.
6345 Together with the b (no blanks at end of line) check, this
6346 enforces a canonical form for the use of blanks to separate
6350 @emph{Check if-then layout.}
6351 The keyword @code{then} must appear either on the same
6352 line as corresponding @code{if}, or on a line on its own, lined
6353 up under the @code{if} with at least one non-blank line in between
6354 containing all or part of the condition to be tested.
6357 @emph{check mode IN keywords}
6358 Mode @code{in} (the default mode) is not
6359 allowed to be given explicitly. @code{in out} is fine,
6360 but not @code{in} on its own.
6363 @emph{Check keyword casing.}
6364 All keywords must be in lower case (with the exception of keywords
6365 such as @code{digits} used as attribute names to which this check
6369 @emph{Check layout.}
6370 Layout of statement and declaration constructs must follow the
6371 recommendations in the Ada Reference Manual, as indicated by the
6372 form of the syntax rules. For example an @code{else} keyword must
6373 be lined up with the corresponding @code{if} keyword.
6375 There are two respects in which the style rule enforced by this check
6376 option are more liberal than those in the Ada Reference Manual. First
6377 in the case of record declarations, it is permissible to put the
6378 @code{record} keyword on the same line as the @code{type} keyword, and
6379 then the @code{end} in @code{end record} must line up under @code{type}.
6380 This is also permitted when the type declaration is split on two lines.
6381 For example, any of the following three layouts is acceptable:
6383 @smallexample @c ada
6406 Second, in the case of a block statement, a permitted alternative
6407 is to put the block label on the same line as the @code{declare} or
6408 @code{begin} keyword, and then line the @code{end} keyword up under
6409 the block label. For example both the following are permitted:
6411 @smallexample @c ada
6429 The same alternative format is allowed for loops. For example, both of
6430 the following are permitted:
6432 @smallexample @c ada
6434 Clear : while J < 10 loop
6445 @item ^Lnnn^MAX_NESTING=nnn^
6446 @emph{Set maximum nesting level}
6447 The maximum level of nesting of constructs (including subprograms, loops,
6448 blocks, packages, and conditionals) may not exceed the given value
6449 @option{nnn}. A value of zero disconnects this style check.
6451 @item ^m^LINE_LENGTH^
6452 @emph{Check maximum line length.}
6453 The length of source lines must not exceed 79 characters, including
6454 any trailing blanks. The value of 79 allows convenient display on an
6455 80 character wide device or window, allowing for possible special
6456 treatment of 80 character lines. Note that this count is of
6457 characters in the source text. This means that a tab character counts
6458 as one character in this count but a wide character sequence counts as
6459 a single character (however many bytes are needed in the encoding).
6461 @item ^Mnnn^MAX_LENGTH=nnn^
6462 @emph{Set maximum line length.}
6463 The length of lines must not exceed the
6464 given value @option{nnn}. The maximum value that can be specified is 32767.
6466 @item ^n^STANDARD_CASING^
6467 @emph{Check casing of entities in Standard.}
6468 Any identifier from Standard must be cased
6469 to match the presentation in the Ada Reference Manual (for example,
6470 @code{Integer} and @code{ASCII.NUL}).
6473 @emph{Turn off all style checks}
6474 All style check options are turned off.
6476 @item ^o^ORDERED_SUBPROGRAMS^
6477 @emph{Check order of subprogram bodies.}
6478 All subprogram bodies in a given scope
6479 (e.g.@: a package body) must be in alphabetical order. The ordering
6480 rule uses normal Ada rules for comparing strings, ignoring casing
6481 of letters, except that if there is a trailing numeric suffix, then
6482 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6485 @item ^O^OVERRIDING_INDICATORS^
6486 @emph{Check that overriding subprograms are explicitly marked as such.}
6487 The declaration of a primitive operation of a type extension that overrides
6488 an inherited operation must carry an overriding indicator.
6491 @emph{Check pragma casing.}
6492 Pragma names must be written in mixed case, that is, the
6493 initial letter and any letter following an underscore must be uppercase.
6494 All other letters must be lowercase.
6496 @item ^r^REFERENCES^
6497 @emph{Check references.}
6498 All identifier references must be cased in the same way as the
6499 corresponding declaration. No specific casing style is imposed on
6500 identifiers. The only requirement is for consistency of references
6503 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6504 @emph{Check no statements after THEN/ELSE.}
6505 No statements are allowed
6506 on the same line as a THEN or ELSE keyword following the
6507 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6508 and a special exception allows a pragma to appear after ELSE.
6511 @emph{Check separate specs.}
6512 Separate declarations (``specs'') are required for subprograms (a
6513 body is not allowed to serve as its own declaration). The only
6514 exception is that parameterless library level procedures are
6515 not required to have a separate declaration. This exception covers
6516 the most frequent form of main program procedures.
6519 @emph{Check token spacing.}
6520 The following token spacing rules are enforced:
6525 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6528 The token @code{=>} must be surrounded by spaces.
6531 The token @code{<>} must be preceded by a space or a left parenthesis.
6534 Binary operators other than @code{**} must be surrounded by spaces.
6535 There is no restriction on the layout of the @code{**} binary operator.
6538 Colon must be surrounded by spaces.
6541 Colon-equal (assignment, initialization) must be surrounded by spaces.
6544 Comma must be the first non-blank character on the line, or be
6545 immediately preceded by a non-blank character, and must be followed
6549 If the token preceding a left parenthesis ends with a letter or digit, then
6550 a space must separate the two tokens.
6553 if the token following a right parenthesis starts with a letter or digit, then
6554 a space must separate the two tokens.
6557 A right parenthesis must either be the first non-blank character on
6558 a line, or it must be preceded by a non-blank character.
6561 A semicolon must not be preceded by a space, and must not be followed by
6562 a non-blank character.
6565 A unary plus or minus may not be followed by a space.
6568 A vertical bar must be surrounded by spaces.
6571 @item ^u^UNNECESSARY_BLANK_LINES^
6572 @emph{Check unnecessary blank lines.}
6573 Unnecessary blank lines are not allowed. A blank line is considered
6574 unnecessary if it appears at the end of the file, or if more than
6575 one blank line occurs in sequence.
6577 @item ^x^XTRA_PARENS^
6578 @emph{Check extra parentheses.}
6579 Unnecessary extra level of parentheses (C-style) are not allowed
6580 around conditions in @code{if} statements, @code{while} statements and
6581 @code{exit} statements.
6583 @item ^y^ALL_BUILTIN^
6584 @emph{Set all standard style check options}
6585 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6586 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6587 @option{-gnatyS}, @option{-gnatyLnnn},
6588 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6592 @emph{Remove style check options}
6593 This causes any subsequent options in the string to act as canceling the
6594 corresponding style check option. To cancel maximum nesting level control,
6595 use @option{L} parameter witout any integer value after that, because any
6596 digit following @option{-} in the parameter string of the @option{-gnaty}
6597 option will be threated as canceling indentation check. The same is true
6598 for @option{M} parameter. @option{y} and @option{N} parameters are not
6599 allowed after @option{-}.
6602 This causes any subsequent options in the string to enable the corresponding
6603 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6609 @emph{Removing style check options}
6610 If the name of a style check is preceded by @option{NO} then the corresponding
6611 style check is turned off. For example @option{NOCOMMENTS} turns off style
6612 checking for comments.
6617 In the above rules, appearing in column one is always permitted, that is,
6618 counts as meeting either a requirement for a required preceding space,
6619 or as meeting a requirement for no preceding space.
6621 Appearing at the end of a line is also always permitted, that is, counts
6622 as meeting either a requirement for a following space, or as meeting
6623 a requirement for no following space.
6626 If any of these style rules is violated, a message is generated giving
6627 details on the violation. The initial characters of such messages are
6628 always ``@code{(style)}''. Note that these messages are treated as warning
6629 messages, so they normally do not prevent the generation of an object
6630 file. The @option{-gnatwe} switch can be used to treat warning messages,
6631 including style messages, as fatal errors.
6635 @option{-gnaty} on its own (that is not
6636 followed by any letters or digits), then the effect is equivalent
6637 to the use of @option{-gnatyy}, as described above, that is all
6638 built-in standard style check options are enabled.
6642 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6643 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6644 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6654 clears any previously set style checks.
6656 @node Run-Time Checks
6657 @subsection Run-Time Checks
6658 @cindex Division by zero
6659 @cindex Access before elaboration
6660 @cindex Checks, division by zero
6661 @cindex Checks, access before elaboration
6662 @cindex Checks, stack overflow checking
6665 By default, the following checks are suppressed: integer overflow
6666 checks, stack overflow checks, and checks for access before
6667 elaboration on subprogram calls. All other checks, including range
6668 checks and array bounds checks, are turned on by default. The
6669 following @command{gcc} switches refine this default behavior.
6674 @cindex @option{-gnatp} (@command{gcc})
6675 @cindex Suppressing checks
6676 @cindex Checks, suppressing
6678 This switch causes the unit to be compiled
6679 as though @code{pragma Suppress (All_checks)}
6680 had been present in the source. Validity checks are also eliminated (in
6681 other words @option{-gnatp} also implies @option{-gnatVn}.
6682 Use this switch to improve the performance
6683 of the code at the expense of safety in the presence of invalid data or
6686 Note that when checks are suppressed, the compiler is allowed, but not
6687 required, to omit the checking code. If the run-time cost of the
6688 checking code is zero or near-zero, the compiler will generate it even
6689 if checks are suppressed. In particular, if the compiler can prove
6690 that a certain check will necessarily fail, it will generate code to
6691 do an unconditional ``raise'', even if checks are suppressed. The
6692 compiler warns in this case. Another case in which checks may not be
6693 eliminated is when they are embedded in certain run time routines such
6694 as math library routines.
6696 Of course, run-time checks are omitted whenever the compiler can prove
6697 that they will not fail, whether or not checks are suppressed.
6699 Note that if you suppress a check that would have failed, program
6700 execution is erroneous, which means the behavior is totally
6701 unpredictable. The program might crash, or print wrong answers, or
6702 do anything else. It might even do exactly what you wanted it to do
6703 (and then it might start failing mysteriously next week or next
6704 year). The compiler will generate code based on the assumption that
6705 the condition being checked is true, which can result in disaster if
6706 that assumption is wrong.
6708 The @option{-gnatp} switch has no effect if a subsequent
6709 @option{-gnat-p} switch appears.
6712 @cindex @option{-gnat-p} (@command{gcc})
6713 @cindex Suppressing checks
6714 @cindex Checks, suppressing
6716 This switch cancels the effect of a previous @option{gnatp} switch.
6719 @cindex @option{-gnato} (@command{gcc})
6720 @cindex Overflow checks
6721 @cindex Check, overflow
6722 Enables overflow checking for integer operations.
6723 This causes GNAT to generate slower and larger executable
6724 programs by adding code to check for overflow (resulting in raising
6725 @code{Constraint_Error} as required by standard Ada
6726 semantics). These overflow checks correspond to situations in which
6727 the true value of the result of an operation may be outside the base
6728 range of the result type. The following example shows the distinction:
6730 @smallexample @c ada
6731 X1 : Integer := "Integer'Last";
6732 X2 : Integer range 1 .. 5 := "5";
6733 X3 : Integer := "Integer'Last";
6734 X4 : Integer range 1 .. 5 := "5";
6735 F : Float := "2.0E+20";
6744 Note that if explicit values are assigned at compile time, the
6745 compiler may be able to detect overflow at compile time, in which case
6746 no actual run-time checking code is required, and Constraint_Error
6747 will be raised unconditionally, with or without
6748 @option{-gnato}. That's why the assigned values in the above fragment
6749 are in quotes, the meaning is "assign a value not known to the
6750 compiler that happens to be equal to ...". The remaining discussion
6751 assumes that the compiler cannot detect the values at compile time.
6753 Here the first addition results in a value that is outside the base range
6754 of Integer, and hence requires an overflow check for detection of the
6755 constraint error. Thus the first assignment to @code{X1} raises a
6756 @code{Constraint_Error} exception only if @option{-gnato} is set.
6758 The second increment operation results in a violation of the explicit
6759 range constraint; such range checks are performed by default, and are
6760 unaffected by @option{-gnato}.
6762 The two conversions of @code{F} both result in values that are outside
6763 the base range of type @code{Integer} and thus will raise
6764 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6765 The fact that the result of the second conversion is assigned to
6766 variable @code{X4} with a restricted range is irrelevant, since the problem
6767 is in the conversion, not the assignment.
6769 Basically the rule is that in the default mode (@option{-gnato} not
6770 used), the generated code assures that all integer variables stay
6771 within their declared ranges, or within the base range if there is
6772 no declared range. This prevents any serious problems like indexes
6773 out of range for array operations.
6775 What is not checked in default mode is an overflow that results in
6776 an in-range, but incorrect value. In the above example, the assignments
6777 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6778 range of the target variable, but the result is wrong in the sense that
6779 it is too large to be represented correctly. Typically the assignment
6780 to @code{X1} will result in wrap around to the largest negative number.
6781 The conversions of @code{F} will result in some @code{Integer} value
6782 and if that integer value is out of the @code{X4} range then the
6783 subsequent assignment would generate an exception.
6785 @findex Machine_Overflows
6786 Note that the @option{-gnato} switch does not affect the code generated
6787 for any floating-point operations; it applies only to integer
6789 For floating-point, GNAT has the @code{Machine_Overflows}
6790 attribute set to @code{False} and the normal mode of operation is to
6791 generate IEEE NaN and infinite values on overflow or invalid operations
6792 (such as dividing 0.0 by 0.0).
6794 The reason that we distinguish overflow checking from other kinds of
6795 range constraint checking is that a failure of an overflow check, unlike
6796 for example the failure of a range check, can result in an incorrect
6797 value, but cannot cause random memory destruction (like an out of range
6798 subscript), or a wild jump (from an out of range case value). Overflow
6799 checking is also quite expensive in time and space, since in general it
6800 requires the use of double length arithmetic.
6802 Note again that @option{-gnato} is off by default, so overflow checking is
6803 not performed in default mode. This means that out of the box, with the
6804 default settings, GNAT does not do all the checks expected from the
6805 language description in the Ada Reference Manual. If you want all constraint
6806 checks to be performed, as described in this Manual, then you must
6807 explicitly use the -gnato switch either on the @command{gnatmake} or
6808 @command{gcc} command.
6811 @cindex @option{-gnatE} (@command{gcc})
6812 @cindex Elaboration checks
6813 @cindex Check, elaboration
6814 Enables dynamic checks for access-before-elaboration
6815 on subprogram calls and generic instantiations.
6816 Note that @option{-gnatE} is not necessary for safety, because in the
6817 default mode, GNAT ensures statically that the checks would not fail.
6818 For full details of the effect and use of this switch,
6819 @xref{Compiling Using gcc}.
6822 @cindex @option{-fstack-check} (@command{gcc})
6823 @cindex Stack Overflow Checking
6824 @cindex Checks, stack overflow checking
6825 Activates stack overflow checking. For full details of the effect and use of
6826 this switch see @ref{Stack Overflow Checking}.
6831 The setting of these switches only controls the default setting of the
6832 checks. You may modify them using either @code{Suppress} (to remove
6833 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6836 @node Using gcc for Syntax Checking
6837 @subsection Using @command{gcc} for Syntax Checking
6840 @cindex @option{-gnats} (@command{gcc})
6844 The @code{s} stands for ``syntax''.
6847 Run GNAT in syntax checking only mode. For
6848 example, the command
6851 $ gcc -c -gnats x.adb
6855 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6856 series of files in a single command
6858 , and can use wild cards to specify such a group of files.
6859 Note that you must specify the @option{-c} (compile
6860 only) flag in addition to the @option{-gnats} flag.
6863 You may use other switches in conjunction with @option{-gnats}. In
6864 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6865 format of any generated error messages.
6867 When the source file is empty or contains only empty lines and/or comments,
6868 the output is a warning:
6871 $ gcc -c -gnats -x ada toto.txt
6872 toto.txt:1:01: warning: empty file, contains no compilation units
6876 Otherwise, the output is simply the error messages, if any. No object file or
6877 ALI file is generated by a syntax-only compilation. Also, no units other
6878 than the one specified are accessed. For example, if a unit @code{X}
6879 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6880 check only mode does not access the source file containing unit
6883 @cindex Multiple units, syntax checking
6884 Normally, GNAT allows only a single unit in a source file. However, this
6885 restriction does not apply in syntax-check-only mode, and it is possible
6886 to check a file containing multiple compilation units concatenated
6887 together. This is primarily used by the @code{gnatchop} utility
6888 (@pxref{Renaming Files Using gnatchop}).
6891 @node Using gcc for Semantic Checking
6892 @subsection Using @command{gcc} for Semantic Checking
6895 @cindex @option{-gnatc} (@command{gcc})
6899 The @code{c} stands for ``check''.
6901 Causes the compiler to operate in semantic check mode,
6902 with full checking for all illegalities specified in the
6903 Ada Reference Manual, but without generation of any object code
6904 (no object file is generated).
6906 Because dependent files must be accessed, you must follow the GNAT
6907 semantic restrictions on file structuring to operate in this mode:
6911 The needed source files must be accessible
6912 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6915 Each file must contain only one compilation unit.
6918 The file name and unit name must match (@pxref{File Naming Rules}).
6921 The output consists of error messages as appropriate. No object file is
6922 generated. An @file{ALI} file is generated for use in the context of
6923 cross-reference tools, but this file is marked as not being suitable
6924 for binding (since no object file is generated).
6925 The checking corresponds exactly to the notion of
6926 legality in the Ada Reference Manual.
6928 Any unit can be compiled in semantics-checking-only mode, including
6929 units that would not normally be compiled (subunits,
6930 and specifications where a separate body is present).
6933 @node Compiling Different Versions of Ada
6934 @subsection Compiling Different Versions of Ada
6937 The switches described in this section allow you to explicitly specify
6938 the version of the Ada language that your programs are written in.
6939 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6940 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6941 indicate Ada 83 compatibility mode.
6944 @cindex Compatibility with Ada 83
6946 @item -gnat83 (Ada 83 Compatibility Mode)
6947 @cindex @option{-gnat83} (@command{gcc})
6948 @cindex ACVC, Ada 83 tests
6952 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6953 specifies that the program is to be compiled in Ada 83 mode. With
6954 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6955 semantics where this can be done easily.
6956 It is not possible to guarantee this switch does a perfect
6957 job; some subtle tests, such as are
6958 found in earlier ACVC tests (and that have been removed from the ACATS suite
6959 for Ada 95), might not compile correctly.
6960 Nevertheless, this switch may be useful in some circumstances, for example
6961 where, due to contractual reasons, existing code needs to be maintained
6962 using only Ada 83 features.
6964 With few exceptions (most notably the need to use @code{<>} on
6965 @cindex Generic formal parameters
6966 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6967 reserved words, and the use of packages
6968 with optional bodies), it is not necessary to specify the
6969 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6970 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6971 a correct Ada 83 program is usually also a correct program
6972 in these later versions of the language standard.
6973 For further information, please refer to @ref{Compatibility and Porting Guide}.
6975 @item -gnat95 (Ada 95 mode)
6976 @cindex @option{-gnat95} (@command{gcc})
6980 This switch directs the compiler to implement the Ada 95 version of the
6982 Since Ada 95 is almost completely upwards
6983 compatible with Ada 83, Ada 83 programs may generally be compiled using
6984 this switch (see the description of the @option{-gnat83} switch for further
6985 information about Ada 83 mode).
6986 If an Ada 2005 program is compiled in Ada 95 mode,
6987 uses of the new Ada 2005 features will cause error
6988 messages or warnings.
6990 This switch also can be used to cancel the effect of a previous
6991 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6992 switch earlier in the command line.
6994 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6995 @cindex @option{-gnat05} (@command{gcc})
6996 @cindex @option{-gnat2005} (@command{gcc})
6997 @cindex Ada 2005 mode
7000 This switch directs the compiler to implement the Ada 2005 version of the
7001 language, as documented in the official Ada standards document.
7002 Since Ada 2005 is almost completely upwards
7003 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7004 may generally be compiled using this switch (see the description of the
7005 @option{-gnat83} and @option{-gnat95} switches for further
7009 Note that even though Ada 2005 is the current official version of the
7010 language, GNAT still compiles in Ada 95 mode by default, so if you are
7011 using Ada 2005 features in your program, you must use this switch (or
7012 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7015 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7016 @cindex @option{-gnat12} (@command{gcc})
7017 @cindex @option{-gnat2012} (@command{gcc})
7018 @cindex Ada 2012 mode
7021 This switch directs the compiler to implement the Ada 2012 version of the
7023 Since Ada 2012 is almost completely upwards
7024 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7025 Ada 83 and Ada 95 programs
7026 may generally be compiled using this switch (see the description of the
7027 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7028 for further information).
7030 For information about the approved ``Ada Issues'' that have been incorporated
7031 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7032 Included with GNAT releases is a file @file{features-ada12} that describes
7033 the set of implemented Ada 2012 features.
7035 @item -gnatX (Enable GNAT Extensions)
7036 @cindex @option{-gnatX} (@command{gcc})
7037 @cindex Ada language extensions
7038 @cindex GNAT extensions
7041 This switch directs the compiler to implement the latest version of the
7042 language (currently Ada 2012) and also to enable certain GNAT implementation
7043 extensions that are not part of any Ada standard. For a full list of these
7044 extensions, see the GNAT reference manual.
7048 @node Character Set Control
7049 @subsection Character Set Control
7051 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7052 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7055 Normally GNAT recognizes the Latin-1 character set in source program
7056 identifiers, as described in the Ada Reference Manual.
7058 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7059 single character ^^or word^ indicating the character set, as follows:
7063 ISO 8859-1 (Latin-1) identifiers
7066 ISO 8859-2 (Latin-2) letters allowed in identifiers
7069 ISO 8859-3 (Latin-3) letters allowed in identifiers
7072 ISO 8859-4 (Latin-4) letters allowed in identifiers
7075 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7078 ISO 8859-15 (Latin-9) letters allowed in identifiers
7081 IBM PC letters (code page 437) allowed in identifiers
7084 IBM PC letters (code page 850) allowed in identifiers
7086 @item ^f^FULL_UPPER^
7087 Full upper-half codes allowed in identifiers
7090 No upper-half codes allowed in identifiers
7093 Wide-character codes (that is, codes greater than 255)
7094 allowed in identifiers
7097 @xref{Foreign Language Representation}, for full details on the
7098 implementation of these character sets.
7100 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7101 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7102 Specify the method of encoding for wide characters.
7103 @var{e} is one of the following:
7108 Hex encoding (brackets coding also recognized)
7111 Upper half encoding (brackets encoding also recognized)
7114 Shift/JIS encoding (brackets encoding also recognized)
7117 EUC encoding (brackets encoding also recognized)
7120 UTF-8 encoding (brackets encoding also recognized)
7123 Brackets encoding only (default value)
7125 For full details on these encoding
7126 methods see @ref{Wide Character Encodings}.
7127 Note that brackets coding is always accepted, even if one of the other
7128 options is specified, so for example @option{-gnatW8} specifies that both
7129 brackets and UTF-8 encodings will be recognized. The units that are
7130 with'ed directly or indirectly will be scanned using the specified
7131 representation scheme, and so if one of the non-brackets scheme is
7132 used, it must be used consistently throughout the program. However,
7133 since brackets encoding is always recognized, it may be conveniently
7134 used in standard libraries, allowing these libraries to be used with
7135 any of the available coding schemes.
7138 If no @option{-gnatW?} parameter is present, then the default
7139 representation is normally Brackets encoding only. However, if the
7140 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7141 byte order mark or BOM for UTF-8), then these three characters are
7142 skipped and the default representation for the file is set to UTF-8.
7144 Note that the wide character representation that is specified (explicitly
7145 or by default) for the main program also acts as the default encoding used
7146 for Wide_Text_IO files if not specifically overridden by a WCEM form
7150 @node File Naming Control
7151 @subsection File Naming Control
7154 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7155 @cindex @option{-gnatk} (@command{gcc})
7156 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7157 1-999, indicates the maximum allowable length of a file name (not
7158 including the @file{.ads} or @file{.adb} extension). The default is not
7159 to enable file name krunching.
7161 For the source file naming rules, @xref{File Naming Rules}.
7164 @node Subprogram Inlining Control
7165 @subsection Subprogram Inlining Control
7170 @cindex @option{-gnatn} (@command{gcc})
7172 The @code{n} here is intended to suggest the first syllable of the
7175 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7176 inlining to actually occur, optimization must be enabled. To enable
7177 inlining of subprograms specified by pragma @code{Inline},
7178 you must also specify this switch.
7179 In the absence of this switch, GNAT does not attempt
7180 inlining and does not need to access the bodies of
7181 subprograms for which @code{pragma Inline} is specified if they are not
7182 in the current unit.
7184 If you specify this switch the compiler will access these bodies,
7185 creating an extra source dependency for the resulting object file, and
7186 where possible, the call will be inlined.
7187 For further details on when inlining is possible
7188 see @ref{Inlining of Subprograms}.
7191 @cindex @option{-gnatN} (@command{gcc})
7192 This switch activates front-end inlining which also
7193 generates additional dependencies.
7195 When using a gcc-based back end (in practice this means using any version
7196 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7197 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7198 Historically front end inlining was more extensive than the gcc back end
7199 inlining, but that is no longer the case.
7202 @node Auxiliary Output Control
7203 @subsection Auxiliary Output Control
7207 @cindex @option{-gnatt} (@command{gcc})
7208 @cindex Writing internal trees
7209 @cindex Internal trees, writing to file
7210 Causes GNAT to write the internal tree for a unit to a file (with the
7211 extension @file{.adt}.
7212 This not normally required, but is used by separate analysis tools.
7214 these tools do the necessary compilations automatically, so you should
7215 not have to specify this switch in normal operation.
7216 Note that the combination of switches @option{-gnatct}
7217 generates a tree in the form required by ASIS applications.
7220 @cindex @option{-gnatu} (@command{gcc})
7221 Print a list of units required by this compilation on @file{stdout}.
7222 The listing includes all units on which the unit being compiled depends
7223 either directly or indirectly.
7226 @item -pass-exit-codes
7227 @cindex @option{-pass-exit-codes} (@command{gcc})
7228 If this switch is not used, the exit code returned by @command{gcc} when
7229 compiling multiple files indicates whether all source files have
7230 been successfully used to generate object files or not.
7232 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7233 exit status and allows an integrated development environment to better
7234 react to a compilation failure. Those exit status are:
7238 There was an error in at least one source file.
7240 At least one source file did not generate an object file.
7242 The compiler died unexpectedly (internal error for example).
7244 An object file has been generated for every source file.
7249 @node Debugging Control
7250 @subsection Debugging Control
7254 @cindex Debugging options
7257 @cindex @option{-gnatd} (@command{gcc})
7258 Activate internal debugging switches. @var{x} is a letter or digit, or
7259 string of letters or digits, which specifies the type of debugging
7260 outputs desired. Normally these are used only for internal development
7261 or system debugging purposes. You can find full documentation for these
7262 switches in the body of the @code{Debug} unit in the compiler source
7263 file @file{debug.adb}.
7267 @cindex @option{-gnatG} (@command{gcc})
7268 This switch causes the compiler to generate auxiliary output containing
7269 a pseudo-source listing of the generated expanded code. Like most Ada
7270 compilers, GNAT works by first transforming the high level Ada code into
7271 lower level constructs. For example, tasking operations are transformed
7272 into calls to the tasking run-time routines. A unique capability of GNAT
7273 is to list this expanded code in a form very close to normal Ada source.
7274 This is very useful in understanding the implications of various Ada
7275 usage on the efficiency of the generated code. There are many cases in
7276 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7277 generate a lot of run-time code. By using @option{-gnatG} you can identify
7278 these cases, and consider whether it may be desirable to modify the coding
7279 approach to improve efficiency.
7281 The optional parameter @code{nn} if present after -gnatG specifies an
7282 alternative maximum line length that overrides the normal default of 72.
7283 This value is in the range 40-999999, values less than 40 being silently
7284 reset to 40. The equal sign is optional.
7286 The format of the output is very similar to standard Ada source, and is
7287 easily understood by an Ada programmer. The following special syntactic
7288 additions correspond to low level features used in the generated code that
7289 do not have any exact analogies in pure Ada source form. The following
7290 is a partial list of these special constructions. See the spec
7291 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7293 If the switch @option{-gnatL} is used in conjunction with
7294 @cindex @option{-gnatL} (@command{gcc})
7295 @option{-gnatG}, then the original source lines are interspersed
7296 in the expanded source (as comment lines with the original line number).
7299 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7300 Shows the storage pool being used for an allocator.
7302 @item at end @var{procedure-name};
7303 Shows the finalization (cleanup) procedure for a scope.
7305 @item (if @var{expr} then @var{expr} else @var{expr})
7306 Conditional expression equivalent to the @code{x?y:z} construction in C.
7308 @item @var{target}^^^(@var{source})
7309 A conversion with floating-point truncation instead of rounding.
7311 @item @var{target}?(@var{source})
7312 A conversion that bypasses normal Ada semantic checking. In particular
7313 enumeration types and fixed-point types are treated simply as integers.
7315 @item @var{target}?^^^(@var{source})
7316 Combines the above two cases.
7318 @item @var{x} #/ @var{y}
7319 @itemx @var{x} #mod @var{y}
7320 @itemx @var{x} #* @var{y}
7321 @itemx @var{x} #rem @var{y}
7322 A division or multiplication of fixed-point values which are treated as
7323 integers without any kind of scaling.
7325 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7326 Shows the storage pool associated with a @code{free} statement.
7328 @item [subtype or type declaration]
7329 Used to list an equivalent declaration for an internally generated
7330 type that is referenced elsewhere in the listing.
7332 @c @item freeze @var{type-name} @ovar{actions}
7333 @c Expanding @ovar macro inline (explanation in macro def comments)
7334 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7335 Shows the point at which @var{type-name} is frozen, with possible
7336 associated actions to be performed at the freeze point.
7338 @item reference @var{itype}
7339 Reference (and hence definition) to internal type @var{itype}.
7341 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7342 Intrinsic function call.
7344 @item @var{label-name} : label
7345 Declaration of label @var{labelname}.
7347 @item #$ @var{subprogram-name}
7348 An implicit call to a run-time support routine
7349 (to meet the requirement of H.3.1(9) in a
7352 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7353 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7354 @var{expr}, but handled more efficiently).
7356 @item [constraint_error]
7357 Raise the @code{Constraint_Error} exception.
7359 @item @var{expression}'reference
7360 A pointer to the result of evaluating @var{expression}.
7362 @item @var{target-type}!(@var{source-expression})
7363 An unchecked conversion of @var{source-expression} to @var{target-type}.
7365 @item [@var{numerator}/@var{denominator}]
7366 Used to represent internal real literals (that) have no exact
7367 representation in base 2-16 (for example, the result of compile time
7368 evaluation of the expression 1.0/27.0).
7372 @cindex @option{-gnatD} (@command{gcc})
7373 When used in conjunction with @option{-gnatG}, this switch causes
7374 the expanded source, as described above for
7375 @option{-gnatG} to be written to files with names
7376 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7377 instead of to the standard output file. For
7378 example, if the source file name is @file{hello.adb}, then a file
7379 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7380 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7381 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7382 you to do source level debugging using the generated code which is
7383 sometimes useful for complex code, for example to find out exactly
7384 which part of a complex construction raised an exception. This switch
7385 also suppress generation of cross-reference information (see
7386 @option{-gnatx}) since otherwise the cross-reference information
7387 would refer to the @file{^.dg^.DG^} file, which would cause
7388 confusion since this is not the original source file.
7390 Note that @option{-gnatD} actually implies @option{-gnatG}
7391 automatically, so it is not necessary to give both options.
7392 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7394 If the switch @option{-gnatL} is used in conjunction with
7395 @cindex @option{-gnatL} (@command{gcc})
7396 @option{-gnatDG}, then the original source lines are interspersed
7397 in the expanded source (as comment lines with the original line number).
7399 The optional parameter @code{nn} if present after -gnatD specifies an
7400 alternative maximum line length that overrides the normal default of 72.
7401 This value is in the range 40-999999, values less than 40 being silently
7402 reset to 40. The equal sign is optional.
7405 @cindex @option{-gnatr} (@command{gcc})
7406 @cindex pragma Restrictions
7407 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7408 so that violation of restrictions causes warnings rather than illegalities.
7409 This is useful during the development process when new restrictions are added
7410 or investigated. The switch also causes pragma Profile to be treated as
7411 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7412 restriction warnings rather than restrictions.
7415 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7416 @cindex @option{-gnatR} (@command{gcc})
7417 This switch controls output from the compiler of a listing showing
7418 representation information for declared types and objects. For
7419 @option{-gnatR0}, no information is output (equivalent to omitting
7420 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7421 so @option{-gnatR} with no parameter has the same effect), size and alignment
7422 information is listed for declared array and record types. For
7423 @option{-gnatR2}, size and alignment information is listed for all
7424 declared types and objects. Finally @option{-gnatR3} includes symbolic
7425 expressions for values that are computed at run time for
7426 variant records. These symbolic expressions have a mostly obvious
7427 format with #n being used to represent the value of the n'th
7428 discriminant. See source files @file{repinfo.ads/adb} in the
7429 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7430 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7431 the output is to a file with the name @file{^file.rep^file_REP^} where
7432 file is the name of the corresponding source file.
7435 @item /REPRESENTATION_INFO
7436 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7437 This qualifier controls output from the compiler of a listing showing
7438 representation information for declared types and objects. For
7439 @option{/REPRESENTATION_INFO=NONE}, no information is output
7440 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7441 @option{/REPRESENTATION_INFO} without option is equivalent to
7442 @option{/REPRESENTATION_INFO=ARRAYS}.
7443 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7444 information is listed for declared array and record types. For
7445 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7446 is listed for all expression information for values that are computed
7447 at run time for variant records. These symbolic expressions have a mostly
7448 obvious format with #n being used to represent the value of the n'th
7449 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7450 @code{GNAT} sources for full details on the format of
7451 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7452 If _FILE is added at the end of an option
7453 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7454 then the output is to a file with the name @file{file_REP} where
7455 file is the name of the corresponding source file.
7457 Note that it is possible for record components to have zero size. In
7458 this case, the component clause uses an obvious extension of permitted
7459 Ada syntax, for example @code{at 0 range 0 .. -1}.
7461 Representation information requires that code be generated (since it is the
7462 code generator that lays out complex data structures). If an attempt is made
7463 to output representation information when no code is generated, for example
7464 when a subunit is compiled on its own, then no information can be generated
7465 and the compiler outputs a message to this effect.
7468 @cindex @option{-gnatS} (@command{gcc})
7469 The use of the switch @option{-gnatS} for an
7470 Ada compilation will cause the compiler to output a
7471 representation of package Standard in a form very
7472 close to standard Ada. It is not quite possible to
7473 do this entirely in standard Ada (since new
7474 numeric base types cannot be created in standard
7475 Ada), but the output is easily
7476 readable to any Ada programmer, and is useful to
7477 determine the characteristics of target dependent
7478 types in package Standard.
7481 @cindex @option{-gnatx} (@command{gcc})
7482 Normally the compiler generates full cross-referencing information in
7483 the @file{ALI} file. This information is used by a number of tools,
7484 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7485 suppresses this information. This saves some space and may slightly
7486 speed up compilation, but means that these tools cannot be used.
7489 @node Exception Handling Control
7490 @subsection Exception Handling Control
7493 GNAT uses two methods for handling exceptions at run-time. The
7494 @code{setjmp/longjmp} method saves the context when entering
7495 a frame with an exception handler. Then when an exception is
7496 raised, the context can be restored immediately, without the
7497 need for tracing stack frames. This method provides very fast
7498 exception propagation, but introduces significant overhead for
7499 the use of exception handlers, even if no exception is raised.
7501 The other approach is called ``zero cost'' exception handling.
7502 With this method, the compiler builds static tables to describe
7503 the exception ranges. No dynamic code is required when entering
7504 a frame containing an exception handler. When an exception is
7505 raised, the tables are used to control a back trace of the
7506 subprogram invocation stack to locate the required exception
7507 handler. This method has considerably poorer performance for
7508 the propagation of exceptions, but there is no overhead for
7509 exception handlers if no exception is raised. Note that in this
7510 mode and in the context of mixed Ada and C/C++ programming,
7511 to propagate an exception through a C/C++ code, the C/C++ code
7512 must be compiled with the @option{-funwind-tables} GCC's
7515 The following switches may be used to control which of the
7516 two exception handling methods is used.
7522 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7523 This switch causes the setjmp/longjmp run-time (when available) to be used
7524 for exception handling. If the default
7525 mechanism for the target is zero cost exceptions, then
7526 this switch can be used to modify this default, and must be
7527 used for all units in the partition.
7528 This option is rarely used. One case in which it may be
7529 advantageous is if you have an application where exception
7530 raising is common and the overall performance of the
7531 application is improved by favoring exception propagation.
7534 @cindex @option{--RTS=zcx} (@command{gnatmake})
7535 @cindex Zero Cost Exceptions
7536 This switch causes the zero cost approach to be used
7537 for exception handling. If this is the default mechanism for the
7538 target (see below), then this switch is unneeded. If the default
7539 mechanism for the target is setjmp/longjmp exceptions, then
7540 this switch can be used to modify this default, and must be
7541 used for all units in the partition.
7542 This option can only be used if the zero cost approach
7543 is available for the target in use, otherwise it will generate an error.
7547 The same option @option{--RTS} must be used both for @command{gcc}
7548 and @command{gnatbind}. Passing this option to @command{gnatmake}
7549 (@pxref{Switches for gnatmake}) will ensure the required consistency
7550 through the compilation and binding steps.
7552 @node Units to Sources Mapping Files
7553 @subsection Units to Sources Mapping Files
7557 @item -gnatem=@var{path}
7558 @cindex @option{-gnatem} (@command{gcc})
7559 A mapping file is a way to communicate to the compiler two mappings:
7560 from unit names to file names (without any directory information) and from
7561 file names to path names (with full directory information). These mappings
7562 are used by the compiler to short-circuit the path search.
7564 The use of mapping files is not required for correct operation of the
7565 compiler, but mapping files can improve efficiency, particularly when
7566 sources are read over a slow network connection. In normal operation,
7567 you need not be concerned with the format or use of mapping files,
7568 and the @option{-gnatem} switch is not a switch that you would use
7569 explicitly. It is intended primarily for use by automatic tools such as
7570 @command{gnatmake} running under the project file facility. The
7571 description here of the format of mapping files is provided
7572 for completeness and for possible use by other tools.
7574 A mapping file is a sequence of sets of three lines. In each set, the
7575 first line is the unit name, in lower case, with @code{%s} appended
7576 for specs and @code{%b} appended for bodies; the second line is the
7577 file name; and the third line is the path name.
7583 /gnat/project1/sources/main.2.ada
7586 When the switch @option{-gnatem} is specified, the compiler will
7587 create in memory the two mappings from the specified file. If there is
7588 any problem (nonexistent file, truncated file or duplicate entries),
7589 no mapping will be created.
7591 Several @option{-gnatem} switches may be specified; however, only the
7592 last one on the command line will be taken into account.
7594 When using a project file, @command{gnatmake} creates a temporary
7595 mapping file and communicates it to the compiler using this switch.
7599 @node Integrated Preprocessing
7600 @subsection Integrated Preprocessing
7603 GNAT sources may be preprocessed immediately before compilation.
7604 In this case, the actual
7605 text of the source is not the text of the source file, but is derived from it
7606 through a process called preprocessing. Integrated preprocessing is specified
7607 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7608 indicates, through a text file, the preprocessing data to be used.
7609 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7612 Note that when integrated preprocessing is used, the output from the
7613 preprocessor is not written to any external file. Instead it is passed
7614 internally to the compiler. If you need to preserve the result of
7615 preprocessing in a file, then you should use @command{gnatprep}
7616 to perform the desired preprocessing in stand-alone mode.
7619 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7620 used when Integrated Preprocessing is used. The reason is that preprocessing
7621 with another Preprocessing Data file without changing the sources will
7622 not trigger recompilation without this switch.
7625 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7626 always trigger recompilation for sources that are preprocessed,
7627 because @command{gnatmake} cannot compute the checksum of the source after
7631 The actual preprocessing function is described in details in section
7632 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7633 preprocessing is triggered and parameterized.
7637 @item -gnatep=@var{file}
7638 @cindex @option{-gnatep} (@command{gcc})
7639 This switch indicates to the compiler the file name (without directory
7640 information) of the preprocessor data file to use. The preprocessor data file
7641 should be found in the source directories. Note that when the compiler is
7642 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7643 file, if the object directory is not also a source directory, the builder needs
7644 to be called with @option{-x}.
7647 A preprocessing data file is a text file with significant lines indicating
7648 how should be preprocessed either a specific source or all sources not
7649 mentioned in other lines. A significant line is a nonempty, non-comment line.
7650 Comments are similar to Ada comments.
7653 Each significant line starts with either a literal string or the character '*'.
7654 A literal string is the file name (without directory information) of the source
7655 to preprocess. A character '*' indicates the preprocessing for all the sources
7656 that are not specified explicitly on other lines (order of the lines is not
7657 significant). It is an error to have two lines with the same file name or two
7658 lines starting with the character '*'.
7661 After the file name or the character '*', another optional literal string
7662 indicating the file name of the definition file to be used for preprocessing
7663 (@pxref{Form of Definitions File}). The definition files are found by the
7664 compiler in one of the source directories. In some cases, when compiling
7665 a source in a directory other than the current directory, if the definition
7666 file is in the current directory, it may be necessary to add the current
7667 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7668 the compiler would not find the definition file.
7671 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7672 be found. Those ^switches^switches^ are:
7677 Causes both preprocessor lines and the lines deleted by
7678 preprocessing to be replaced by blank lines, preserving the line number.
7679 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7680 it cancels the effect of @option{-c}.
7683 Causes both preprocessor lines and the lines deleted
7684 by preprocessing to be retained as comments marked
7685 with the special string ``@code{--! }''.
7687 @item -Dsymbol=value
7688 Define or redefine a symbol, associated with value. A symbol is an Ada
7689 identifier, or an Ada reserved word, with the exception of @code{if},
7690 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7691 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7692 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7693 same name defined in a definition file.
7696 Causes a sorted list of symbol names and values to be
7697 listed on the standard output file.
7700 Causes undefined symbols to be treated as having the value @code{FALSE}
7702 of a preprocessor test. In the absence of this option, an undefined symbol in
7703 a @code{#if} or @code{#elsif} test will be treated as an error.
7708 Examples of valid lines in a preprocessor data file:
7711 "toto.adb" "prep.def" -u
7712 -- preprocess "toto.adb", using definition file "prep.def",
7713 -- undefined symbol are False.
7716 -- preprocess all other sources without a definition file;
7717 -- suppressed lined are commented; symbol VERSION has the value V101.
7719 "titi.adb" "prep2.def" -s
7720 -- preprocess "titi.adb", using definition file "prep2.def";
7721 -- list all symbols with their values.
7724 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7725 @cindex @option{-gnateD} (@command{gcc})
7726 Define or redefine a preprocessing symbol, associated with value. If no value
7727 is given on the command line, then the value of the symbol is @code{True}.
7728 A symbol is an identifier, following normal Ada (case-insensitive)
7729 rules for its syntax, and value is any sequence (including an empty sequence)
7730 of characters from the set (letters, digits, period, underline).
7731 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7732 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7735 A symbol declared with this ^switch^switch^ on the command line replaces a
7736 symbol with the same name either in a definition file or specified with a
7737 ^switch^switch^ -D in the preprocessor data file.
7740 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7743 When integrated preprocessing is performed and the preprocessor modifies
7744 the source text, write the result of this preprocessing into a file
7745 <source>^.prep^_prep^.
7749 @node Code Generation Control
7750 @subsection Code Generation Control
7754 The GCC technology provides a wide range of target dependent
7755 @option{-m} switches for controlling
7756 details of code generation with respect to different versions of
7757 architectures. This includes variations in instruction sets (e.g.@:
7758 different members of the power pc family), and different requirements
7759 for optimal arrangement of instructions (e.g.@: different members of
7760 the x86 family). The list of available @option{-m} switches may be
7761 found in the GCC documentation.
7763 Use of these @option{-m} switches may in some cases result in improved
7766 The @value{EDITION} technology is tested and qualified without any
7767 @option{-m} switches,
7768 so generally the most reliable approach is to avoid the use of these
7769 switches. However, we generally expect most of these switches to work
7770 successfully with @value{EDITION}, and many customers have reported successful
7771 use of these options.
7773 Our general advice is to avoid the use of @option{-m} switches unless
7774 special needs lead to requirements in this area. In particular,
7775 there is no point in using @option{-m} switches to improve performance
7776 unless you actually see a performance improvement.
7780 @subsection Return Codes
7781 @cindex Return Codes
7782 @cindex @option{/RETURN_CODES=VMS}
7785 On VMS, GNAT compiled programs return POSIX-style codes by default,
7786 e.g.@: @option{/RETURN_CODES=POSIX}.
7788 To enable VMS style return codes, use GNAT BIND and LINK with the option
7789 @option{/RETURN_CODES=VMS}. For example:
7792 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7793 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7797 Programs built with /RETURN_CODES=VMS are suitable to be called in
7798 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7799 are suitable for spawning with appropriate GNAT RTL routines.
7803 @node Search Paths and the Run-Time Library (RTL)
7804 @section Search Paths and the Run-Time Library (RTL)
7807 With the GNAT source-based library system, the compiler must be able to
7808 find source files for units that are needed by the unit being compiled.
7809 Search paths are used to guide this process.
7811 The compiler compiles one source file whose name must be given
7812 explicitly on the command line. In other words, no searching is done
7813 for this file. To find all other source files that are needed (the most
7814 common being the specs of units), the compiler examines the following
7815 directories, in the following order:
7819 The directory containing the source file of the main unit being compiled
7820 (the file name on the command line).
7823 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7824 @command{gcc} command line, in the order given.
7827 @findex ADA_PRJ_INCLUDE_FILE
7828 Each of the directories listed in the text file whose name is given
7829 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7832 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7833 driver when project files are used. It should not normally be set
7837 @findex ADA_INCLUDE_PATH
7838 Each of the directories listed in the value of the
7839 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7841 Construct this value
7842 exactly as the @env{PATH} environment variable: a list of directory
7843 names separated by colons (semicolons when working with the NT version).
7846 Normally, define this value as a logical name containing a comma separated
7847 list of directory names.
7849 This variable can also be defined by means of an environment string
7850 (an argument to the HP C exec* set of functions).
7854 DEFINE ANOTHER_PATH FOO:[BAG]
7855 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7858 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7859 first, followed by the standard Ada
7860 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7861 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7862 (Text_IO, Sequential_IO, etc)
7863 instead of the standard Ada packages. Thus, in order to get the standard Ada
7864 packages by default, ADA_INCLUDE_PATH must be redefined.
7868 The content of the @file{ada_source_path} file which is part of the GNAT
7869 installation tree and is used to store standard libraries such as the
7870 GNAT Run Time Library (RTL) source files.
7872 @ref{Installing a library}
7877 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7878 inhibits the use of the directory
7879 containing the source file named in the command line. You can still
7880 have this directory on your search path, but in this case it must be
7881 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7883 Specifying the switch @option{-nostdinc}
7884 inhibits the search of the default location for the GNAT Run Time
7885 Library (RTL) source files.
7887 The compiler outputs its object files and ALI files in the current
7890 Caution: The object file can be redirected with the @option{-o} switch;
7891 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7892 so the @file{ALI} file will not go to the right place. Therefore, you should
7893 avoid using the @option{-o} switch.
7897 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7898 children make up the GNAT RTL, together with the simple @code{System.IO}
7899 package used in the @code{"Hello World"} example. The sources for these units
7900 are needed by the compiler and are kept together in one directory. Not
7901 all of the bodies are needed, but all of the sources are kept together
7902 anyway. In a normal installation, you need not specify these directory
7903 names when compiling or binding. Either the environment variables or
7904 the built-in defaults cause these files to be found.
7906 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7907 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7908 consisting of child units of @code{GNAT}. This is a collection of generally
7909 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7910 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7912 Besides simplifying access to the RTL, a major use of search paths is
7913 in compiling sources from multiple directories. This can make
7914 development environments much more flexible.
7916 @node Order of Compilation Issues
7917 @section Order of Compilation Issues
7920 If, in our earlier example, there was a spec for the @code{hello}
7921 procedure, it would be contained in the file @file{hello.ads}; yet this
7922 file would not have to be explicitly compiled. This is the result of the
7923 model we chose to implement library management. Some of the consequences
7924 of this model are as follows:
7928 There is no point in compiling specs (except for package
7929 specs with no bodies) because these are compiled as needed by clients. If
7930 you attempt a useless compilation, you will receive an error message.
7931 It is also useless to compile subunits because they are compiled as needed
7935 There are no order of compilation requirements: performing a
7936 compilation never obsoletes anything. The only way you can obsolete
7937 something and require recompilations is to modify one of the
7938 source files on which it depends.
7941 There is no library as such, apart from the ALI files
7942 (@pxref{The Ada Library Information Files}, for information on the format
7943 of these files). For now we find it convenient to create separate ALI files,
7944 but eventually the information therein may be incorporated into the object
7948 When you compile a unit, the source files for the specs of all units
7949 that it @code{with}'s, all its subunits, and the bodies of any generics it
7950 instantiates must be available (reachable by the search-paths mechanism
7951 described above), or you will receive a fatal error message.
7958 The following are some typical Ada compilation command line examples:
7961 @item $ gcc -c xyz.adb
7962 Compile body in file @file{xyz.adb} with all default options.
7965 @item $ gcc -c -O2 -gnata xyz-def.adb
7968 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7971 Compile the child unit package in file @file{xyz-def.adb} with extensive
7972 optimizations, and pragma @code{Assert}/@code{Debug} statements
7975 @item $ gcc -c -gnatc abc-def.adb
7976 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7980 @node Binding Using gnatbind
7981 @chapter Binding Using @code{gnatbind}
7985 * Running gnatbind::
7986 * Switches for gnatbind::
7987 * Command-Line Access::
7988 * Search Paths for gnatbind::
7989 * Examples of gnatbind Usage::
7993 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7994 to bind compiled GNAT objects.
7996 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7997 driver (see @ref{The GNAT Driver and Project Files}).
7999 The @code{gnatbind} program performs four separate functions:
8003 Checks that a program is consistent, in accordance with the rules in
8004 Chapter 10 of the Ada Reference Manual. In particular, error
8005 messages are generated if a program uses inconsistent versions of a
8009 Checks that an acceptable order of elaboration exists for the program
8010 and issues an error message if it cannot find an order of elaboration
8011 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8014 Generates a main program incorporating the given elaboration order.
8015 This program is a small Ada package (body and spec) that
8016 must be subsequently compiled
8017 using the GNAT compiler. The necessary compilation step is usually
8018 performed automatically by @command{gnatlink}. The two most important
8019 functions of this program
8020 are to call the elaboration routines of units in an appropriate order
8021 and to call the main program.
8024 Determines the set of object files required by the given main program.
8025 This information is output in the forms of comments in the generated program,
8026 to be read by the @command{gnatlink} utility used to link the Ada application.
8029 @node Running gnatbind
8030 @section Running @code{gnatbind}
8033 The form of the @code{gnatbind} command is
8036 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8037 @c Expanding @ovar macro inline (explanation in macro def comments)
8038 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8042 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8043 unit body. @code{gnatbind} constructs an Ada
8044 package in two files whose names are
8045 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8046 For example, if given the
8047 parameter @file{hello.ali}, for a main program contained in file
8048 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8049 and @file{b~hello.adb}.
8051 When doing consistency checking, the binder takes into consideration
8052 any source files it can locate. For example, if the binder determines
8053 that the given main program requires the package @code{Pack}, whose
8055 file is @file{pack.ali} and whose corresponding source spec file is
8056 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8057 (using the same search path conventions as previously described for the
8058 @command{gcc} command). If it can locate this source file, it checks that
8060 or source checksums of the source and its references to in @file{ALI} files
8061 match. In other words, any @file{ALI} files that mentions this spec must have
8062 resulted from compiling this version of the source file (or in the case
8063 where the source checksums match, a version close enough that the
8064 difference does not matter).
8066 @cindex Source files, use by binder
8067 The effect of this consistency checking, which includes source files, is
8068 that the binder ensures that the program is consistent with the latest
8069 version of the source files that can be located at bind time. Editing a
8070 source file without compiling files that depend on the source file cause
8071 error messages to be generated by the binder.
8073 For example, suppose you have a main program @file{hello.adb} and a
8074 package @code{P}, from file @file{p.ads} and you perform the following
8079 Enter @code{gcc -c hello.adb} to compile the main program.
8082 Enter @code{gcc -c p.ads} to compile package @code{P}.
8085 Edit file @file{p.ads}.
8088 Enter @code{gnatbind hello}.
8092 At this point, the file @file{p.ali} contains an out-of-date time stamp
8093 because the file @file{p.ads} has been edited. The attempt at binding
8094 fails, and the binder generates the following error messages:
8097 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8098 error: "p.ads" has been modified and must be recompiled
8102 Now both files must be recompiled as indicated, and then the bind can
8103 succeed, generating a main program. You need not normally be concerned
8104 with the contents of this file, but for reference purposes a sample
8105 binder output file is given in @ref{Example of Binder Output File}.
8107 In most normal usage, the default mode of @command{gnatbind} which is to
8108 generate the main package in Ada, as described in the previous section.
8109 In particular, this means that any Ada programmer can read and understand
8110 the generated main program. It can also be debugged just like any other
8111 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8112 @command{gnatbind} and @command{gnatlink}.
8114 @node Switches for gnatbind
8115 @section Switches for @command{gnatbind}
8118 The following switches are available with @code{gnatbind}; details will
8119 be presented in subsequent sections.
8122 * Consistency-Checking Modes::
8123 * Binder Error Message Control::
8124 * Elaboration Control::
8126 * Dynamic Allocation Control::
8127 * Binding with Non-Ada Main Programs::
8128 * Binding Programs with No Main Subprogram::
8135 @cindex @option{--version} @command{gnatbind}
8136 Display Copyright and version, then exit disregarding all other options.
8139 @cindex @option{--help} @command{gnatbind}
8140 If @option{--version} was not used, display usage, then exit disregarding
8144 @cindex @option{-a} @command{gnatbind}
8145 Indicates that, if supported by the platform, the adainit procedure should
8146 be treated as an initialisation routine by the linker (a constructor). This
8147 is intended to be used by the Project Manager to automatically initialize
8148 shared Stand-Alone Libraries.
8150 @item ^-aO^/OBJECT_SEARCH^
8151 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8152 Specify directory to be searched for ALI files.
8154 @item ^-aI^/SOURCE_SEARCH^
8155 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8156 Specify directory to be searched for source file.
8158 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8159 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8160 Output ALI list (to standard output or to the named file).
8162 @item ^-b^/REPORT_ERRORS=BRIEF^
8163 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8164 Generate brief messages to @file{stderr} even if verbose mode set.
8166 @item ^-c^/NOOUTPUT^
8167 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8168 Check only, no generation of binder output file.
8170 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8171 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8172 This switch can be used to change the default task stack size value
8173 to a specified size @var{nn}, which is expressed in bytes by default, or
8174 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8176 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8177 in effect, to completing all task specs with
8178 @smallexample @c ada
8179 pragma Storage_Size (nn);
8181 When they do not already have such a pragma.
8183 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8184 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8185 This switch can be used to change the default secondary stack size value
8186 to a specified size @var{nn}, which is expressed in bytes by default, or
8187 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8190 The secondary stack is used to deal with functions that return a variable
8191 sized result, for example a function returning an unconstrained
8192 String. There are two ways in which this secondary stack is allocated.
8194 For most targets, the secondary stack is growing on demand and is allocated
8195 as a chain of blocks in the heap. The -D option is not very
8196 relevant. It only give some control over the size of the allocated
8197 blocks (whose size is the minimum of the default secondary stack size value,
8198 and the actual size needed for the current allocation request).
8200 For certain targets, notably VxWorks 653,
8201 the secondary stack is allocated by carving off a fixed ratio chunk of the
8202 primary task stack. The -D option is used to define the
8203 size of the environment task's secondary stack.
8205 @item ^-e^/ELABORATION_DEPENDENCIES^
8206 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8207 Output complete list of elaboration-order dependencies.
8209 @item ^-E^/STORE_TRACEBACKS^
8210 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8211 Store tracebacks in exception occurrences when the target supports it.
8213 @c The following may get moved to an appendix
8214 This option is currently supported on the following targets:
8215 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8217 See also the packages @code{GNAT.Traceback} and
8218 @code{GNAT.Traceback.Symbolic} for more information.
8220 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8221 @command{gcc} option.
8224 @item ^-F^/FORCE_ELABS_FLAGS^
8225 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8226 Force the checks of elaboration flags. @command{gnatbind} does not normally
8227 generate checks of elaboration flags for the main executable, except when
8228 a Stand-Alone Library is used. However, there are cases when this cannot be
8229 detected by gnatbind. An example is importing an interface of a Stand-Alone
8230 Library through a pragma Import and only specifying through a linker switch
8231 this Stand-Alone Library. This switch is used to guarantee that elaboration
8232 flag checks are generated.
8235 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8236 Output usage (help) information
8238 @item ^-H32^/32_MALLOC^
8239 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8240 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8241 For further details see @ref{Dynamic Allocation Control}.
8243 @item ^-H64^/64_MALLOC^
8244 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8245 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8246 @cindex @code{__gnat_malloc}
8247 For further details see @ref{Dynamic Allocation Control}.
8250 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8251 Specify directory to be searched for source and ALI files.
8253 @item ^-I-^/NOCURRENT_DIRECTORY^
8254 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8255 Do not look for sources in the current directory where @code{gnatbind} was
8256 invoked, and do not look for ALI files in the directory containing the
8257 ALI file named in the @code{gnatbind} command line.
8259 @item ^-l^/ORDER_OF_ELABORATION^
8260 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8261 Output chosen elaboration order.
8263 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8264 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8265 Bind the units for library building. In this case the adainit and
8266 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8267 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8268 ^@var{xxx}final^@var{XXX}FINAL^.
8269 Implies ^-n^/NOCOMPILE^.
8271 (@xref{GNAT and Libraries}, for more details.)
8274 On OpenVMS, these init and final procedures are exported in uppercase
8275 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8276 the init procedure will be "TOTOINIT" and the exported name of the final
8277 procedure will be "TOTOFINAL".
8280 @item ^-Mxyz^/RENAME_MAIN=xyz^
8281 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8282 Rename generated main program from main to xyz. This option is
8283 supported on cross environments only.
8285 @item ^-m^/ERROR_LIMIT=^@var{n}
8286 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8287 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8288 in the range 1..999999. The default value if no switch is
8289 given is 9999. If the number of warnings reaches this limit, then a
8290 message is output and further warnings are suppressed, the bind
8291 continues in this case. If the number of errors reaches this
8292 limit, then a message is output and the bind is abandoned.
8293 A value of zero means that no limit is enforced. The equal
8297 Furthermore, under Windows, the sources pointed to by the libraries path
8298 set in the registry are not searched for.
8302 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8306 @cindex @option{-nostdinc} (@command{gnatbind})
8307 Do not look for sources in the system default directory.
8310 @cindex @option{-nostdlib} (@command{gnatbind})
8311 Do not look for library files in the system default directory.
8313 @item --RTS=@var{rts-path}
8314 @cindex @option{--RTS} (@code{gnatbind})
8315 Specifies the default location of the runtime library. Same meaning as the
8316 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8318 @item ^-o ^/OUTPUT=^@var{file}
8319 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8320 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8321 Note that if this option is used, then linking must be done manually,
8322 gnatlink cannot be used.
8324 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8325 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8326 Output object list (to standard output or to the named file).
8328 @item ^-p^/PESSIMISTIC_ELABORATION^
8329 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8330 Pessimistic (worst-case) elaboration order
8333 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8334 Generate binder file suitable for CodePeer.
8337 @cindex @option{^-R^-R^} (@command{gnatbind})
8338 Output closure source list.
8340 @item ^-s^/READ_SOURCES=ALL^
8341 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8342 Require all source files to be present.
8344 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8345 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8346 Specifies the value to be used when detecting uninitialized scalar
8347 objects with pragma Initialize_Scalars.
8348 The @var{xxx} ^string specified with the switch^option^ may be either
8350 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8351 @item ``@option{^lo^LOW^}'' for the lowest possible value
8352 @item ``@option{^hi^HIGH^}'' for the highest possible value
8353 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8354 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8357 In addition, you can specify @option{-Sev} to indicate that the value is
8358 to be set at run time. In this case, the program will look for an environment
8359 @cindex GNAT_INIT_SCALARS
8360 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8361 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8362 If no environment variable is found, or if it does not have a valid value,
8363 then the default is @option{in} (invalid values).
8367 @cindex @option{-static} (@code{gnatbind})
8368 Link against a static GNAT run time.
8371 @cindex @option{-shared} (@code{gnatbind})
8372 Link against a shared GNAT run time when available.
8375 @item ^-t^/NOTIME_STAMP_CHECK^
8376 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8377 Tolerate time stamp and other consistency errors
8379 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8380 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8381 Set the time slice value to @var{n} milliseconds. If the system supports
8382 the specification of a specific time slice value, then the indicated value
8383 is used. If the system does not support specific time slice values, but
8384 does support some general notion of round-robin scheduling, then any
8385 nonzero value will activate round-robin scheduling.
8387 A value of zero is treated specially. It turns off time
8388 slicing, and in addition, indicates to the tasking run time that the
8389 semantics should match as closely as possible the Annex D
8390 requirements of the Ada RM, and in particular sets the default
8391 scheduling policy to @code{FIFO_Within_Priorities}.
8393 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8394 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8395 Enable dynamic stack usage, with @var{n} results stored and displayed
8396 at program termination. A result is generated when a task
8397 terminates. Results that can't be stored are displayed on the fly, at
8398 task termination. This option is currently not supported on Itanium
8399 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8401 @item ^-v^/REPORT_ERRORS=VERBOSE^
8402 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8403 Verbose mode. Write error messages, header, summary output to
8408 @cindex @option{-w} (@code{gnatbind})
8409 Warning mode (@var{x}=s/e for suppress/treat as error)
8413 @item /WARNINGS=NORMAL
8414 @cindex @option{/WARNINGS} (@code{gnatbind})
8415 Normal warnings mode. Warnings are issued but ignored
8417 @item /WARNINGS=SUPPRESS
8418 @cindex @option{/WARNINGS} (@code{gnatbind})
8419 All warning messages are suppressed
8421 @item /WARNINGS=ERROR
8422 @cindex @option{/WARNINGS} (@code{gnatbind})
8423 Warning messages are treated as fatal errors
8426 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8427 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8428 Override default wide character encoding for standard Text_IO files.
8430 @item ^-x^/READ_SOURCES=NONE^
8431 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8432 Exclude source files (check object consistency only).
8435 @item /READ_SOURCES=AVAILABLE
8436 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8437 Default mode, in which sources are checked for consistency only if
8441 @item ^-y^/ENABLE_LEAP_SECONDS^
8442 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8443 Enable leap seconds support in @code{Ada.Calendar} and its children.
8445 @item ^-z^/ZERO_MAIN^
8446 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8452 You may obtain this listing of switches by running @code{gnatbind} with
8456 @node Consistency-Checking Modes
8457 @subsection Consistency-Checking Modes
8460 As described earlier, by default @code{gnatbind} checks
8461 that object files are consistent with one another and are consistent
8462 with any source files it can locate. The following switches control binder
8467 @item ^-s^/READ_SOURCES=ALL^
8468 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8469 Require source files to be present. In this mode, the binder must be
8470 able to locate all source files that are referenced, in order to check
8471 their consistency. In normal mode, if a source file cannot be located it
8472 is simply ignored. If you specify this switch, a missing source
8475 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8476 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8477 Override default wide character encoding for standard Text_IO files.
8478 Normally the default wide character encoding method used for standard
8479 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8480 the main source input (see description of switch
8481 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8482 use of this switch for the binder (which has the same set of
8483 possible arguments) overrides this default as specified.
8485 @item ^-x^/READ_SOURCES=NONE^
8486 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8487 Exclude source files. In this mode, the binder only checks that ALI
8488 files are consistent with one another. Source files are not accessed.
8489 The binder runs faster in this mode, and there is still a guarantee that
8490 the resulting program is self-consistent.
8491 If a source file has been edited since it was last compiled, and you
8492 specify this switch, the binder will not detect that the object
8493 file is out of date with respect to the source file. Note that this is the
8494 mode that is automatically used by @command{gnatmake} because in this
8495 case the checking against sources has already been performed by
8496 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8499 @item /READ_SOURCES=AVAILABLE
8500 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8501 This is the default mode in which source files are checked if they are
8502 available, and ignored if they are not available.
8506 @node Binder Error Message Control
8507 @subsection Binder Error Message Control
8510 The following switches provide control over the generation of error
8511 messages from the binder:
8515 @item ^-v^/REPORT_ERRORS=VERBOSE^
8516 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8517 Verbose mode. In the normal mode, brief error messages are generated to
8518 @file{stderr}. If this switch is present, a header is written
8519 to @file{stdout} and any error messages are directed to @file{stdout}.
8520 All that is written to @file{stderr} is a brief summary message.
8522 @item ^-b^/REPORT_ERRORS=BRIEF^
8523 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8524 Generate brief error messages to @file{stderr} even if verbose mode is
8525 specified. This is relevant only when used with the
8526 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8530 @cindex @option{-m} (@code{gnatbind})
8531 Limits the number of error messages to @var{n}, a decimal integer in the
8532 range 1-999. The binder terminates immediately if this limit is reached.
8535 @cindex @option{-M} (@code{gnatbind})
8536 Renames the generated main program from @code{main} to @code{xxx}.
8537 This is useful in the case of some cross-building environments, where
8538 the actual main program is separate from the one generated
8542 @item ^-ws^/WARNINGS=SUPPRESS^
8543 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8545 Suppress all warning messages.
8547 @item ^-we^/WARNINGS=ERROR^
8548 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8549 Treat any warning messages as fatal errors.
8552 @item /WARNINGS=NORMAL
8553 Standard mode with warnings generated, but warnings do not get treated
8557 @item ^-t^/NOTIME_STAMP_CHECK^
8558 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8559 @cindex Time stamp checks, in binder
8560 @cindex Binder consistency checks
8561 @cindex Consistency checks, in binder
8562 The binder performs a number of consistency checks including:
8566 Check that time stamps of a given source unit are consistent
8568 Check that checksums of a given source unit are consistent
8570 Check that consistent versions of @code{GNAT} were used for compilation
8572 Check consistency of configuration pragmas as required
8576 Normally failure of such checks, in accordance with the consistency
8577 requirements of the Ada Reference Manual, causes error messages to be
8578 generated which abort the binder and prevent the output of a binder
8579 file and subsequent link to obtain an executable.
8581 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8582 into warnings, so that
8583 binding and linking can continue to completion even in the presence of such
8584 errors. The result may be a failed link (due to missing symbols), or a
8585 non-functional executable which has undefined semantics.
8586 @emph{This means that
8587 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8591 @node Elaboration Control
8592 @subsection Elaboration Control
8595 The following switches provide additional control over the elaboration
8596 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8599 @item ^-p^/PESSIMISTIC_ELABORATION^
8600 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8601 Normally the binder attempts to choose an elaboration order that is
8602 likely to minimize the likelihood of an elaboration order error resulting
8603 in raising a @code{Program_Error} exception. This switch reverses the
8604 action of the binder, and requests that it deliberately choose an order
8605 that is likely to maximize the likelihood of an elaboration error.
8606 This is useful in ensuring portability and avoiding dependence on
8607 accidental fortuitous elaboration ordering.
8609 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8611 elaboration checking is used (@option{-gnatE} switch used for compilation).
8612 This is because in the default static elaboration mode, all necessary
8613 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8614 These implicit pragmas are still respected by the binder in
8615 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8616 safe elaboration order is assured.
8619 @node Output Control
8620 @subsection Output Control
8623 The following switches allow additional control over the output
8624 generated by the binder.
8629 @item ^-c^/NOOUTPUT^
8630 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8631 Check only. Do not generate the binder output file. In this mode the
8632 binder performs all error checks but does not generate an output file.
8634 @item ^-e^/ELABORATION_DEPENDENCIES^
8635 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8636 Output complete list of elaboration-order dependencies, showing the
8637 reason for each dependency. This output can be rather extensive but may
8638 be useful in diagnosing problems with elaboration order. The output is
8639 written to @file{stdout}.
8642 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8643 Output usage information. The output is written to @file{stdout}.
8645 @item ^-K^/LINKER_OPTION_LIST^
8646 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8647 Output linker options to @file{stdout}. Includes library search paths,
8648 contents of pragmas Ident and Linker_Options, and libraries added
8651 @item ^-l^/ORDER_OF_ELABORATION^
8652 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8653 Output chosen elaboration order. The output is written to @file{stdout}.
8655 @item ^-O^/OBJECT_LIST^
8656 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8657 Output full names of all the object files that must be linked to provide
8658 the Ada component of the program. The output is written to @file{stdout}.
8659 This list includes the files explicitly supplied and referenced by the user
8660 as well as implicitly referenced run-time unit files. The latter are
8661 omitted if the corresponding units reside in shared libraries. The
8662 directory names for the run-time units depend on the system configuration.
8664 @item ^-o ^/OUTPUT=^@var{file}
8665 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8666 Set name of output file to @var{file} instead of the normal
8667 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8668 binder generated body filename.
8669 Note that if this option is used, then linking must be done manually.
8670 It is not possible to use gnatlink in this case, since it cannot locate
8673 @item ^-r^/RESTRICTION_LIST^
8674 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8675 Generate list of @code{pragma Restrictions} that could be applied to
8676 the current unit. This is useful for code audit purposes, and also may
8677 be used to improve code generation in some cases.
8681 @node Dynamic Allocation Control
8682 @subsection Dynamic Allocation Control
8685 The heap control switches -- @option{-H32} and @option{-H64} --
8686 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8687 They only affect compiler-generated allocations via @code{__gnat_malloc};
8688 explicit calls to @code{malloc} and related functions from the C
8689 run-time library are unaffected.
8693 Allocate memory on 32-bit heap
8696 Allocate memory on 64-bit heap. This is the default
8697 unless explicitly overridden by a @code{'Size} clause on the access type.
8702 See also @ref{Access types and 32/64-bit allocation}.
8706 These switches are only effective on VMS platforms.
8710 @node Binding with Non-Ada Main Programs
8711 @subsection Binding with Non-Ada Main Programs
8714 In our description so far we have assumed that the main
8715 program is in Ada, and that the task of the binder is to generate a
8716 corresponding function @code{main} that invokes this Ada main
8717 program. GNAT also supports the building of executable programs where
8718 the main program is not in Ada, but some of the called routines are
8719 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8720 The following switch is used in this situation:
8724 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8725 No main program. The main program is not in Ada.
8729 In this case, most of the functions of the binder are still required,
8730 but instead of generating a main program, the binder generates a file
8731 containing the following callable routines:
8736 You must call this routine to initialize the Ada part of the program by
8737 calling the necessary elaboration routines. A call to @code{adainit} is
8738 required before the first call to an Ada subprogram.
8740 Note that it is assumed that the basic execution environment must be setup
8741 to be appropriate for Ada execution at the point where the first Ada
8742 subprogram is called. In particular, if the Ada code will do any
8743 floating-point operations, then the FPU must be setup in an appropriate
8744 manner. For the case of the x86, for example, full precision mode is
8745 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8746 that the FPU is in the right state.
8750 You must call this routine to perform any library-level finalization
8751 required by the Ada subprograms. A call to @code{adafinal} is required
8752 after the last call to an Ada subprogram, and before the program
8757 If the @option{^-n^/NOMAIN^} switch
8758 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8759 @cindex Binder, multiple input files
8760 is given, more than one ALI file may appear on
8761 the command line for @code{gnatbind}. The normal @dfn{closure}
8762 calculation is performed for each of the specified units. Calculating
8763 the closure means finding out the set of units involved by tracing
8764 @code{with} references. The reason it is necessary to be able to
8765 specify more than one ALI file is that a given program may invoke two or
8766 more quite separate groups of Ada units.
8768 The binder takes the name of its output file from the last specified ALI
8769 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8770 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8771 The output is an Ada unit in source form that can be compiled with GNAT.
8772 This compilation occurs automatically as part of the @command{gnatlink}
8775 Currently the GNAT run time requires a FPU using 80 bits mode
8776 precision. Under targets where this is not the default it is required to
8777 call GNAT.Float_Control.Reset before using floating point numbers (this
8778 include float computation, float input and output) in the Ada code. A
8779 side effect is that this could be the wrong mode for the foreign code
8780 where floating point computation could be broken after this call.
8782 @node Binding Programs with No Main Subprogram
8783 @subsection Binding Programs with No Main Subprogram
8786 It is possible to have an Ada program which does not have a main
8787 subprogram. This program will call the elaboration routines of all the
8788 packages, then the finalization routines.
8790 The following switch is used to bind programs organized in this manner:
8793 @item ^-z^/ZERO_MAIN^
8794 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8795 Normally the binder checks that the unit name given on the command line
8796 corresponds to a suitable main subprogram. When this switch is used,
8797 a list of ALI files can be given, and the execution of the program
8798 consists of elaboration of these units in an appropriate order. Note
8799 that the default wide character encoding method for standard Text_IO
8800 files is always set to Brackets if this switch is set (you can use
8802 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8805 @node Command-Line Access
8806 @section Command-Line Access
8809 The package @code{Ada.Command_Line} provides access to the command-line
8810 arguments and program name. In order for this interface to operate
8811 correctly, the two variables
8823 are declared in one of the GNAT library routines. These variables must
8824 be set from the actual @code{argc} and @code{argv} values passed to the
8825 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8826 generates the C main program to automatically set these variables.
8827 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8828 set these variables. If they are not set, the procedures in
8829 @code{Ada.Command_Line} will not be available, and any attempt to use
8830 them will raise @code{Constraint_Error}. If command line access is
8831 required, your main program must set @code{gnat_argc} and
8832 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8835 @node Search Paths for gnatbind
8836 @section Search Paths for @code{gnatbind}
8839 The binder takes the name of an ALI file as its argument and needs to
8840 locate source files as well as other ALI files to verify object consistency.
8842 For source files, it follows exactly the same search rules as @command{gcc}
8843 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8844 directories searched are:
8848 The directory containing the ALI file named in the command line, unless
8849 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8852 All directories specified by @option{^-I^/SEARCH^}
8853 switches on the @code{gnatbind}
8854 command line, in the order given.
8857 @findex ADA_PRJ_OBJECTS_FILE
8858 Each of the directories listed in the text file whose name is given
8859 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8862 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8863 driver when project files are used. It should not normally be set
8867 @findex ADA_OBJECTS_PATH
8868 Each of the directories listed in the value of the
8869 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8871 Construct this value
8872 exactly as the @env{PATH} environment variable: a list of directory
8873 names separated by colons (semicolons when working with the NT version
8877 Normally, define this value as a logical name containing a comma separated
8878 list of directory names.
8880 This variable can also be defined by means of an environment string
8881 (an argument to the HP C exec* set of functions).
8885 DEFINE ANOTHER_PATH FOO:[BAG]
8886 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8889 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8890 first, followed by the standard Ada
8891 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8892 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8893 (Text_IO, Sequential_IO, etc)
8894 instead of the standard Ada packages. Thus, in order to get the standard Ada
8895 packages by default, ADA_OBJECTS_PATH must be redefined.
8899 The content of the @file{ada_object_path} file which is part of the GNAT
8900 installation tree and is used to store standard libraries such as the
8901 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8904 @ref{Installing a library}
8909 In the binder the switch @option{^-I^/SEARCH^}
8910 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8911 is used to specify both source and
8912 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8913 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8914 instead if you want to specify
8915 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8916 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8917 if you want to specify library paths
8918 only. This means that for the binder
8919 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8920 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8921 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8922 The binder generates the bind file (a C language source file) in the
8923 current working directory.
8929 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8930 children make up the GNAT Run-Time Library, together with the package
8931 GNAT and its children, which contain a set of useful additional
8932 library functions provided by GNAT. The sources for these units are
8933 needed by the compiler and are kept together in one directory. The ALI
8934 files and object files generated by compiling the RTL are needed by the
8935 binder and the linker and are kept together in one directory, typically
8936 different from the directory containing the sources. In a normal
8937 installation, you need not specify these directory names when compiling
8938 or binding. Either the environment variables or the built-in defaults
8939 cause these files to be found.
8941 Besides simplifying access to the RTL, a major use of search paths is
8942 in compiling sources from multiple directories. This can make
8943 development environments much more flexible.
8945 @node Examples of gnatbind Usage
8946 @section Examples of @code{gnatbind} Usage
8949 This section contains a number of examples of using the GNAT binding
8950 utility @code{gnatbind}.
8953 @item gnatbind hello
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{b~hello.adb}. This is the normal, default use of the binder.
8959 @item gnatbind hello -o mainprog.adb
8962 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8964 The main program @code{Hello} (source program in @file{hello.adb}) is
8965 bound using the standard switch settings. The generated main program is
8966 @file{mainprog.adb} with the associated spec in
8967 @file{mainprog.ads}. Note that you must specify the body here not the
8968 spec. Note that if this option is used, then linking must be done manually,
8969 since gnatlink will not be able to find the generated file.
8972 @c ------------------------------------
8973 @node Linking Using gnatlink
8974 @chapter Linking Using @command{gnatlink}
8975 @c ------------------------------------
8979 This chapter discusses @command{gnatlink}, a tool that links
8980 an Ada program and builds an executable file. This utility
8981 invokes the system linker ^(via the @command{gcc} command)^^
8982 with a correct list of object files and library references.
8983 @command{gnatlink} automatically determines the list of files and
8984 references for the Ada part of a program. It uses the binder file
8985 generated by the @command{gnatbind} to determine this list.
8987 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8988 driver (see @ref{The GNAT Driver and Project Files}).
8991 * Running gnatlink::
8992 * Switches for gnatlink::
8995 @node Running gnatlink
8996 @section Running @command{gnatlink}
8999 The form of the @command{gnatlink} command is
9002 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9003 @c @ovar{non-Ada objects} @ovar{linker options}
9004 @c Expanding @ovar macro inline (explanation in macro def comments)
9005 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9006 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9011 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9013 or linker options) may be in any order, provided that no non-Ada object may
9014 be mistaken for a main @file{ALI} file.
9015 Any file name @file{F} without the @file{.ali}
9016 extension will be taken as the main @file{ALI} file if a file exists
9017 whose name is the concatenation of @file{F} and @file{.ali}.
9020 @file{@var{mainprog}.ali} references the ALI file of the main program.
9021 The @file{.ali} extension of this file can be omitted. From this
9022 reference, @command{gnatlink} locates the corresponding binder file
9023 @file{b~@var{mainprog}.adb} and, using the information in this file along
9024 with the list of non-Ada objects and linker options, constructs a
9025 linker command file to create the executable.
9027 The arguments other than the @command{gnatlink} switches and the main
9028 @file{ALI} file are passed to the linker uninterpreted.
9029 They typically include the names of
9030 object files for units written in other languages than Ada and any library
9031 references required to resolve references in any of these foreign language
9032 units, or in @code{Import} pragmas in any Ada units.
9034 @var{linker options} is an optional list of linker specific
9036 The default linker called by gnatlink is @command{gcc} which in
9037 turn calls the appropriate system linker.
9039 One useful option for the linker is @option{-s}: it reduces the size of the
9040 executable by removing all symbol table and relocation information from the
9043 Standard options for the linker such as @option{-lmy_lib} or
9044 @option{-Ldir} can be added as is.
9045 For options that are not recognized by
9046 @command{gcc} as linker options, use the @command{gcc} switches
9047 @option{-Xlinker} or @option{-Wl,}.
9049 Refer to the GCC documentation for
9052 Here is an example showing how to generate a linker map:
9055 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9058 Using @var{linker options} it is possible to set the program stack and
9061 See @ref{Setting Stack Size from gnatlink} and
9062 @ref{Setting Heap Size from gnatlink}.
9065 @command{gnatlink} determines the list of objects required by the Ada
9066 program and prepends them to the list of objects passed to the linker.
9067 @command{gnatlink} also gathers any arguments set by the use of
9068 @code{pragma Linker_Options} and adds them to the list of arguments
9069 presented to the linker.
9072 @command{gnatlink} accepts the following types of extra files on the command
9073 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9074 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9075 handled according to their extension.
9078 @node Switches for gnatlink
9079 @section Switches for @command{gnatlink}
9082 The following switches are available with the @command{gnatlink} utility:
9088 @cindex @option{--version} @command{gnatlink}
9089 Display Copyright and version, then exit disregarding all other options.
9092 @cindex @option{--help} @command{gnatlink}
9093 If @option{--version} was not used, display usage, then exit disregarding
9096 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9097 @cindex Command line length
9098 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9099 On some targets, the command line length is limited, and @command{gnatlink}
9100 will generate a separate file for the linker if the list of object files
9102 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9103 to be generated even if
9104 the limit is not exceeded. This is useful in some cases to deal with
9105 special situations where the command line length is exceeded.
9108 @cindex Debugging information, including
9109 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9110 The option to include debugging information causes the Ada bind file (in
9111 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9112 @option{^-g^/DEBUG^}.
9113 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9114 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9115 Without @option{^-g^/DEBUG^}, the binder removes these files by
9116 default. The same procedure apply if a C bind file was generated using
9117 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9118 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9120 @item ^-n^/NOCOMPILE^
9121 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9122 Do not compile the file generated by the binder. This may be used when
9123 a link is rerun with different options, but there is no need to recompile
9127 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9128 Causes additional information to be output, including a full list of the
9129 included object files. This switch option is most useful when you want
9130 to see what set of object files are being used in the link step.
9132 @item ^-v -v^/VERBOSE/VERBOSE^
9133 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9134 Very verbose mode. Requests that the compiler operate in verbose mode when
9135 it compiles the binder file, and that the system linker run in verbose mode.
9137 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9138 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9139 @var{exec-name} specifies an alternate name for the generated
9140 executable program. If this switch is omitted, the executable has the same
9141 name as the main unit. For example, @code{gnatlink try.ali} creates
9142 an executable called @file{^try^TRY.EXE^}.
9145 @item -b @var{target}
9146 @cindex @option{-b} (@command{gnatlink})
9147 Compile your program to run on @var{target}, which is the name of a
9148 system configuration. You must have a GNAT cross-compiler built if
9149 @var{target} is not the same as your host system.
9152 @cindex @option{-B} (@command{gnatlink})
9153 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9154 from @var{dir} instead of the default location. Only use this switch
9155 when multiple versions of the GNAT compiler are available.
9156 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9157 for further details. You would normally use the @option{-b} or
9158 @option{-V} switch instead.
9161 When linking an executable, create a map file. The name of the map file
9162 has the same name as the executable with extension ".map".
9165 When linking an executable, create a map file. The name of the map file is
9168 @item --GCC=@var{compiler_name}
9169 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9170 Program used for compiling the binder file. The default is
9171 @command{gcc}. You need to use quotes around @var{compiler_name} if
9172 @code{compiler_name} contains spaces or other separator characters.
9173 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9174 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9175 inserted after your command name. Thus in the above example the compiler
9176 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9177 A limitation of this syntax is that the name and path name of the executable
9178 itself must not include any embedded spaces. If the compiler executable is
9179 different from the default one (gcc or <prefix>-gcc), then the back-end
9180 switches in the ALI file are not used to compile the binder generated source.
9181 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9182 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9183 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9184 is taken into account. However, all the additional switches are also taken
9186 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9187 @option{--GCC="bar -x -y -z -t"}.
9189 @item --LINK=@var{name}
9190 @cindex @option{--LINK=} (@command{gnatlink})
9191 @var{name} is the name of the linker to be invoked. This is especially
9192 useful in mixed language programs since languages such as C++ require
9193 their own linker to be used. When this switch is omitted, the default
9194 name for the linker is @command{gcc}. When this switch is used, the
9195 specified linker is called instead of @command{gcc} with exactly the same
9196 parameters that would have been passed to @command{gcc} so if the desired
9197 linker requires different parameters it is necessary to use a wrapper
9198 script that massages the parameters before invoking the real linker. It
9199 may be useful to control the exact invocation by using the verbose
9205 @item /DEBUG=TRACEBACK
9206 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9207 This qualifier causes sufficient information to be included in the
9208 executable file to allow a traceback, but does not include the full
9209 symbol information needed by the debugger.
9211 @item /IDENTIFICATION="<string>"
9212 @code{"<string>"} specifies the string to be stored in the image file
9213 identification field in the image header.
9214 It overrides any pragma @code{Ident} specified string.
9216 @item /NOINHIBIT-EXEC
9217 Generate the executable file even if there are linker warnings.
9219 @item /NOSTART_FILES
9220 Don't link in the object file containing the ``main'' transfer address.
9221 Used when linking with a foreign language main program compiled with an
9225 Prefer linking with object libraries over sharable images, even without
9231 @node The GNAT Make Program gnatmake
9232 @chapter The GNAT Make Program @command{gnatmake}
9236 * Running gnatmake::
9237 * Switches for gnatmake::
9238 * Mode Switches for gnatmake::
9239 * Notes on the Command Line::
9240 * How gnatmake Works::
9241 * Examples of gnatmake Usage::
9244 A typical development cycle when working on an Ada program consists of
9245 the following steps:
9249 Edit some sources to fix bugs.
9255 Compile all sources affected.
9265 The third step can be tricky, because not only do the modified files
9266 @cindex Dependency rules
9267 have to be compiled, but any files depending on these files must also be
9268 recompiled. The dependency rules in Ada can be quite complex, especially
9269 in the presence of overloading, @code{use} clauses, generics and inlined
9272 @command{gnatmake} automatically takes care of the third and fourth steps
9273 of this process. It determines which sources need to be compiled,
9274 compiles them, and binds and links the resulting object files.
9276 Unlike some other Ada make programs, the dependencies are always
9277 accurately recomputed from the new sources. The source based approach of
9278 the GNAT compilation model makes this possible. This means that if
9279 changes to the source program cause corresponding changes in
9280 dependencies, they will always be tracked exactly correctly by
9283 @node Running gnatmake
9284 @section Running @command{gnatmake}
9287 The usual form of the @command{gnatmake} command is
9290 @c $ gnatmake @ovar{switches} @var{file_name}
9291 @c @ovar{file_names} @ovar{mode_switches}
9292 @c Expanding @ovar macro inline (explanation in macro def comments)
9293 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9294 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9298 The only required argument is one @var{file_name}, which specifies
9299 a compilation unit that is a main program. Several @var{file_names} can be
9300 specified: this will result in several executables being built.
9301 If @code{switches} are present, they can be placed before the first
9302 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9303 If @var{mode_switches} are present, they must always be placed after
9304 the last @var{file_name} and all @code{switches}.
9306 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9307 extension may be omitted from the @var{file_name} arguments. However, if
9308 you are using non-standard extensions, then it is required that the
9309 extension be given. A relative or absolute directory path can be
9310 specified in a @var{file_name}, in which case, the input source file will
9311 be searched for in the specified directory only. Otherwise, the input
9312 source file will first be searched in the directory where
9313 @command{gnatmake} was invoked and if it is not found, it will be search on
9314 the source path of the compiler as described in
9315 @ref{Search Paths and the Run-Time Library (RTL)}.
9317 All @command{gnatmake} output (except when you specify
9318 @option{^-M^/DEPENDENCIES_LIST^}) is to
9319 @file{stderr}. The output produced by the
9320 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9323 @node Switches for gnatmake
9324 @section Switches for @command{gnatmake}
9327 You may specify any of the following switches to @command{gnatmake}:
9333 @cindex @option{--version} @command{gnatmake}
9334 Display Copyright and version, then exit disregarding all other options.
9337 @cindex @option{--help} @command{gnatmake}
9338 If @option{--version} was not used, display usage, then exit disregarding
9342 @item --GCC=@var{compiler_name}
9343 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9344 Program used for compiling. The default is `@command{gcc}'. You need to use
9345 quotes around @var{compiler_name} if @code{compiler_name} contains
9346 spaces or other separator characters. As an example @option{--GCC="foo -x
9347 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9348 compiler. A limitation of this syntax is that the name and path name of
9349 the executable itself must not include any embedded spaces. Note that
9350 switch @option{-c} is always inserted after your command name. Thus in the
9351 above example the compiler command that will be used by @command{gnatmake}
9352 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9353 used, only the last @var{compiler_name} is taken into account. However,
9354 all the additional switches are also taken into account. Thus,
9355 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9356 @option{--GCC="bar -x -y -z -t"}.
9358 @item --GNATBIND=@var{binder_name}
9359 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9360 Program used for binding. The default is `@code{gnatbind}'. You need to
9361 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9362 or other separator characters. As an example @option{--GNATBIND="bar -x
9363 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9364 binder. Binder switches that are normally appended by @command{gnatmake}
9365 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9366 A limitation of this syntax is that the name and path name of the executable
9367 itself must not include any embedded spaces.
9369 @item --GNATLINK=@var{linker_name}
9370 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9371 Program used for linking. The default is `@command{gnatlink}'. You need to
9372 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9373 or other separator characters. As an example @option{--GNATLINK="lan -x
9374 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9375 linker. Linker switches that are normally appended by @command{gnatmake} to
9376 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9377 A limitation of this syntax is that the name and path name of the executable
9378 itself must not include any embedded spaces.
9382 @item ^--subdirs^/SUBDIRS^=subdir
9383 Actual object directory of each project file is the subdirectory subdir of the
9384 object directory specified or defaulted in the project file.
9386 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9387 Disallow simultaneous compilations in the same object directory when
9388 project files are used.
9390 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9391 By default, shared library projects are not allowed to import static library
9392 projects. When this switch is used on the command line, this restriction is
9395 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9396 Specify a source info file. This switch is active only when project files
9397 are used. If the source info file is specified as a relative path, then it is
9398 relative to the object directory of the main project. If the source info file
9399 does not exist, then after the Project Manager has successfully parsed and
9400 processed the project files and found the sources, it creates the source info
9401 file. If the source info file already exists and can be read successfully,
9402 then the Project Manager will get all the needed information about the sources
9403 from the source info file and will not look for them. This reduces the time
9404 to process the project files, especially when looking for sources that take a
9405 long time. If the source info file exists but cannot be parsed successfully,
9406 the Project Manager will attempt to recreate it. If the Project Manager fails
9407 to create the source info file, a message is issued, but gnatmake does not
9408 fail. @command{gnatmake} "trusts" the source info file. This means that
9409 if the source files have changed (addition, deletion, moving to a different
9410 source directory), then the source info file need to be deleted and recreated.
9413 @item --create-map-file
9414 When linking an executable, create a map file. The name of the map file
9415 has the same name as the executable with extension ".map".
9417 @item --create-map-file=mapfile
9418 When linking an executable, create a map file. The name of the map file is
9423 @item ^-a^/ALL_FILES^
9424 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9425 Consider all files in the make process, even the GNAT internal system
9426 files (for example, the predefined Ada library files), as well as any
9427 locked files. Locked files are files whose ALI file is write-protected.
9429 @command{gnatmake} does not check these files,
9430 because the assumption is that the GNAT internal files are properly up
9431 to date, and also that any write protected ALI files have been properly
9432 installed. Note that if there is an installation problem, such that one
9433 of these files is not up to date, it will be properly caught by the
9435 You may have to specify this switch if you are working on GNAT
9436 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9437 in conjunction with @option{^-f^/FORCE_COMPILE^}
9438 if you need to recompile an entire application,
9439 including run-time files, using special configuration pragmas,
9440 such as a @code{Normalize_Scalars} pragma.
9443 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9446 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9449 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9452 @item ^-b^/ACTIONS=BIND^
9453 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9454 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9455 compilation and binding, but no link.
9456 Can be combined with @option{^-l^/ACTIONS=LINK^}
9457 to do binding and linking. When not combined with
9458 @option{^-c^/ACTIONS=COMPILE^}
9459 all the units in the closure of the main program must have been previously
9460 compiled and must be up to date. The root unit specified by @var{file_name}
9461 may be given without extension, with the source extension or, if no GNAT
9462 Project File is specified, with the ALI file extension.
9464 @item ^-c^/ACTIONS=COMPILE^
9465 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9466 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9467 is also specified. Do not perform linking, except if both
9468 @option{^-b^/ACTIONS=BIND^} and
9469 @option{^-l^/ACTIONS=LINK^} are also specified.
9470 If the root unit specified by @var{file_name} is not a main unit, this is the
9471 default. Otherwise @command{gnatmake} will attempt binding and linking
9472 unless all objects are up to date and the executable is more recent than
9476 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9477 Use a temporary mapping file. A mapping file is a way to communicate
9478 to the compiler two mappings: from unit names to file names (without
9479 any directory information) and from file names to path names (with
9480 full directory information). A mapping file can make the compiler's
9481 file searches faster, especially if there are many source directories,
9482 or the sources are read over a slow network connection. If
9483 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9484 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9485 is initially populated based on the project file. If
9486 @option{^-C^/MAPPING^} is used without
9487 @option{^-P^/PROJECT_FILE^},
9488 the mapping file is initially empty. Each invocation of the compiler
9489 will add any newly accessed sources to the mapping file.
9491 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9492 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9493 Use a specific mapping file. The file, specified as a path name (absolute or
9494 relative) by this switch, should already exist, otherwise the switch is
9495 ineffective. The specified mapping file will be communicated to the compiler.
9496 This switch is not compatible with a project file
9497 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9498 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9500 @item ^-d^/DISPLAY_PROGRESS^
9501 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9502 Display progress for each source, up to date or not, as a single line
9505 completed x out of y (zz%)
9508 If the file needs to be compiled this is displayed after the invocation of
9509 the compiler. These lines are displayed even in quiet output mode.
9511 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9512 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9513 Put all object files and ALI file in directory @var{dir}.
9514 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9515 and ALI files go in the current working directory.
9517 This switch cannot be used when using a project file.
9520 @cindex @option{-eI} (@command{gnatmake})
9521 Indicates that the main source is a multi-unit source and the rank of the unit
9522 in the source file is nnn. nnn needs to be a positive number and a valid
9523 index in the source. This switch cannot be used when @command{gnatmake} is
9524 invoked for several mains.
9528 @cindex @option{-eL} (@command{gnatmake})
9529 @cindex symbolic links
9530 Follow all symbolic links when processing project files.
9531 This should be used if your project uses symbolic links for files or
9532 directories, but is not needed in other cases.
9534 @cindex naming scheme
9535 This also assumes that no directory matches the naming scheme for files (for
9536 instance that you do not have a directory called "sources.ads" when using the
9537 default GNAT naming scheme).
9539 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9540 save a lot of system calls (several per source file and object file), which
9541 can result in a significant speed up to load and manipulate a project file,
9542 especially when using source files from a remote system.
9546 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9547 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9548 Output the commands for the compiler, the binder and the linker
9549 on ^standard output^SYS$OUTPUT^,
9550 instead of ^standard error^SYS$ERROR^.
9552 @item ^-f^/FORCE_COMPILE^
9553 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9554 Force recompilations. Recompile all sources, even though some object
9555 files may be up to date, but don't recompile predefined or GNAT internal
9556 files or locked files (files with a write-protected ALI file),
9557 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9559 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9560 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9561 When using project files, if some errors or warnings are detected during
9562 parsing and verbose mode is not in effect (no use of switch
9563 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9564 file, rather than its simple file name.
9567 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9568 Enable debugging. This switch is simply passed to the compiler and to the
9571 @item ^-i^/IN_PLACE^
9572 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9573 In normal mode, @command{gnatmake} compiles all object files and ALI files
9574 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9575 then instead object files and ALI files that already exist are overwritten
9576 in place. This means that once a large project is organized into separate
9577 directories in the desired manner, then @command{gnatmake} will automatically
9578 maintain and update this organization. If no ALI files are found on the
9579 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9580 the new object and ALI files are created in the
9581 directory containing the source being compiled. If another organization
9582 is desired, where objects and sources are kept in different directories,
9583 a useful technique is to create dummy ALI files in the desired directories.
9584 When detecting such a dummy file, @command{gnatmake} will be forced to
9585 recompile the corresponding source file, and it will be put the resulting
9586 object and ALI files in the directory where it found the dummy file.
9588 @item ^-j^/PROCESSES=^@var{n}
9589 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9590 @cindex Parallel make
9591 Use @var{n} processes to carry out the (re)compilations. On a
9592 multiprocessor machine compilations will occur in parallel. In the
9593 event of compilation errors, messages from various compilations might
9594 get interspersed (but @command{gnatmake} will give you the full ordered
9595 list of failing compiles at the end). If this is problematic, rerun
9596 the make process with n set to 1 to get a clean list of messages.
9598 @item ^-k^/CONTINUE_ON_ERROR^
9599 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9600 Keep going. Continue as much as possible after a compilation error. To
9601 ease the programmer's task in case of compilation errors, the list of
9602 sources for which the compile fails is given when @command{gnatmake}
9605 If @command{gnatmake} is invoked with several @file{file_names} and with this
9606 switch, if there are compilation errors when building an executable,
9607 @command{gnatmake} will not attempt to build the following executables.
9609 @item ^-l^/ACTIONS=LINK^
9610 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9611 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9612 and linking. Linking will not be performed if combined with
9613 @option{^-c^/ACTIONS=COMPILE^}
9614 but not with @option{^-b^/ACTIONS=BIND^}.
9615 When not combined with @option{^-b^/ACTIONS=BIND^}
9616 all the units in the closure of the main program must have been previously
9617 compiled and must be up to date, and the main program needs to have been bound.
9618 The root unit specified by @var{file_name}
9619 may be given without extension, with the source extension or, if no GNAT
9620 Project File is specified, with the ALI file extension.
9622 @item ^-m^/MINIMAL_RECOMPILATION^
9623 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9624 Specify that the minimum necessary amount of recompilations
9625 be performed. In this mode @command{gnatmake} ignores time
9626 stamp differences when the only
9627 modifications to a source file consist in adding/removing comments,
9628 empty lines, spaces or tabs. This means that if you have changed the
9629 comments in a source file or have simply reformatted it, using this
9630 switch will tell @command{gnatmake} not to recompile files that depend on it
9631 (provided other sources on which these files depend have undergone no
9632 semantic modifications). Note that the debugging information may be
9633 out of date with respect to the sources if the @option{-m} switch causes
9634 a compilation to be switched, so the use of this switch represents a
9635 trade-off between compilation time and accurate debugging information.
9637 @item ^-M^/DEPENDENCIES_LIST^
9638 @cindex Dependencies, producing list
9639 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9640 Check if all objects are up to date. If they are, output the object
9641 dependences to @file{stdout} in a form that can be directly exploited in
9642 a @file{Makefile}. By default, each source file is prefixed with its
9643 (relative or absolute) directory name. This name is whatever you
9644 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9645 and @option{^-I^/SEARCH^} switches. If you use
9646 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9647 @option{^-q^/QUIET^}
9648 (see below), only the source file names,
9649 without relative paths, are output. If you just specify the
9650 @option{^-M^/DEPENDENCIES_LIST^}
9651 switch, dependencies of the GNAT internal system files are omitted. This
9652 is typically what you want. If you also specify
9653 the @option{^-a^/ALL_FILES^} switch,
9654 dependencies of the GNAT internal files are also listed. Note that
9655 dependencies of the objects in external Ada libraries (see switch
9656 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9659 @item ^-n^/DO_OBJECT_CHECK^
9660 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9661 Don't compile, bind, or link. Checks if all objects are up to date.
9662 If they are not, the full name of the first file that needs to be
9663 recompiled is printed.
9664 Repeated use of this option, followed by compiling the indicated source
9665 file, will eventually result in recompiling all required units.
9667 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9668 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9669 Output executable name. The name of the final executable program will be
9670 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9671 name for the executable will be the name of the input file in appropriate form
9672 for an executable file on the host system.
9674 This switch cannot be used when invoking @command{gnatmake} with several
9677 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9678 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9679 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9680 automatically missing object directories, library directories and exec
9683 @item ^-P^/PROJECT_FILE=^@var{project}
9684 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9685 Use project file @var{project}. Only one such switch can be used.
9686 @xref{gnatmake and Project Files}.
9689 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9690 Quiet. When this flag is not set, the commands carried out by
9691 @command{gnatmake} are displayed.
9693 @item ^-s^/SWITCH_CHECK/^
9694 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9695 Recompile if compiler switches have changed since last compilation.
9696 All compiler switches but -I and -o are taken into account in the
9698 orders between different ``first letter'' switches are ignored, but
9699 orders between same switches are taken into account. For example,
9700 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9701 is equivalent to @option{-O -g}.
9703 This switch is recommended when Integrated Preprocessing is used.
9706 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9707 Unique. Recompile at most the main files. It implies -c. Combined with
9708 -f, it is equivalent to calling the compiler directly. Note that using
9709 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9710 (@pxref{Project Files and Main Subprograms}).
9712 @item ^-U^/ALL_PROJECTS^
9713 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9714 When used without a project file or with one or several mains on the command
9715 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9716 on the command line, all sources of all project files are checked and compiled
9717 if not up to date, and libraries are rebuilt, if necessary.
9720 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9721 Verbose. Display the reason for all recompilations @command{gnatmake}
9722 decides are necessary, with the highest verbosity level.
9724 @item ^-vl^/LOW_VERBOSITY^
9725 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9726 Verbosity level Low. Display fewer lines than in verbosity Medium.
9728 @item ^-vm^/MEDIUM_VERBOSITY^
9729 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9730 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9732 @item ^-vh^/HIGH_VERBOSITY^
9733 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9734 Verbosity level High. Equivalent to ^-v^/REASONS^.
9736 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9737 Indicate the verbosity of the parsing of GNAT project files.
9738 @xref{Switches Related to Project Files}.
9740 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9741 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9742 Indicate that sources that are not part of any Project File may be compiled.
9743 Normally, when using Project Files, only sources that are part of a Project
9744 File may be compile. When this switch is used, a source outside of all Project
9745 Files may be compiled. The ALI file and the object file will be put in the
9746 object directory of the main Project. The compilation switches used will only
9747 be those specified on the command line. Even when
9748 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9749 command line need to be sources of a project file.
9751 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9752 Indicate that external variable @var{name} has the value @var{value}.
9753 The Project Manager will use this value for occurrences of
9754 @code{external(name)} when parsing the project file.
9755 @xref{Switches Related to Project Files}.
9758 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9759 No main subprogram. Bind and link the program even if the unit name
9760 given on the command line is a package name. The resulting executable
9761 will execute the elaboration routines of the package and its closure,
9762 then the finalization routines.
9767 @item @command{gcc} @asis{switches}
9769 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9770 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9773 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9774 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9775 automatically treated as a compiler switch, and passed on to all
9776 compilations that are carried out.
9781 Source and library search path switches:
9785 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9786 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9787 When looking for source files also look in directory @var{dir}.
9788 The order in which source files search is undertaken is
9789 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9791 @item ^-aL^/SKIP_MISSING=^@var{dir}
9792 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9793 Consider @var{dir} as being an externally provided Ada library.
9794 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9795 files have been located in directory @var{dir}. This allows you to have
9796 missing bodies for the units in @var{dir} and to ignore out of date bodies
9797 for the same units. You still need to specify
9798 the location of the specs for these units by using the switches
9799 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9800 or @option{^-I^/SEARCH=^@var{dir}}.
9801 Note: this switch is provided for compatibility with previous versions
9802 of @command{gnatmake}. The easier method of causing standard libraries
9803 to be excluded from consideration is to write-protect the corresponding
9806 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9807 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9808 When searching for library and object files, look in directory
9809 @var{dir}. The order in which library files are searched is described in
9810 @ref{Search Paths for gnatbind}.
9812 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9813 @cindex Search paths, for @command{gnatmake}
9814 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9815 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9816 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9818 @item ^-I^/SEARCH=^@var{dir}
9819 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9820 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9821 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9823 @item ^-I-^/NOCURRENT_DIRECTORY^
9824 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9825 @cindex Source files, suppressing search
9826 Do not look for source files in the directory containing the source
9827 file named in the command line.
9828 Do not look for ALI or object files in the directory
9829 where @command{gnatmake} was invoked.
9831 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9832 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9833 @cindex Linker libraries
9834 Add directory @var{dir} to the list of directories in which the linker
9835 will search for libraries. This is equivalent to
9836 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9838 Furthermore, under Windows, the sources pointed to by the libraries path
9839 set in the registry are not searched for.
9843 @cindex @option{-nostdinc} (@command{gnatmake})
9844 Do not look for source files in the system default directory.
9847 @cindex @option{-nostdlib} (@command{gnatmake})
9848 Do not look for library files in the system default directory.
9850 @item --RTS=@var{rts-path}
9851 @cindex @option{--RTS} (@command{gnatmake})
9852 Specifies the default location of the runtime library. GNAT looks for the
9854 in the following directories, and stops as soon as a valid runtime is found
9855 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9856 @file{ada_object_path} present):
9859 @item <current directory>/$rts_path
9861 @item <default-search-dir>/$rts_path
9863 @item <default-search-dir>/rts-$rts_path
9867 The selected path is handled like a normal RTS path.
9871 @node Mode Switches for gnatmake
9872 @section Mode Switches for @command{gnatmake}
9875 The mode switches (referred to as @code{mode_switches}) allow the
9876 inclusion of switches that are to be passed to the compiler itself, the
9877 binder or the linker. The effect of a mode switch is to cause all
9878 subsequent switches up to the end of the switch list, or up to the next
9879 mode switch, to be interpreted as switches to be passed on to the
9880 designated component of GNAT.
9884 @item -cargs @var{switches}
9885 @cindex @option{-cargs} (@command{gnatmake})
9886 Compiler switches. Here @var{switches} is a list of switches
9887 that are valid switches for @command{gcc}. They will be passed on to
9888 all compile steps performed by @command{gnatmake}.
9890 @item -bargs @var{switches}
9891 @cindex @option{-bargs} (@command{gnatmake})
9892 Binder switches. Here @var{switches} is a list of switches
9893 that are valid switches for @code{gnatbind}. They will be passed on to
9894 all bind steps performed by @command{gnatmake}.
9896 @item -largs @var{switches}
9897 @cindex @option{-largs} (@command{gnatmake})
9898 Linker switches. Here @var{switches} is a list of switches
9899 that are valid switches for @command{gnatlink}. They will be passed on to
9900 all link steps performed by @command{gnatmake}.
9902 @item -margs @var{switches}
9903 @cindex @option{-margs} (@command{gnatmake})
9904 Make switches. The switches are directly interpreted by @command{gnatmake},
9905 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9909 @node Notes on the Command Line
9910 @section Notes on the Command Line
9913 This section contains some additional useful notes on the operation
9914 of the @command{gnatmake} command.
9918 @cindex Recompilation, by @command{gnatmake}
9919 If @command{gnatmake} finds no ALI files, it recompiles the main program
9920 and all other units required by the main program.
9921 This means that @command{gnatmake}
9922 can be used for the initial compile, as well as during subsequent steps of
9923 the development cycle.
9926 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9927 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9928 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9932 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9933 is used to specify both source and
9934 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9935 instead if you just want to specify
9936 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9937 if you want to specify library paths
9941 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9942 This may conveniently be used to exclude standard libraries from
9943 consideration and in particular it means that the use of the
9944 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9945 unless @option{^-a^/ALL_FILES^} is also specified.
9948 @command{gnatmake} has been designed to make the use of Ada libraries
9949 particularly convenient. Assume you have an Ada library organized
9950 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9951 of your Ada compilation units,
9952 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9953 specs of these units, but no bodies. Then to compile a unit
9954 stored in @code{main.adb}, which uses this Ada library you would just type
9958 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9961 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9962 /SKIP_MISSING=@i{[OBJ_DIR]} main
9967 Using @command{gnatmake} along with the
9968 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9969 switch provides a mechanism for avoiding unnecessary recompilations. Using
9971 you can update the comments/format of your
9972 source files without having to recompile everything. Note, however, that
9973 adding or deleting lines in a source files may render its debugging
9974 info obsolete. If the file in question is a spec, the impact is rather
9975 limited, as that debugging info will only be useful during the
9976 elaboration phase of your program. For bodies the impact can be more
9977 significant. In all events, your debugger will warn you if a source file
9978 is more recent than the corresponding object, and alert you to the fact
9979 that the debugging information may be out of date.
9982 @node How gnatmake Works
9983 @section How @command{gnatmake} Works
9986 Generally @command{gnatmake} automatically performs all necessary
9987 recompilations and you don't need to worry about how it works. However,
9988 it may be useful to have some basic understanding of the @command{gnatmake}
9989 approach and in particular to understand how it uses the results of
9990 previous compilations without incorrectly depending on them.
9992 First a definition: an object file is considered @dfn{up to date} if the
9993 corresponding ALI file exists and if all the source files listed in the
9994 dependency section of this ALI file have time stamps matching those in
9995 the ALI file. This means that neither the source file itself nor any
9996 files that it depends on have been modified, and hence there is no need
9997 to recompile this file.
9999 @command{gnatmake} works by first checking if the specified main unit is up
10000 to date. If so, no compilations are required for the main unit. If not,
10001 @command{gnatmake} compiles the main program to build a new ALI file that
10002 reflects the latest sources. Then the ALI file of the main unit is
10003 examined to find all the source files on which the main program depends,
10004 and @command{gnatmake} recursively applies the above procedure on all these
10007 This process ensures that @command{gnatmake} only trusts the dependencies
10008 in an existing ALI file if they are known to be correct. Otherwise it
10009 always recompiles to determine a new, guaranteed accurate set of
10010 dependencies. As a result the program is compiled ``upside down'' from what may
10011 be more familiar as the required order of compilation in some other Ada
10012 systems. In particular, clients are compiled before the units on which
10013 they depend. The ability of GNAT to compile in any order is critical in
10014 allowing an order of compilation to be chosen that guarantees that
10015 @command{gnatmake} will recompute a correct set of new dependencies if
10018 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10019 imported by several of the executables, it will be recompiled at most once.
10021 Note: when using non-standard naming conventions
10022 (@pxref{Using Other File Names}), changing through a configuration pragmas
10023 file the version of a source and invoking @command{gnatmake} to recompile may
10024 have no effect, if the previous version of the source is still accessible
10025 by @command{gnatmake}. It may be necessary to use the switch
10026 ^-f^/FORCE_COMPILE^.
10028 @node Examples of gnatmake Usage
10029 @section Examples of @command{gnatmake} Usage
10032 @item gnatmake hello.adb
10033 Compile all files necessary to bind and link the main program
10034 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10035 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10037 @item gnatmake main1 main2 main3
10038 Compile all files necessary to bind and link the main programs
10039 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10040 (containing unit @code{Main2}) and @file{main3.adb}
10041 (containing unit @code{Main3}) and bind and link the resulting object files
10042 to generate three executable files @file{^main1^MAIN1.EXE^},
10043 @file{^main2^MAIN2.EXE^}
10044 and @file{^main3^MAIN3.EXE^}.
10047 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10051 @item gnatmake Main_Unit /QUIET
10052 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10053 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10055 Compile all files necessary to bind and link the main program unit
10056 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10057 be done with optimization level 2 and the order of elaboration will be
10058 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10059 displaying commands it is executing.
10062 @c *************************
10063 @node Improving Performance
10064 @chapter Improving Performance
10065 @cindex Improving performance
10068 This chapter presents several topics related to program performance.
10069 It first describes some of the tradeoffs that need to be considered
10070 and some of the techniques for making your program run faster.
10071 It then documents the @command{gnatelim} tool and unused subprogram/data
10072 elimination feature, which can reduce the size of program executables.
10074 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
10075 driver (see @ref{The GNAT Driver and Project Files}).
10079 * Performance Considerations::
10080 * Text_IO Suggestions::
10081 * Reducing Size of Ada Executables with gnatelim::
10082 * Reducing Size of Executables with unused subprogram/data elimination::
10086 @c *****************************
10087 @node Performance Considerations
10088 @section Performance Considerations
10091 The GNAT system provides a number of options that allow a trade-off
10096 performance of the generated code
10099 speed of compilation
10102 minimization of dependences and recompilation
10105 the degree of run-time checking.
10109 The defaults (if no options are selected) aim at improving the speed
10110 of compilation and minimizing dependences, at the expense of performance
10111 of the generated code:
10118 no inlining of subprogram calls
10121 all run-time checks enabled except overflow and elaboration checks
10125 These options are suitable for most program development purposes. This
10126 chapter describes how you can modify these choices, and also provides
10127 some guidelines on debugging optimized code.
10130 * Controlling Run-Time Checks::
10131 * Use of Restrictions::
10132 * Optimization Levels::
10133 * Debugging Optimized Code::
10134 * Inlining of Subprograms::
10135 * Other Optimization Switches::
10136 * Optimization and Strict Aliasing::
10139 * Coverage Analysis::
10143 @node Controlling Run-Time Checks
10144 @subsection Controlling Run-Time Checks
10147 By default, GNAT generates all run-time checks, except integer overflow
10148 checks, stack overflow checks, and checks for access before elaboration on
10149 subprogram calls. The latter are not required in default mode, because all
10150 necessary checking is done at compile time.
10151 @cindex @option{-gnatp} (@command{gcc})
10152 @cindex @option{-gnato} (@command{gcc})
10153 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10154 be modified. @xref{Run-Time Checks}.
10156 Our experience is that the default is suitable for most development
10159 We treat integer overflow specially because these
10160 are quite expensive and in our experience are not as important as other
10161 run-time checks in the development process. Note that division by zero
10162 is not considered an overflow check, and divide by zero checks are
10163 generated where required by default.
10165 Elaboration checks are off by default, and also not needed by default, since
10166 GNAT uses a static elaboration analysis approach that avoids the need for
10167 run-time checking. This manual contains a full chapter discussing the issue
10168 of elaboration checks, and if the default is not satisfactory for your use,
10169 you should read this chapter.
10171 For validity checks, the minimal checks required by the Ada Reference
10172 Manual (for case statements and assignments to array elements) are on
10173 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10174 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10175 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10176 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10177 are also suppressed entirely if @option{-gnatp} is used.
10179 @cindex Overflow checks
10180 @cindex Checks, overflow
10183 @cindex pragma Suppress
10184 @cindex pragma Unsuppress
10185 Note that the setting of the switches controls the default setting of
10186 the checks. They may be modified using either @code{pragma Suppress} (to
10187 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10188 checks) in the program source.
10190 @node Use of Restrictions
10191 @subsection Use of Restrictions
10194 The use of pragma Restrictions allows you to control which features are
10195 permitted in your program. Apart from the obvious point that if you avoid
10196 relatively expensive features like finalization (enforceable by the use
10197 of pragma Restrictions (No_Finalization), the use of this pragma does not
10198 affect the generated code in most cases.
10200 One notable exception to this rule is that the possibility of task abort
10201 results in some distributed overhead, particularly if finalization or
10202 exception handlers are used. The reason is that certain sections of code
10203 have to be marked as non-abortable.
10205 If you use neither the @code{abort} statement, nor asynchronous transfer
10206 of control (@code{select @dots{} then abort}), then this distributed overhead
10207 is removed, which may have a general positive effect in improving
10208 overall performance. Especially code involving frequent use of tasking
10209 constructs and controlled types will show much improved performance.
10210 The relevant restrictions pragmas are
10212 @smallexample @c ada
10213 pragma Restrictions (No_Abort_Statements);
10214 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10218 It is recommended that these restriction pragmas be used if possible. Note
10219 that this also means that you can write code without worrying about the
10220 possibility of an immediate abort at any point.
10222 @node Optimization Levels
10223 @subsection Optimization Levels
10224 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10227 Without any optimization ^option,^qualifier,^
10228 the compiler's goal is to reduce the cost of
10229 compilation and to make debugging produce the expected results.
10230 Statements are independent: if you stop the program with a breakpoint between
10231 statements, you can then assign a new value to any variable or change
10232 the program counter to any other statement in the subprogram and get exactly
10233 the results you would expect from the source code.
10235 Turning on optimization makes the compiler attempt to improve the
10236 performance and/or code size at the expense of compilation time and
10237 possibly the ability to debug the program.
10239 If you use multiple
10240 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10241 the last such option is the one that is effective.
10244 The default is optimization off. This results in the fastest compile
10245 times, but GNAT makes absolutely no attempt to optimize, and the
10246 generated programs are considerably larger and slower than when
10247 optimization is enabled. You can use the
10249 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10250 @option{-O2}, @option{-O3}, and @option{-Os})
10253 @code{OPTIMIZE} qualifier
10255 to @command{gcc} to control the optimization level:
10258 @item ^-O0^/OPTIMIZE=NONE^
10259 No optimization (the default);
10260 generates unoptimized code but has
10261 the fastest compilation time.
10263 Note that many other compilers do fairly extensive optimization
10264 even if ``no optimization'' is specified. With gcc, it is
10265 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10266 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10267 really does mean no optimization at all. This difference between
10268 gcc and other compilers should be kept in mind when doing
10269 performance comparisons.
10271 @item ^-O1^/OPTIMIZE=SOME^
10272 Moderate optimization;
10273 optimizes reasonably well but does not
10274 degrade compilation time significantly.
10276 @item ^-O2^/OPTIMIZE=ALL^
10278 @itemx /OPTIMIZE=DEVELOPMENT
10281 generates highly optimized code and has
10282 the slowest compilation time.
10284 @item ^-O3^/OPTIMIZE=INLINING^
10285 Full optimization as in @option{-O2};
10286 also uses more aggressive automatic inlining of subprograms within a unit
10287 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10289 @item ^-Os^/OPTIMIZE=SPACE^
10290 Optimize space usage (code and data) of resulting program.
10294 Higher optimization levels perform more global transformations on the
10295 program and apply more expensive analysis algorithms in order to generate
10296 faster and more compact code. The price in compilation time, and the
10297 resulting improvement in execution time,
10298 both depend on the particular application and the hardware environment.
10299 You should experiment to find the best level for your application.
10301 Since the precise set of optimizations done at each level will vary from
10302 release to release (and sometime from target to target), it is best to think
10303 of the optimization settings in general terms.
10304 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10305 the GNU Compiler Collection (GCC)}, for details about
10306 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10307 individually enable or disable specific optimizations.
10309 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10310 been tested extensively at all optimization levels. There are some bugs
10311 which appear only with optimization turned on, but there have also been
10312 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10313 level of optimization does not improve the reliability of the code
10314 generator, which in practice is highly reliable at all optimization
10317 Note regarding the use of @option{-O3}: The use of this optimization level
10318 is generally discouraged with GNAT, since it often results in larger
10319 executables which may run more slowly. See further discussion of this point
10320 in @ref{Inlining of Subprograms}.
10322 @node Debugging Optimized Code
10323 @subsection Debugging Optimized Code
10324 @cindex Debugging optimized code
10325 @cindex Optimization and debugging
10328 Although it is possible to do a reasonable amount of debugging at
10330 nonzero optimization levels,
10331 the higher the level the more likely that
10334 @option{/OPTIMIZE} settings other than @code{NONE},
10335 such settings will make it more likely that
10337 source-level constructs will have been eliminated by optimization.
10338 For example, if a loop is strength-reduced, the loop
10339 control variable may be completely eliminated and thus cannot be
10340 displayed in the debugger.
10341 This can only happen at @option{-O2} or @option{-O3}.
10342 Explicit temporary variables that you code might be eliminated at
10343 ^level^setting^ @option{-O1} or higher.
10345 The use of the @option{^-g^/DEBUG^} switch,
10346 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10347 which is needed for source-level debugging,
10348 affects the size of the program executable on disk,
10349 and indeed the debugging information can be quite large.
10350 However, it has no effect on the generated code (and thus does not
10351 degrade performance)
10353 Since the compiler generates debugging tables for a compilation unit before
10354 it performs optimizations, the optimizing transformations may invalidate some
10355 of the debugging data. You therefore need to anticipate certain
10356 anomalous situations that may arise while debugging optimized code.
10357 These are the most common cases:
10361 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10363 the PC bouncing back and forth in the code. This may result from any of
10364 the following optimizations:
10368 @i{Common subexpression elimination:} using a single instance of code for a
10369 quantity that the source computes several times. As a result you
10370 may not be able to stop on what looks like a statement.
10373 @i{Invariant code motion:} moving an expression that does not change within a
10374 loop, to the beginning of the loop.
10377 @i{Instruction scheduling:} moving instructions so as to
10378 overlap loads and stores (typically) with other code, or in
10379 general to move computations of values closer to their uses. Often
10380 this causes you to pass an assignment statement without the assignment
10381 happening and then later bounce back to the statement when the
10382 value is actually needed. Placing a breakpoint on a line of code
10383 and then stepping over it may, therefore, not always cause all the
10384 expected side-effects.
10388 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10389 two identical pieces of code are merged and the program counter suddenly
10390 jumps to a statement that is not supposed to be executed, simply because
10391 it (and the code following) translates to the same thing as the code
10392 that @emph{was} supposed to be executed. This effect is typically seen in
10393 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10394 a @code{break} in a C @code{^switch^switch^} statement.
10397 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10398 There are various reasons for this effect:
10402 In a subprogram prologue, a parameter may not yet have been moved to its
10406 A variable may be dead, and its register re-used. This is
10407 probably the most common cause.
10410 As mentioned above, the assignment of a value to a variable may
10414 A variable may be eliminated entirely by value propagation or
10415 other means. In this case, GCC may incorrectly generate debugging
10416 information for the variable
10420 In general, when an unexpected value appears for a local variable or parameter
10421 you should first ascertain if that value was actually computed by
10422 your program, as opposed to being incorrectly reported by the debugger.
10424 array elements in an object designated by an access value
10425 are generally less of a problem, once you have ascertained that the access
10427 Typically, this means checking variables in the preceding code and in the
10428 calling subprogram to verify that the value observed is explainable from other
10429 values (one must apply the procedure recursively to those
10430 other values); or re-running the code and stopping a little earlier
10431 (perhaps before the call) and stepping to better see how the variable obtained
10432 the value in question; or continuing to step @emph{from} the point of the
10433 strange value to see if code motion had simply moved the variable's
10438 In light of such anomalies, a recommended technique is to use @option{-O0}
10439 early in the software development cycle, when extensive debugging capabilities
10440 are most needed, and then move to @option{-O1} and later @option{-O2} as
10441 the debugger becomes less critical.
10442 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10443 a release management issue.
10445 Note that if you use @option{-g} you can then use the @command{strip} program
10446 on the resulting executable,
10447 which removes both debugging information and global symbols.
10450 @node Inlining of Subprograms
10451 @subsection Inlining of Subprograms
10454 A call to a subprogram in the current unit is inlined if all the
10455 following conditions are met:
10459 The optimization level is at least @option{-O1}.
10462 The called subprogram is suitable for inlining: It must be small enough
10463 and not contain something that @command{gcc} cannot support in inlined
10467 @cindex pragma Inline
10469 Any one of the following applies: @code{pragma Inline} is applied to the
10470 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10471 subprogram is local to the unit and called once from within it; the
10472 subprogram is small and optimization level @option{-O2} is specified;
10473 optimization level @option{-O3}) is specified.
10477 Calls to subprograms in @code{with}'ed units are normally not inlined.
10478 To achieve actual inlining (that is, replacement of the call by the code
10479 in the body of the subprogram), the following conditions must all be true.
10483 The optimization level is at least @option{-O1}.
10486 The called subprogram is suitable for inlining: It must be small enough
10487 and not contain something that @command{gcc} cannot support in inlined
10491 The call appears in a body (not in a package spec).
10494 There is a @code{pragma Inline} for the subprogram.
10497 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10500 Even if all these conditions are met, it may not be possible for
10501 the compiler to inline the call, due to the length of the body,
10502 or features in the body that make it impossible for the compiler
10503 to do the inlining.
10505 Note that specifying the @option{-gnatn} switch causes additional
10506 compilation dependencies. Consider the following:
10508 @smallexample @c ada
10528 With the default behavior (no @option{-gnatn} switch specified), the
10529 compilation of the @code{Main} procedure depends only on its own source,
10530 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10531 means that editing the body of @code{R} does not require recompiling
10534 On the other hand, the call @code{R.Q} is not inlined under these
10535 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10536 is compiled, the call will be inlined if the body of @code{Q} is small
10537 enough, but now @code{Main} depends on the body of @code{R} in
10538 @file{r.adb} as well as on the spec. This means that if this body is edited,
10539 the main program must be recompiled. Note that this extra dependency
10540 occurs whether or not the call is in fact inlined by @command{gcc}.
10542 The use of front end inlining with @option{-gnatN} generates similar
10543 additional dependencies.
10545 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10546 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10547 can be used to prevent
10548 all inlining. This switch overrides all other conditions and ensures
10549 that no inlining occurs. The extra dependences resulting from
10550 @option{-gnatn} will still be active, even if
10551 this switch is used to suppress the resulting inlining actions.
10553 @cindex @option{-fno-inline-functions} (@command{gcc})
10554 Note: The @option{-fno-inline-functions} switch can be used to prevent
10555 automatic inlining of subprograms if @option{-O3} is used.
10557 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10558 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10559 automatic inlining of small subprograms if @option{-O2} is used.
10561 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10562 Note: The @option{-fno-inline-functions-called-once} switch
10563 can be used to prevent inlining of subprograms local to the unit
10564 and called once from within it if @option{-O1} is used.
10566 Note regarding the use of @option{-O3}: There is no difference in inlining
10567 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10568 pragma @code{Inline} assuming the use of @option{-gnatn}
10569 or @option{-gnatN} (the switches that activate inlining). If you have used
10570 pragma @code{Inline} in appropriate cases, then it is usually much better
10571 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10572 in this case only has the effect of inlining subprograms you did not
10573 think should be inlined. We often find that the use of @option{-O3} slows
10574 down code by performing excessive inlining, leading to increased instruction
10575 cache pressure from the increased code size. So the bottom line here is
10576 that you should not automatically assume that @option{-O3} is better than
10577 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10578 it actually improves performance.
10580 @node Other Optimization Switches
10581 @subsection Other Optimization Switches
10582 @cindex Optimization Switches
10584 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10585 @command{gcc} optimization switches are potentially usable. These switches
10586 have not been extensively tested with GNAT but can generally be expected
10587 to work. Examples of switches in this category are
10588 @option{-funroll-loops} and
10589 the various target-specific @option{-m} options (in particular, it has been
10590 observed that @option{-march=pentium4} can significantly improve performance
10591 on appropriate machines). For full details of these switches, see
10592 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10593 the GNU Compiler Collection (GCC)}.
10595 @node Optimization and Strict Aliasing
10596 @subsection Optimization and Strict Aliasing
10598 @cindex Strict Aliasing
10599 @cindex No_Strict_Aliasing
10602 The strong typing capabilities of Ada allow an optimizer to generate
10603 efficient code in situations where other languages would be forced to
10604 make worst case assumptions preventing such optimizations. Consider
10605 the following example:
10607 @smallexample @c ada
10610 type Int1 is new Integer;
10611 type Int2 is new Integer;
10612 type Int1A is access Int1;
10613 type Int2A is access Int2;
10620 for J in Data'Range loop
10621 if Data (J) = Int1V.all then
10622 Int2V.all := Int2V.all + 1;
10631 In this example, since the variable @code{Int1V} can only access objects
10632 of type @code{Int1}, and @code{Int2V} can only access objects of type
10633 @code{Int2}, there is no possibility that the assignment to
10634 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10635 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10636 for all iterations of the loop and avoid the extra memory reference
10637 required to dereference it each time through the loop.
10639 This kind of optimization, called strict aliasing analysis, is
10640 triggered by specifying an optimization level of @option{-O2} or
10641 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10642 when access values are involved.
10644 However, although this optimization is always correct in terms of
10645 the formal semantics of the Ada Reference Manual, difficulties can
10646 arise if features like @code{Unchecked_Conversion} are used to break
10647 the typing system. Consider the following complete program example:
10649 @smallexample @c ada
10652 type int1 is new integer;
10653 type int2 is new integer;
10654 type a1 is access int1;
10655 type a2 is access int2;
10660 function to_a2 (Input : a1) return a2;
10663 with Unchecked_Conversion;
10665 function to_a2 (Input : a1) return a2 is
10667 new Unchecked_Conversion (a1, a2);
10669 return to_a2u (Input);
10675 with Text_IO; use Text_IO;
10677 v1 : a1 := new int1;
10678 v2 : a2 := to_a2 (v1);
10682 put_line (int1'image (v1.all));
10688 This program prints out 0 in @option{-O0} or @option{-O1}
10689 mode, but it prints out 1 in @option{-O2} mode. That's
10690 because in strict aliasing mode, the compiler can and
10691 does assume that the assignment to @code{v2.all} could not
10692 affect the value of @code{v1.all}, since different types
10695 This behavior is not a case of non-conformance with the standard, since
10696 the Ada RM specifies that an unchecked conversion where the resulting
10697 bit pattern is not a correct value of the target type can result in an
10698 abnormal value and attempting to reference an abnormal value makes the
10699 execution of a program erroneous. That's the case here since the result
10700 does not point to an object of type @code{int2}. This means that the
10701 effect is entirely unpredictable.
10703 However, although that explanation may satisfy a language
10704 lawyer, in practice an applications programmer expects an
10705 unchecked conversion involving pointers to create true
10706 aliases and the behavior of printing 1 seems plain wrong.
10707 In this case, the strict aliasing optimization is unwelcome.
10709 Indeed the compiler recognizes this possibility, and the
10710 unchecked conversion generates a warning:
10713 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10714 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10715 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10719 Unfortunately the problem is recognized when compiling the body of
10720 package @code{p2}, but the actual "bad" code is generated while
10721 compiling the body of @code{m} and this latter compilation does not see
10722 the suspicious @code{Unchecked_Conversion}.
10724 As implied by the warning message, there are approaches you can use to
10725 avoid the unwanted strict aliasing optimization in a case like this.
10727 One possibility is to simply avoid the use of @option{-O2}, but
10728 that is a bit drastic, since it throws away a number of useful
10729 optimizations that do not involve strict aliasing assumptions.
10731 A less drastic approach is to compile the program using the
10732 option @option{-fno-strict-aliasing}. Actually it is only the
10733 unit containing the dereferencing of the suspicious pointer
10734 that needs to be compiled. So in this case, if we compile
10735 unit @code{m} with this switch, then we get the expected
10736 value of zero printed. Analyzing which units might need
10737 the switch can be painful, so a more reasonable approach
10738 is to compile the entire program with options @option{-O2}
10739 and @option{-fno-strict-aliasing}. If the performance is
10740 satisfactory with this combination of options, then the
10741 advantage is that the entire issue of possible "wrong"
10742 optimization due to strict aliasing is avoided.
10744 To avoid the use of compiler switches, the configuration
10745 pragma @code{No_Strict_Aliasing} with no parameters may be
10746 used to specify that for all access types, the strict
10747 aliasing optimization should be suppressed.
10749 However, these approaches are still overkill, in that they causes
10750 all manipulations of all access values to be deoptimized. A more
10751 refined approach is to concentrate attention on the specific
10752 access type identified as problematic.
10754 First, if a careful analysis of uses of the pointer shows
10755 that there are no possible problematic references, then
10756 the warning can be suppressed by bracketing the
10757 instantiation of @code{Unchecked_Conversion} to turn
10760 @smallexample @c ada
10761 pragma Warnings (Off);
10763 new Unchecked_Conversion (a1, a2);
10764 pragma Warnings (On);
10768 Of course that approach is not appropriate for this particular
10769 example, since indeed there is a problematic reference. In this
10770 case we can take one of two other approaches.
10772 The first possibility is to move the instantiation of unchecked
10773 conversion to the unit in which the type is declared. In
10774 this example, we would move the instantiation of
10775 @code{Unchecked_Conversion} from the body of package
10776 @code{p2} to the spec of package @code{p1}. Now the
10777 warning disappears. That's because any use of the
10778 access type knows there is a suspicious unchecked
10779 conversion, and the strict aliasing optimization
10780 is automatically suppressed for the type.
10782 If it is not practical to move the unchecked conversion to the same unit
10783 in which the destination access type is declared (perhaps because the
10784 source type is not visible in that unit), you may use pragma
10785 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10786 same declarative sequence as the declaration of the access type:
10788 @smallexample @c ada
10789 type a2 is access int2;
10790 pragma No_Strict_Aliasing (a2);
10794 Here again, the compiler now knows that the strict aliasing optimization
10795 should be suppressed for any reference to type @code{a2} and the
10796 expected behavior is obtained.
10798 Finally, note that although the compiler can generate warnings for
10799 simple cases of unchecked conversions, there are tricker and more
10800 indirect ways of creating type incorrect aliases which the compiler
10801 cannot detect. Examples are the use of address overlays and unchecked
10802 conversions involving composite types containing access types as
10803 components. In such cases, no warnings are generated, but there can
10804 still be aliasing problems. One safe coding practice is to forbid the
10805 use of address clauses for type overlaying, and to allow unchecked
10806 conversion only for primitive types. This is not really a significant
10807 restriction since any possible desired effect can be achieved by
10808 unchecked conversion of access values.
10810 The aliasing analysis done in strict aliasing mode can certainly
10811 have significant benefits. We have seen cases of large scale
10812 application code where the time is increased by up to 5% by turning
10813 this optimization off. If you have code that includes significant
10814 usage of unchecked conversion, you might want to just stick with
10815 @option{-O1} and avoid the entire issue. If you get adequate
10816 performance at this level of optimization level, that's probably
10817 the safest approach. If tests show that you really need higher
10818 levels of optimization, then you can experiment with @option{-O2}
10819 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10820 has on size and speed of the code. If you really need to use
10821 @option{-O2} with strict aliasing in effect, then you should
10822 review any uses of unchecked conversion of access types,
10823 particularly if you are getting the warnings described above.
10826 @node Coverage Analysis
10827 @subsection Coverage Analysis
10830 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10831 the user to determine the distribution of execution time across a program,
10832 @pxref{Profiling} for details of usage.
10836 @node Text_IO Suggestions
10837 @section @code{Text_IO} Suggestions
10838 @cindex @code{Text_IO} and performance
10841 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10842 the requirement of maintaining page and line counts. If performance
10843 is critical, a recommendation is to use @code{Stream_IO} instead of
10844 @code{Text_IO} for volume output, since this package has less overhead.
10846 If @code{Text_IO} must be used, note that by default output to the standard
10847 output and standard error files is unbuffered (this provides better
10848 behavior when output statements are used for debugging, or if the
10849 progress of a program is observed by tracking the output, e.g. by
10850 using the Unix @command{tail -f} command to watch redirected output.
10852 If you are generating large volumes of output with @code{Text_IO} and
10853 performance is an important factor, use a designated file instead
10854 of the standard output file, or change the standard output file to
10855 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10859 @node Reducing Size of Ada Executables with gnatelim
10860 @section Reducing Size of Ada Executables with @code{gnatelim}
10864 This section describes @command{gnatelim}, a tool which detects unused
10865 subprograms and helps the compiler to create a smaller executable for your
10870 * Running gnatelim::
10871 * Processing Precompiled Libraries::
10872 * Correcting the List of Eliminate Pragmas::
10873 * Making Your Executables Smaller::
10874 * Summary of the gnatelim Usage Cycle::
10877 @node About gnatelim
10878 @subsection About @code{gnatelim}
10881 When a program shares a set of Ada
10882 packages with other programs, it may happen that this program uses
10883 only a fraction of the subprograms defined in these packages. The code
10884 created for these unused subprograms increases the size of the executable.
10886 @code{gnatelim} tracks unused subprograms in an Ada program and
10887 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10888 subprograms that are declared but never called. By placing the list of
10889 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10890 recompiling your program, you may decrease the size of its executable,
10891 because the compiler will not generate the code for 'eliminated' subprograms.
10892 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10893 information about this pragma.
10895 @code{gnatelim} needs as its input data the name of the main subprogram.
10897 If a set of source files is specified as @code{gnatelim} arguments, it
10898 treats these files as a complete set of sources making up a program to
10899 analyse, and analyses only these sources.
10901 After a full successful build of the main subprogram @code{gnatelim} can be
10902 called without specifying sources to analyse, in this case it computes
10903 the source closure of the main unit from the @file{ALI} files.
10905 The following command will create the set of @file{ALI} files needed for
10909 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10912 Note that @code{gnatelim} does not need object files.
10914 @node Running gnatelim
10915 @subsection Running @code{gnatelim}
10918 @code{gnatelim} has the following command-line interface:
10921 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10925 @var{main_unit_name} should be a name of a source file that contains the main
10926 subprogram of a program (partition).
10928 Each @var{filename} is the name (including the extension) of a source
10929 file to process. ``Wildcards'' are allowed, and
10930 the file name may contain path information.
10932 @samp{@var{gcc_switches}} is a list of switches for
10933 @command{gcc}. They will be passed on to all compiler invocations made by
10934 @command{gnatelim} to generate the ASIS trees. Here you can provide
10935 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10936 use the @option{-gnatec} switch to set the configuration file,
10937 use the @option{-gnat05} switch if sources should be compiled in
10940 @code{gnatelim} has the following switches:
10944 @item ^-files^/FILES^=@var{filename}
10945 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10946 Take the argument source files from the specified file. This file should be an
10947 ordinary text file containing file names separated by spaces or
10948 line breaks. You can use this switch more than once in the same call to
10949 @command{gnatelim}. You also can combine this switch with
10950 an explicit list of files.
10953 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10954 Duplicate all the output sent to @file{stderr} into a log file. The log file
10955 is named @file{gnatelim.log} and is located in the current directory.
10957 @item ^-log^/LOGFILE^=@var{filename}
10958 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10959 Duplicate all the output sent to @file{stderr} into a specified log file.
10961 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10962 @item ^--no-elim-dispatch^/NO_DISPATCH^
10963 Do not generate pragmas for dispatching operations.
10965 @item ^--ignore^/IGNORE^=@var{filename}
10966 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
10967 Do not generate pragmas for subprograms declared in the sources
10968 listed in a specified file
10970 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10971 @item ^-o^/OUTPUT^=@var{report_file}
10972 Put @command{gnatelim} output into a specified file. If this file already exists,
10973 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10977 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10978 Quiet mode: by default @code{gnatelim} outputs to the standard error
10979 stream the number of program units left to be processed. This option turns
10982 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10984 Print out execution time.
10986 @item ^-v^/VERBOSE^
10987 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10988 Verbose mode: @code{gnatelim} version information is printed as Ada
10989 comments to the standard output stream. Also, in addition to the number of
10990 program units left @code{gnatelim} will output the name of the current unit
10993 @item ^-wq^/WARNINGS=QUIET^
10994 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10995 Quiet warning mode - some warnings are suppressed. In particular warnings that
10996 indicate that the analysed set of sources is incomplete to make up a
10997 partition and that some subprogram bodies are missing are not generated.
11000 @node Processing Precompiled Libraries
11001 @subsection Processing Precompiled Libraries
11004 If some program uses a precompiled Ada library, it can be processed by
11005 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11006 Eliminate pragma for a subprogram if the body of this subprogram has not
11007 been analysed, this is a typical case for subprograms from precompiled
11008 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11009 warnings about missing source files and non-analyzed subprogram bodies
11010 that can be generated when processing precompiled Ada libraries.
11012 @node Correcting the List of Eliminate Pragmas
11013 @subsection Correcting the List of Eliminate Pragmas
11016 In some rare cases @code{gnatelim} may try to eliminate
11017 subprograms that are actually called in the program. In this case, the
11018 compiler will generate an error message of the form:
11021 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11025 You will need to manually remove the wrong @code{Eliminate} pragmas from
11026 the configuration file indicated in the error message. You should recompile
11027 your program from scratch after that, because you need a consistent
11028 configuration file(s) during the entire compilation.
11030 @node Making Your Executables Smaller
11031 @subsection Making Your Executables Smaller
11034 In order to get a smaller executable for your program you now have to
11035 recompile the program completely with the configuration file containing
11036 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11037 @file{gnat.adc} file located in your current directory, just do:
11040 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11044 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11045 recompile everything
11046 with the set of pragmas @code{Eliminate} that you have obtained with
11047 @command{gnatelim}).
11049 Be aware that the set of @code{Eliminate} pragmas is specific to each
11050 program. It is not recommended to merge sets of @code{Eliminate}
11051 pragmas created for different programs in one configuration file.
11053 @node Summary of the gnatelim Usage Cycle
11054 @subsection Summary of the @code{gnatelim} Usage Cycle
11057 Here is a quick summary of the steps to be taken in order to reduce
11058 the size of your executables with @code{gnatelim}. You may use
11059 other GNAT options to control the optimization level,
11060 to produce the debugging information, to set search path, etc.
11064 Create a complete set of @file{ALI} files (if the program has not been
11068 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11072 Generate a list of @code{Eliminate} pragmas in default configuration file
11073 @file{gnat.adc} in the current directory
11076 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11079 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11084 Recompile the application
11087 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11092 @node Reducing Size of Executables with unused subprogram/data elimination
11093 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11094 @findex unused subprogram/data elimination
11097 This section describes how you can eliminate unused subprograms and data from
11098 your executable just by setting options at compilation time.
11101 * About unused subprogram/data elimination::
11102 * Compilation options::
11103 * Example of unused subprogram/data elimination::
11106 @node About unused subprogram/data elimination
11107 @subsection About unused subprogram/data elimination
11110 By default, an executable contains all code and data of its composing objects
11111 (directly linked or coming from statically linked libraries), even data or code
11112 never used by this executable.
11114 This feature will allow you to eliminate such unused code from your
11115 executable, making it smaller (in disk and in memory).
11117 This functionality is available on all Linux platforms except for the IA-64
11118 architecture and on all cross platforms using the ELF binary file format.
11119 In both cases GNU binutils version 2.16 or later are required to enable it.
11121 @node Compilation options
11122 @subsection Compilation options
11125 The operation of eliminating the unused code and data from the final executable
11126 is directly performed by the linker.
11128 In order to do this, it has to work with objects compiled with the
11130 @option{-ffunction-sections} @option{-fdata-sections}.
11131 @cindex @option{-ffunction-sections} (@command{gcc})
11132 @cindex @option{-fdata-sections} (@command{gcc})
11133 These options are usable with C and Ada files.
11134 They will place respectively each
11135 function or data in a separate section in the resulting object file.
11137 Once the objects and static libraries are created with these options, the
11138 linker can perform the dead code elimination. You can do this by setting
11139 the @option{-Wl,--gc-sections} option to gcc command or in the
11140 @option{-largs} section of @command{gnatmake}. This will perform a
11141 garbage collection of code and data never referenced.
11143 If the linker performs a partial link (@option{-r} ld linker option), then you
11144 will need to provide one or several entry point using the
11145 @option{-e} / @option{--entry} ld option.
11147 Note that objects compiled without the @option{-ffunction-sections} and
11148 @option{-fdata-sections} options can still be linked with the executable.
11149 However, no dead code elimination will be performed on those objects (they will
11152 The GNAT static library is now compiled with -ffunction-sections and
11153 -fdata-sections on some platforms. This allows you to eliminate the unused code
11154 and data of the GNAT library from your executable.
11156 @node Example of unused subprogram/data elimination
11157 @subsection Example of unused subprogram/data elimination
11160 Here is a simple example:
11162 @smallexample @c ada
11171 Used_Data : Integer;
11172 Unused_Data : Integer;
11174 procedure Used (Data : Integer);
11175 procedure Unused (Data : Integer);
11178 package body Aux is
11179 procedure Used (Data : Integer) is
11184 procedure Unused (Data : Integer) is
11186 Unused_Data := Data;
11192 @code{Unused} and @code{Unused_Data} are never referenced in this code
11193 excerpt, and hence they may be safely removed from the final executable.
11198 $ nm test | grep used
11199 020015f0 T aux__unused
11200 02005d88 B aux__unused_data
11201 020015cc T aux__used
11202 02005d84 B aux__used_data
11204 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11205 -largs -Wl,--gc-sections
11207 $ nm test | grep used
11208 02005350 T aux__used
11209 0201ffe0 B aux__used_data
11213 It can be observed that the procedure @code{Unused} and the object
11214 @code{Unused_Data} are removed by the linker when using the
11215 appropriate options.
11217 @c ********************************
11218 @node Renaming Files Using gnatchop
11219 @chapter Renaming Files Using @code{gnatchop}
11223 This chapter discusses how to handle files with multiple units by using
11224 the @code{gnatchop} utility. This utility is also useful in renaming
11225 files to meet the standard GNAT default file naming conventions.
11228 * Handling Files with Multiple Units::
11229 * Operating gnatchop in Compilation Mode::
11230 * Command Line for gnatchop::
11231 * Switches for gnatchop::
11232 * Examples of gnatchop Usage::
11235 @node Handling Files with Multiple Units
11236 @section Handling Files with Multiple Units
11239 The basic compilation model of GNAT requires that a file submitted to the
11240 compiler have only one unit and there be a strict correspondence
11241 between the file name and the unit name.
11243 The @code{gnatchop} utility allows both of these rules to be relaxed,
11244 allowing GNAT to process files which contain multiple compilation units
11245 and files with arbitrary file names. @code{gnatchop}
11246 reads the specified file and generates one or more output files,
11247 containing one unit per file. The unit and the file name correspond,
11248 as required by GNAT.
11250 If you want to permanently restructure a set of ``foreign'' files so that
11251 they match the GNAT rules, and do the remaining development using the
11252 GNAT structure, you can simply use @command{gnatchop} once, generate the
11253 new set of files and work with them from that point on.
11255 Alternatively, if you want to keep your files in the ``foreign'' format,
11256 perhaps to maintain compatibility with some other Ada compilation
11257 system, you can set up a procedure where you use @command{gnatchop} each
11258 time you compile, regarding the source files that it writes as temporary
11259 files that you throw away.
11261 Note that if your file containing multiple units starts with a byte order
11262 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11263 will each start with a copy of this BOM, meaning that they can be compiled
11264 automatically in UTF-8 mode without needing to specify an explicit encoding.
11266 @node Operating gnatchop in Compilation Mode
11267 @section Operating gnatchop in Compilation Mode
11270 The basic function of @code{gnatchop} is to take a file with multiple units
11271 and split it into separate files. The boundary between files is reasonably
11272 clear, except for the issue of comments and pragmas. In default mode, the
11273 rule is that any pragmas between units belong to the previous unit, except
11274 that configuration pragmas always belong to the following unit. Any comments
11275 belong to the following unit. These rules
11276 almost always result in the right choice of
11277 the split point without needing to mark it explicitly and most users will
11278 find this default to be what they want. In this default mode it is incorrect to
11279 submit a file containing only configuration pragmas, or one that ends in
11280 configuration pragmas, to @code{gnatchop}.
11282 However, using a special option to activate ``compilation mode'',
11284 can perform another function, which is to provide exactly the semantics
11285 required by the RM for handling of configuration pragmas in a compilation.
11286 In the absence of configuration pragmas (at the main file level), this
11287 option has no effect, but it causes such configuration pragmas to be handled
11288 in a quite different manner.
11290 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11291 only configuration pragmas, then this file is appended to the
11292 @file{gnat.adc} file in the current directory. This behavior provides
11293 the required behavior described in the RM for the actions to be taken
11294 on submitting such a file to the compiler, namely that these pragmas
11295 should apply to all subsequent compilations in the same compilation
11296 environment. Using GNAT, the current directory, possibly containing a
11297 @file{gnat.adc} file is the representation
11298 of a compilation environment. For more information on the
11299 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11301 Second, in compilation mode, if @code{gnatchop}
11302 is given a file that starts with
11303 configuration pragmas, and contains one or more units, then these
11304 configuration pragmas are prepended to each of the chopped files. This
11305 behavior provides the required behavior described in the RM for the
11306 actions to be taken on compiling such a file, namely that the pragmas
11307 apply to all units in the compilation, but not to subsequently compiled
11310 Finally, if configuration pragmas appear between units, they are appended
11311 to the previous unit. This results in the previous unit being illegal,
11312 since the compiler does not accept configuration pragmas that follow
11313 a unit. This provides the required RM behavior that forbids configuration
11314 pragmas other than those preceding the first compilation unit of a
11317 For most purposes, @code{gnatchop} will be used in default mode. The
11318 compilation mode described above is used only if you need exactly
11319 accurate behavior with respect to compilations, and you have files
11320 that contain multiple units and configuration pragmas. In this
11321 circumstance the use of @code{gnatchop} with the compilation mode
11322 switch provides the required behavior, and is for example the mode
11323 in which GNAT processes the ACVC tests.
11325 @node Command Line for gnatchop
11326 @section Command Line for @code{gnatchop}
11329 The @code{gnatchop} command has the form:
11332 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11333 @c @ovar{directory}
11334 @c Expanding @ovar macro inline (explanation in macro def comments)
11335 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11336 @r{[}@var{directory}@r{]}
11340 The only required argument is the file name of the file to be chopped.
11341 There are no restrictions on the form of this file name. The file itself
11342 contains one or more Ada units, in normal GNAT format, concatenated
11343 together. As shown, more than one file may be presented to be chopped.
11345 When run in default mode, @code{gnatchop} generates one output file in
11346 the current directory for each unit in each of the files.
11348 @var{directory}, if specified, gives the name of the directory to which
11349 the output files will be written. If it is not specified, all files are
11350 written to the current directory.
11352 For example, given a
11353 file called @file{hellofiles} containing
11355 @smallexample @c ada
11360 with Text_IO; use Text_IO;
11363 Put_Line ("Hello");
11373 $ gnatchop ^hellofiles^HELLOFILES.^
11377 generates two files in the current directory, one called
11378 @file{hello.ads} containing the single line that is the procedure spec,
11379 and the other called @file{hello.adb} containing the remaining text. The
11380 original file is not affected. The generated files can be compiled in
11384 When gnatchop is invoked on a file that is empty or that contains only empty
11385 lines and/or comments, gnatchop will not fail, but will not produce any
11388 For example, given a
11389 file called @file{toto.txt} containing
11391 @smallexample @c ada
11403 $ gnatchop ^toto.txt^TOT.TXT^
11407 will not produce any new file and will result in the following warnings:
11410 toto.txt:1:01: warning: empty file, contains no compilation units
11411 no compilation units found
11412 no source files written
11415 @node Switches for gnatchop
11416 @section Switches for @code{gnatchop}
11419 @command{gnatchop} recognizes the following switches:
11425 @cindex @option{--version} @command{gnatchop}
11426 Display Copyright and version, then exit disregarding all other options.
11429 @cindex @option{--help} @command{gnatchop}
11430 If @option{--version} was not used, display usage, then exit disregarding
11433 @item ^-c^/COMPILATION^
11434 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11435 Causes @code{gnatchop} to operate in compilation mode, in which
11436 configuration pragmas are handled according to strict RM rules. See
11437 previous section for a full description of this mode.
11440 @item -gnat@var{xxx}
11441 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11442 used to parse the given file. Not all @var{xxx} options make sense,
11443 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11444 process a source file that uses Latin-2 coding for identifiers.
11448 Causes @code{gnatchop} to generate a brief help summary to the standard
11449 output file showing usage information.
11451 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11452 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11453 Limit generated file names to the specified number @code{mm}
11455 This is useful if the
11456 resulting set of files is required to be interoperable with systems
11457 which limit the length of file names.
11459 If no value is given, or
11460 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11461 a default of 39, suitable for OpenVMS Alpha
11462 Systems, is assumed
11465 No space is allowed between the @option{-k} and the numeric value. The numeric
11466 value may be omitted in which case a default of @option{-k8},
11468 with DOS-like file systems, is used. If no @option{-k} switch
11470 there is no limit on the length of file names.
11473 @item ^-p^/PRESERVE^
11474 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11475 Causes the file ^modification^creation^ time stamp of the input file to be
11476 preserved and used for the time stamp of the output file(s). This may be
11477 useful for preserving coherency of time stamps in an environment where
11478 @code{gnatchop} is used as part of a standard build process.
11481 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11482 Causes output of informational messages indicating the set of generated
11483 files to be suppressed. Warnings and error messages are unaffected.
11485 @item ^-r^/REFERENCE^
11486 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11487 @findex Source_Reference
11488 Generate @code{Source_Reference} pragmas. Use this switch if the output
11489 files are regarded as temporary and development is to be done in terms
11490 of the original unchopped file. This switch causes
11491 @code{Source_Reference} pragmas to be inserted into each of the
11492 generated files to refers back to the original file name and line number.
11493 The result is that all error messages refer back to the original
11495 In addition, the debugging information placed into the object file (when
11496 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11498 also refers back to this original file so that tools like profilers and
11499 debuggers will give information in terms of the original unchopped file.
11501 If the original file to be chopped itself contains
11502 a @code{Source_Reference}
11503 pragma referencing a third file, then gnatchop respects
11504 this pragma, and the generated @code{Source_Reference} pragmas
11505 in the chopped file refer to the original file, with appropriate
11506 line numbers. This is particularly useful when @code{gnatchop}
11507 is used in conjunction with @code{gnatprep} to compile files that
11508 contain preprocessing statements and multiple units.
11510 @item ^-v^/VERBOSE^
11511 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11512 Causes @code{gnatchop} to operate in verbose mode. The version
11513 number and copyright notice are output, as well as exact copies of
11514 the gnat1 commands spawned to obtain the chop control information.
11516 @item ^-w^/OVERWRITE^
11517 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11518 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11519 fatal error if there is already a file with the same name as a
11520 file it would otherwise output, in other words if the files to be
11521 chopped contain duplicated units. This switch bypasses this
11522 check, and causes all but the last instance of such duplicated
11523 units to be skipped.
11526 @item --GCC=@var{xxxx}
11527 @cindex @option{--GCC=} (@code{gnatchop})
11528 Specify the path of the GNAT parser to be used. When this switch is used,
11529 no attempt is made to add the prefix to the GNAT parser executable.
11533 @node Examples of gnatchop Usage
11534 @section Examples of @code{gnatchop} Usage
11538 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11541 @item gnatchop -w hello_s.ada prerelease/files
11544 Chops the source file @file{hello_s.ada}. The output files will be
11545 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11547 files with matching names in that directory (no files in the current
11548 directory are modified).
11550 @item gnatchop ^archive^ARCHIVE.^
11551 Chops the source file @file{^archive^ARCHIVE.^}
11552 into the current directory. One
11553 useful application of @code{gnatchop} is in sending sets of sources
11554 around, for example in email messages. The required sources are simply
11555 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11557 @command{gnatchop} is used at the other end to reconstitute the original
11560 @item gnatchop file1 file2 file3 direc
11561 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11562 the resulting files in the directory @file{direc}. Note that if any units
11563 occur more than once anywhere within this set of files, an error message
11564 is generated, and no files are written. To override this check, use the
11565 @option{^-w^/OVERWRITE^} switch,
11566 in which case the last occurrence in the last file will
11567 be the one that is output, and earlier duplicate occurrences for a given
11568 unit will be skipped.
11571 @node Configuration Pragmas
11572 @chapter Configuration Pragmas
11573 @cindex Configuration pragmas
11574 @cindex Pragmas, configuration
11577 Configuration pragmas include those pragmas described as
11578 such in the Ada Reference Manual, as well as
11579 implementation-dependent pragmas that are configuration pragmas.
11580 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11581 for details on these additional GNAT-specific configuration pragmas.
11582 Most notably, the pragma @code{Source_File_Name}, which allows
11583 specifying non-default names for source files, is a configuration
11584 pragma. The following is a complete list of configuration pragmas
11585 recognized by GNAT:
11595 Assume_No_Invalid_Values
11600 Compile_Time_Warning
11602 Component_Alignment
11603 Convention_Identifier
11606 Default_Storage_Pool
11612 External_Name_Casing
11615 Float_Representation
11628 Priority_Specific_Dispatching
11631 Propagate_Exceptions
11634 Restricted_Run_Time
11636 Restrictions_Warnings
11638 Short_Circuit_And_Or
11640 Source_File_Name_Project
11643 Suppress_Exception_Locations
11644 Task_Dispatching_Policy
11650 Wide_Character_Encoding
11655 * Handling of Configuration Pragmas::
11656 * The Configuration Pragmas Files::
11659 @node Handling of Configuration Pragmas
11660 @section Handling of Configuration Pragmas
11662 Configuration pragmas may either appear at the start of a compilation
11663 unit, in which case they apply only to that unit, or they may apply to
11664 all compilations performed in a given compilation environment.
11666 GNAT also provides the @code{gnatchop} utility to provide an automatic
11667 way to handle configuration pragmas following the semantics for
11668 compilations (that is, files with multiple units), described in the RM.
11669 See @ref{Operating gnatchop in Compilation Mode} for details.
11670 However, for most purposes, it will be more convenient to edit the
11671 @file{gnat.adc} file that contains configuration pragmas directly,
11672 as described in the following section.
11674 @node The Configuration Pragmas Files
11675 @section The Configuration Pragmas Files
11676 @cindex @file{gnat.adc}
11679 In GNAT a compilation environment is defined by the current
11680 directory at the time that a compile command is given. This current
11681 directory is searched for a file whose name is @file{gnat.adc}. If
11682 this file is present, it is expected to contain one or more
11683 configuration pragmas that will be applied to the current compilation.
11684 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11687 Configuration pragmas may be entered into the @file{gnat.adc} file
11688 either by running @code{gnatchop} on a source file that consists only of
11689 configuration pragmas, or more conveniently by
11690 direct editing of the @file{gnat.adc} file, which is a standard format
11693 In addition to @file{gnat.adc}, additional files containing configuration
11694 pragmas may be applied to the current compilation using the switch
11695 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11696 contains only configuration pragmas. These configuration pragmas are
11697 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11698 is present and switch @option{-gnatA} is not used).
11700 It is allowed to specify several switches @option{-gnatec}, all of which
11701 will be taken into account.
11703 If you are using project file, a separate mechanism is provided using
11704 project attributes, see @ref{Specifying Configuration Pragmas} for more
11708 Of special interest to GNAT OpenVMS Alpha is the following
11709 configuration pragma:
11711 @smallexample @c ada
11713 pragma Extend_System (Aux_DEC);
11718 In the presence of this pragma, GNAT adds to the definition of the
11719 predefined package SYSTEM all the additional types and subprograms that are
11720 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11723 @node Handling Arbitrary File Naming Conventions Using gnatname
11724 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11725 @cindex Arbitrary File Naming Conventions
11728 * Arbitrary File Naming Conventions::
11729 * Running gnatname::
11730 * Switches for gnatname::
11731 * Examples of gnatname Usage::
11734 @node Arbitrary File Naming Conventions
11735 @section Arbitrary File Naming Conventions
11738 The GNAT compiler must be able to know the source file name of a compilation
11739 unit. When using the standard GNAT default file naming conventions
11740 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11741 does not need additional information.
11744 When the source file names do not follow the standard GNAT default file naming
11745 conventions, the GNAT compiler must be given additional information through
11746 a configuration pragmas file (@pxref{Configuration Pragmas})
11748 When the non-standard file naming conventions are well-defined,
11749 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11750 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11751 if the file naming conventions are irregular or arbitrary, a number
11752 of pragma @code{Source_File_Name} for individual compilation units
11754 To help maintain the correspondence between compilation unit names and
11755 source file names within the compiler,
11756 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11759 @node Running gnatname
11760 @section Running @code{gnatname}
11763 The usual form of the @code{gnatname} command is
11766 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11767 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11768 @c Expanding @ovar macro inline (explanation in macro def comments)
11769 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11770 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11774 All of the arguments are optional. If invoked without any argument,
11775 @code{gnatname} will display its usage.
11778 When used with at least one naming pattern, @code{gnatname} will attempt to
11779 find all the compilation units in files that follow at least one of the
11780 naming patterns. To find these compilation units,
11781 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11785 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11786 Each Naming Pattern is enclosed between double quotes (or single
11787 quotes on Windows).
11788 A Naming Pattern is a regular expression similar to the wildcard patterns
11789 used in file names by the Unix shells or the DOS prompt.
11792 @code{gnatname} may be called with several sections of directories/patterns.
11793 Sections are separated by switch @code{--and}. In each section, there must be
11794 at least one pattern. If no directory is specified in a section, the current
11795 directory (or the project directory is @code{-P} is used) is implied.
11796 The options other that the directory switches and the patterns apply globally
11797 even if they are in different sections.
11800 Examples of Naming Patterns are
11809 For a more complete description of the syntax of Naming Patterns,
11810 see the second kind of regular expressions described in @file{g-regexp.ads}
11811 (the ``Glob'' regular expressions).
11814 When invoked with no switch @code{-P}, @code{gnatname} will create a
11815 configuration pragmas file @file{gnat.adc} in the current working directory,
11816 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11819 @node Switches for gnatname
11820 @section Switches for @code{gnatname}
11823 Switches for @code{gnatname} must precede any specified Naming Pattern.
11826 You may specify any of the following switches to @code{gnatname}:
11832 @cindex @option{--version} @command{gnatname}
11833 Display Copyright and version, then exit disregarding all other options.
11836 @cindex @option{--help} @command{gnatname}
11837 If @option{--version} was not used, display usage, then exit disregarding
11841 Start another section of directories/patterns.
11843 @item ^-c^/CONFIG_FILE=^@file{file}
11844 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11845 Create a configuration pragmas file @file{file} (instead of the default
11848 There may be zero, one or more space between @option{-c} and
11851 @file{file} may include directory information. @file{file} must be
11852 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11853 When a switch @option{^-c^/CONFIG_FILE^} is
11854 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11856 @item ^-d^/SOURCE_DIRS=^@file{dir}
11857 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11858 Look for source files in directory @file{dir}. There may be zero, one or more
11859 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11860 When a switch @option{^-d^/SOURCE_DIRS^}
11861 is specified, the current working directory will not be searched for source
11862 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11863 or @option{^-D^/DIR_FILES^} switch.
11864 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11865 If @file{dir} is a relative path, it is relative to the directory of
11866 the configuration pragmas file specified with switch
11867 @option{^-c^/CONFIG_FILE^},
11868 or to the directory of the project file specified with switch
11869 @option{^-P^/PROJECT_FILE^} or,
11870 if neither switch @option{^-c^/CONFIG_FILE^}
11871 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11872 current working directory. The directory
11873 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11875 @item ^-D^/DIRS_FILE=^@file{file}
11876 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11877 Look for source files in all directories listed in text file @file{file}.
11878 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11880 @file{file} must be an existing, readable text file.
11881 Each nonempty line in @file{file} must be a directory.
11882 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11883 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11886 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11887 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11888 Foreign patterns. Using this switch, it is possible to add sources of languages
11889 other than Ada to the list of sources of a project file.
11890 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11893 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11896 will look for Ada units in all files with the @file{.ada} extension,
11897 and will add to the list of file for project @file{prj.gpr} the C files
11898 with extension @file{.^c^C^}.
11901 @cindex @option{^-h^/HELP^} (@code{gnatname})
11902 Output usage (help) information. The output is written to @file{stdout}.
11904 @item ^-P^/PROJECT_FILE=^@file{proj}
11905 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11906 Create or update project file @file{proj}. There may be zero, one or more space
11907 between @option{-P} and @file{proj}. @file{proj} may include directory
11908 information. @file{proj} must be writable.
11909 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11910 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11911 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11913 @item ^-v^/VERBOSE^
11914 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11915 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11916 This includes name of the file written, the name of the directories to search
11917 and, for each file in those directories whose name matches at least one of
11918 the Naming Patterns, an indication of whether the file contains a unit,
11919 and if so the name of the unit.
11921 @item ^-v -v^/VERBOSE /VERBOSE^
11922 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11923 Very Verbose mode. In addition to the output produced in verbose mode,
11924 for each file in the searched directories whose name matches none of
11925 the Naming Patterns, an indication is given that there is no match.
11927 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11928 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11929 Excluded patterns. Using this switch, it is possible to exclude some files
11930 that would match the name patterns. For example,
11932 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11935 will look for Ada units in all files with the @file{.ada} extension,
11936 except those whose names end with @file{_nt.ada}.
11940 @node Examples of gnatname Usage
11941 @section Examples of @code{gnatname} Usage
11945 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11951 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11956 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11957 and be writable. In addition, the directory
11958 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11959 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11962 Note the optional spaces after @option{-c} and @option{-d}.
11967 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11968 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11971 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11972 /EXCLUDED_PATTERN=*_nt_body.ada
11973 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11974 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11978 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11979 even in conjunction with one or several switches
11980 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11981 are used in this example.
11983 @c *****************************************
11984 @c * G N A T P r o j e c t M a n a g e r *
11985 @c *****************************************
11987 @c ------ macros for projects.texi
11988 @c These macros are needed when building the gprbuild documentation, but
11989 @c should have no effect in the gnat user's guide
11991 @macro CODESAMPLE{TXT}
11999 @macro PROJECTFILE{TXT}
12003 @c simulates a newline when in a @CODESAMPLE
12014 @macro TIPHTML{TXT}
12018 @macro IMPORTANT{TXT}
12033 @include projects.texi
12035 @c *****************************************
12036 @c * Cross-referencing tools
12037 @c *****************************************
12039 @node The Cross-Referencing Tools gnatxref and gnatfind
12040 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12045 The compiler generates cross-referencing information (unless
12046 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12047 This information indicates where in the source each entity is declared and
12048 referenced. Note that entities in package Standard are not included, but
12049 entities in all other predefined units are included in the output.
12051 Before using any of these two tools, you need to compile successfully your
12052 application, so that GNAT gets a chance to generate the cross-referencing
12055 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12056 information to provide the user with the capability to easily locate the
12057 declaration and references to an entity. These tools are quite similar,
12058 the difference being that @code{gnatfind} is intended for locating
12059 definitions and/or references to a specified entity or entities, whereas
12060 @code{gnatxref} is oriented to generating a full report of all
12063 To use these tools, you must not compile your application using the
12064 @option{-gnatx} switch on the @command{gnatmake} command line
12065 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12066 information will not be generated.
12068 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12069 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12072 * Switches for gnatxref::
12073 * Switches for gnatfind::
12074 * Project Files for gnatxref and gnatfind::
12075 * Regular Expressions in gnatfind and gnatxref::
12076 * Examples of gnatxref Usage::
12077 * Examples of gnatfind Usage::
12080 @node Switches for gnatxref
12081 @section @code{gnatxref} Switches
12084 The command invocation for @code{gnatxref} is:
12086 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12087 @c Expanding @ovar macro inline (explanation in macro def comments)
12088 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12097 identifies the source files for which a report is to be generated. The
12098 ``with''ed units will be processed too. You must provide at least one file.
12100 These file names are considered to be regular expressions, so for instance
12101 specifying @file{source*.adb} is the same as giving every file in the current
12102 directory whose name starts with @file{source} and whose extension is
12105 You shouldn't specify any directory name, just base names. @command{gnatxref}
12106 and @command{gnatfind} will be able to locate these files by themselves using
12107 the source path. If you specify directories, no result is produced.
12112 The switches can be:
12116 @cindex @option{--version} @command{gnatxref}
12117 Display Copyright and version, then exit disregarding all other options.
12120 @cindex @option{--help} @command{gnatxref}
12121 If @option{--version} was not used, display usage, then exit disregarding
12124 @item ^-a^/ALL_FILES^
12125 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12126 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12127 the read-only files found in the library search path. Otherwise, these files
12128 will be ignored. This option can be used to protect Gnat sources or your own
12129 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12130 much faster, and their output much smaller. Read-only here refers to access
12131 or permissions status in the file system for the current user.
12134 @cindex @option{-aIDIR} (@command{gnatxref})
12135 When looking for source files also look in directory DIR. The order in which
12136 source file search is undertaken is the same as for @command{gnatmake}.
12139 @cindex @option{-aODIR} (@command{gnatxref})
12140 When searching for library and object files, look in directory
12141 DIR. The order in which library files are searched is the same as for
12142 @command{gnatmake}.
12145 @cindex @option{-nostdinc} (@command{gnatxref})
12146 Do not look for sources in the system default directory.
12149 @cindex @option{-nostdlib} (@command{gnatxref})
12150 Do not look for library files in the system default directory.
12152 @item --ext=@var{extension}
12153 @cindex @option{--ext} (@command{gnatxref})
12154 Specify an alternate ali file extension. The default is @code{ali} and other
12155 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12156 switch. Note that if this switch overrides the default, which means that only
12157 the new extension will be considered.
12159 @item --RTS=@var{rts-path}
12160 @cindex @option{--RTS} (@command{gnatxref})
12161 Specifies the default location of the runtime library. Same meaning as the
12162 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12164 @item ^-d^/DERIVED_TYPES^
12165 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12166 If this switch is set @code{gnatxref} will output the parent type
12167 reference for each matching derived types.
12169 @item ^-f^/FULL_PATHNAME^
12170 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12171 If this switch is set, the output file names will be preceded by their
12172 directory (if the file was found in the search path). If this switch is
12173 not set, the directory will not be printed.
12175 @item ^-g^/IGNORE_LOCALS^
12176 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12177 If this switch is set, information is output only for library-level
12178 entities, ignoring local entities. The use of this switch may accelerate
12179 @code{gnatfind} and @code{gnatxref}.
12182 @cindex @option{-IDIR} (@command{gnatxref})
12183 Equivalent to @samp{-aODIR -aIDIR}.
12186 @cindex @option{-pFILE} (@command{gnatxref})
12187 Specify a project file to use @xref{GNAT Project Manager}.
12188 If you need to use the @file{.gpr}
12189 project files, you should use gnatxref through the GNAT driver
12190 (@command{gnat xref -Pproject}).
12192 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12193 project file in the current directory.
12195 If a project file is either specified or found by the tools, then the content
12196 of the source directory and object directory lines are added as if they
12197 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12198 and @samp{^-aO^OBJECT_SEARCH^}.
12200 Output only unused symbols. This may be really useful if you give your
12201 main compilation unit on the command line, as @code{gnatxref} will then
12202 display every unused entity and 'with'ed package.
12206 Instead of producing the default output, @code{gnatxref} will generate a
12207 @file{tags} file that can be used by vi. For examples how to use this
12208 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12209 to the standard output, thus you will have to redirect it to a file.
12215 All these switches may be in any order on the command line, and may even
12216 appear after the file names. They need not be separated by spaces, thus
12217 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12218 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12220 @node Switches for gnatfind
12221 @section @code{gnatfind} Switches
12224 The command line for @code{gnatfind} is:
12227 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12228 @c @r{[}@var{file1} @var{file2} @dots{}]
12229 @c Expanding @ovar macro inline (explanation in macro def comments)
12230 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12231 @r{[}@var{file1} @var{file2} @dots{}@r{]}
12239 An entity will be output only if it matches the regular expression found
12240 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12242 Omitting the pattern is equivalent to specifying @samp{*}, which
12243 will match any entity. Note that if you do not provide a pattern, you
12244 have to provide both a sourcefile and a line.
12246 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12247 for matching purposes. At the current time there is no support for
12248 8-bit codes other than Latin-1, or for wide characters in identifiers.
12251 @code{gnatfind} will look for references, bodies or declarations
12252 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12253 and column @var{column}. See @ref{Examples of gnatfind Usage}
12254 for syntax examples.
12257 is a decimal integer identifying the line number containing
12258 the reference to the entity (or entities) to be located.
12261 is a decimal integer identifying the exact location on the
12262 line of the first character of the identifier for the
12263 entity reference. Columns are numbered from 1.
12265 @item file1 file2 @dots{}
12266 The search will be restricted to these source files. If none are given, then
12267 the search will be done for every library file in the search path.
12268 These file must appear only after the pattern or sourcefile.
12270 These file names are considered to be regular expressions, so for instance
12271 specifying @file{source*.adb} is the same as giving every file in the current
12272 directory whose name starts with @file{source} and whose extension is
12275 The location of the spec of the entity will always be displayed, even if it
12276 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
12277 occurrences of the entity in the separate units of the ones given on the
12278 command line will also be displayed.
12280 Note that if you specify at least one file in this part, @code{gnatfind} may
12281 sometimes not be able to find the body of the subprograms.
12286 At least one of 'sourcefile' or 'pattern' has to be present on
12289 The following switches are available:
12293 @cindex @option{--version} @command{gnatfind}
12294 Display Copyright and version, then exit disregarding all other options.
12297 @cindex @option{--help} @command{gnatfind}
12298 If @option{--version} was not used, display usage, then exit disregarding
12301 @item ^-a^/ALL_FILES^
12302 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12303 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12304 the read-only files found in the library search path. Otherwise, these files
12305 will be ignored. This option can be used to protect Gnat sources or your own
12306 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12307 much faster, and their output much smaller. Read-only here refers to access
12308 or permission status in the file system for the current user.
12311 @cindex @option{-aIDIR} (@command{gnatfind})
12312 When looking for source files also look in directory DIR. The order in which
12313 source file search is undertaken is the same as for @command{gnatmake}.
12316 @cindex @option{-aODIR} (@command{gnatfind})
12317 When searching for library and object files, look in directory
12318 DIR. The order in which library files are searched is the same as for
12319 @command{gnatmake}.
12322 @cindex @option{-nostdinc} (@command{gnatfind})
12323 Do not look for sources in the system default directory.
12326 @cindex @option{-nostdlib} (@command{gnatfind})
12327 Do not look for library files in the system default directory.
12329 @item --ext=@var{extension}
12330 @cindex @option{--ext} (@command{gnatfind})
12331 Specify an alternate ali file extension. The default is @code{ali} and other
12332 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12333 switch. Note that if this switch overrides the default, which means that only
12334 the new extension will be considered.
12336 @item --RTS=@var{rts-path}
12337 @cindex @option{--RTS} (@command{gnatfind})
12338 Specifies the default location of the runtime library. Same meaning as the
12339 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12341 @item ^-d^/DERIVED_TYPE_INFORMATION^
12342 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12343 If this switch is set, then @code{gnatfind} will output the parent type
12344 reference for each matching derived types.
12346 @item ^-e^/EXPRESSIONS^
12347 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12348 By default, @code{gnatfind} accept the simple regular expression set for
12349 @samp{pattern}. If this switch is set, then the pattern will be
12350 considered as full Unix-style regular expression.
12352 @item ^-f^/FULL_PATHNAME^
12353 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12354 If this switch is set, the output file names will be preceded by their
12355 directory (if the file was found in the search path). If this switch is
12356 not set, the directory will not be printed.
12358 @item ^-g^/IGNORE_LOCALS^
12359 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12360 If this switch is set, information is output only for library-level
12361 entities, ignoring local entities. The use of this switch may accelerate
12362 @code{gnatfind} and @code{gnatxref}.
12365 @cindex @option{-IDIR} (@command{gnatfind})
12366 Equivalent to @samp{-aODIR -aIDIR}.
12369 @cindex @option{-pFILE} (@command{gnatfind})
12370 Specify a project file (@pxref{GNAT Project Manager}) to use.
12371 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12372 project file in the current directory.
12374 If a project file is either specified or found by the tools, then the content
12375 of the source directory and object directory lines are added as if they
12376 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12377 @samp{^-aO^/OBJECT_SEARCH^}.
12379 @item ^-r^/REFERENCES^
12380 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12381 By default, @code{gnatfind} will output only the information about the
12382 declaration, body or type completion of the entities. If this switch is
12383 set, the @code{gnatfind} will locate every reference to the entities in
12384 the files specified on the command line (or in every file in the search
12385 path if no file is given on the command line).
12387 @item ^-s^/PRINT_LINES^
12388 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12389 If this switch is set, then @code{gnatfind} will output the content
12390 of the Ada source file lines were the entity was found.
12392 @item ^-t^/TYPE_HIERARCHY^
12393 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12394 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12395 the specified type. It act like -d option but recursively from parent
12396 type to parent type. When this switch is set it is not possible to
12397 specify more than one file.
12402 All these switches may be in any order on the command line, and may even
12403 appear after the file names. They need not be separated by spaces, thus
12404 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12405 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12407 As stated previously, gnatfind will search in every directory in the
12408 search path. You can force it to look only in the current directory if
12409 you specify @code{*} at the end of the command line.
12411 @node Project Files for gnatxref and gnatfind
12412 @section Project Files for @command{gnatxref} and @command{gnatfind}
12415 Project files allow a programmer to specify how to compile its
12416 application, where to find sources, etc. These files are used
12418 primarily by GPS, but they can also be used
12421 @code{gnatxref} and @code{gnatfind}.
12423 A project file name must end with @file{.gpr}. If a single one is
12424 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12425 extract the information from it. If multiple project files are found, none of
12426 them is read, and you have to use the @samp{-p} switch to specify the one
12429 The following lines can be included, even though most of them have default
12430 values which can be used in most cases.
12431 The lines can be entered in any order in the file.
12432 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12433 each line. If you have multiple instances, only the last one is taken into
12438 [default: @code{"^./^[]^"}]
12439 specifies a directory where to look for source files. Multiple @code{src_dir}
12440 lines can be specified and they will be searched in the order they
12444 [default: @code{"^./^[]^"}]
12445 specifies a directory where to look for object and library files. Multiple
12446 @code{obj_dir} lines can be specified, and they will be searched in the order
12449 @item comp_opt=SWITCHES
12450 [default: @code{""}]
12451 creates a variable which can be referred to subsequently by using
12452 the @code{$@{comp_opt@}} notation. This is intended to store the default
12453 switches given to @command{gnatmake} and @command{gcc}.
12455 @item bind_opt=SWITCHES
12456 [default: @code{""}]
12457 creates a variable which can be referred to subsequently by using
12458 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12459 switches given to @command{gnatbind}.
12461 @item link_opt=SWITCHES
12462 [default: @code{""}]
12463 creates a variable which can be referred to subsequently by using
12464 the @samp{$@{link_opt@}} notation. This is intended to store the default
12465 switches given to @command{gnatlink}.
12467 @item main=EXECUTABLE
12468 [default: @code{""}]
12469 specifies the name of the executable for the application. This variable can
12470 be referred to in the following lines by using the @samp{$@{main@}} notation.
12473 @item comp_cmd=COMMAND
12474 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12477 @item comp_cmd=COMMAND
12478 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12480 specifies the command used to compile a single file in the application.
12483 @item make_cmd=COMMAND
12484 [default: @code{"GNAT MAKE $@{main@}
12485 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12486 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12487 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12490 @item make_cmd=COMMAND
12491 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12492 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12493 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12495 specifies the command used to recompile the whole application.
12497 @item run_cmd=COMMAND
12498 [default: @code{"$@{main@}"}]
12499 specifies the command used to run the application.
12501 @item debug_cmd=COMMAND
12502 [default: @code{"gdb $@{main@}"}]
12503 specifies the command used to debug the application
12508 @command{gnatxref} and @command{gnatfind} only take into account the
12509 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12511 @node Regular Expressions in gnatfind and gnatxref
12512 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12515 As specified in the section about @command{gnatfind}, the pattern can be a
12516 regular expression. Actually, there are to set of regular expressions
12517 which are recognized by the program:
12520 @item globbing patterns
12521 These are the most usual regular expression. They are the same that you
12522 generally used in a Unix shell command line, or in a DOS session.
12524 Here is a more formal grammar:
12531 term ::= elmt -- matches elmt
12532 term ::= elmt elmt -- concatenation (elmt then elmt)
12533 term ::= * -- any string of 0 or more characters
12534 term ::= ? -- matches any character
12535 term ::= [char @{char@}] -- matches any character listed
12536 term ::= [char - char] -- matches any character in range
12540 @item full regular expression
12541 The second set of regular expressions is much more powerful. This is the
12542 type of regular expressions recognized by utilities such a @file{grep}.
12544 The following is the form of a regular expression, expressed in Ada
12545 reference manual style BNF is as follows
12552 regexp ::= term @{| term@} -- alternation (term or term @dots{})
12554 term ::= item @{item@} -- concatenation (item then item)
12556 item ::= elmt -- match elmt
12557 item ::= elmt * -- zero or more elmt's
12558 item ::= elmt + -- one or more elmt's
12559 item ::= elmt ? -- matches elmt or nothing
12562 elmt ::= nschar -- matches given character
12563 elmt ::= [nschar @{nschar@}] -- matches any character listed
12564 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12565 elmt ::= [char - char] -- matches chars in given range
12566 elmt ::= \ char -- matches given character
12567 elmt ::= . -- matches any single character
12568 elmt ::= ( regexp ) -- parens used for grouping
12570 char ::= any character, including special characters
12571 nschar ::= any character except ()[].*+?^^^
12575 Following are a few examples:
12579 will match any of the two strings @samp{abcde} and @samp{fghi},
12582 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12583 @samp{abcccd}, and so on,
12586 will match any string which has only lowercase characters in it (and at
12587 least one character.
12592 @node Examples of gnatxref Usage
12593 @section Examples of @code{gnatxref} Usage
12595 @subsection General Usage
12598 For the following examples, we will consider the following units:
12600 @smallexample @c ada
12606 3: procedure Foo (B : in Integer);
12613 1: package body Main is
12614 2: procedure Foo (B : in Integer) is
12625 2: procedure Print (B : Integer);
12634 The first thing to do is to recompile your application (for instance, in
12635 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12636 the cross-referencing information.
12637 You can then issue any of the following commands:
12639 @item gnatxref main.adb
12640 @code{gnatxref} generates cross-reference information for main.adb
12641 and every unit 'with'ed by main.adb.
12643 The output would be:
12651 Decl: main.ads 3:20
12652 Body: main.adb 2:20
12653 Ref: main.adb 4:13 5:13 6:19
12656 Ref: main.adb 6:8 7:8
12666 Decl: main.ads 3:15
12667 Body: main.adb 2:15
12670 Body: main.adb 1:14
12673 Ref: main.adb 6:12 7:12
12677 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12678 its body is in main.adb, line 1, column 14 and is not referenced any where.
12680 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12681 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12683 @item gnatxref package1.adb package2.ads
12684 @code{gnatxref} will generates cross-reference information for
12685 package1.adb, package2.ads and any other package 'with'ed by any
12691 @subsection Using gnatxref with vi
12693 @code{gnatxref} can generate a tags file output, which can be used
12694 directly from @command{vi}. Note that the standard version of @command{vi}
12695 will not work properly with overloaded symbols. Consider using another
12696 free implementation of @command{vi}, such as @command{vim}.
12699 $ gnatxref -v gnatfind.adb > tags
12703 will generate the tags file for @code{gnatfind} itself (if the sources
12704 are in the search path!).
12706 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12707 (replacing @var{entity} by whatever you are looking for), and vi will
12708 display a new file with the corresponding declaration of entity.
12711 @node Examples of gnatfind Usage
12712 @section Examples of @code{gnatfind} Usage
12716 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12717 Find declarations for all entities xyz referenced at least once in
12718 main.adb. The references are search in every library file in the search
12721 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12724 The output will look like:
12726 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12727 ^directory/^[directory]^main.adb:24:10: xyz <= body
12728 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12732 that is to say, one of the entities xyz found in main.adb is declared at
12733 line 12 of main.ads (and its body is in main.adb), and another one is
12734 declared at line 45 of foo.ads
12736 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12737 This is the same command as the previous one, instead @code{gnatfind} will
12738 display the content of the Ada source file lines.
12740 The output will look like:
12743 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12745 ^directory/^[directory]^main.adb:24:10: xyz <= body
12747 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12752 This can make it easier to find exactly the location your are looking
12755 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12756 Find references to all entities containing an x that are
12757 referenced on line 123 of main.ads.
12758 The references will be searched only in main.ads and foo.adb.
12760 @item gnatfind main.ads:123
12761 Find declarations and bodies for all entities that are referenced on
12762 line 123 of main.ads.
12764 This is the same as @code{gnatfind "*":main.adb:123}.
12766 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12767 Find the declaration for the entity referenced at column 45 in
12768 line 123 of file main.adb in directory mydir. Note that it
12769 is usual to omit the identifier name when the column is given,
12770 since the column position identifies a unique reference.
12772 The column has to be the beginning of the identifier, and should not
12773 point to any character in the middle of the identifier.
12777 @c *********************************
12778 @node The GNAT Pretty-Printer gnatpp
12779 @chapter The GNAT Pretty-Printer @command{gnatpp}
12781 @cindex Pretty-Printer
12784 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12785 for source reformatting / pretty-printing.
12786 It takes an Ada source file as input and generates a reformatted
12788 You can specify various style directives via switches; e.g.,
12789 identifier case conventions, rules of indentation, and comment layout.
12791 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12792 tree for the input source and thus requires the input to be syntactically and
12793 semantically legal.
12794 If this condition is not met, @command{gnatpp} will terminate with an
12795 error message; no output file will be generated.
12797 If the source files presented to @command{gnatpp} contain
12798 preprocessing directives, then the output file will
12799 correspond to the generated source after all
12800 preprocessing is carried out. There is no way
12801 using @command{gnatpp} to obtain pretty printed files that
12802 include the preprocessing directives.
12804 If the compilation unit
12805 contained in the input source depends semantically upon units located
12806 outside the current directory, you have to provide the source search path
12807 when invoking @command{gnatpp}, if these units are contained in files with
12808 names that do not follow the GNAT file naming rules, you have to provide
12809 the configuration file describing the corresponding naming scheme;
12810 see the description of the @command{gnatpp}
12811 switches below. Another possibility is to use a project file and to
12812 call @command{gnatpp} through the @command{gnat} driver
12814 The @command{gnatpp} command has the form
12817 @c $ gnatpp @ovar{switches} @var{filename}
12818 @c Expanding @ovar macro inline (explanation in macro def comments)
12819 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12826 @var{switches} is an optional sequence of switches defining such properties as
12827 the formatting rules, the source search path, and the destination for the
12831 @var{filename} is the name (including the extension) of the source file to
12832 reformat; ``wildcards'' or several file names on the same gnatpp command are
12833 allowed. The file name may contain path information; it does not have to
12834 follow the GNAT file naming rules
12837 @samp{@var{gcc_switches}} is a list of switches for
12838 @command{gcc}. They will be passed on to all compiler invocations made by
12839 @command{gnatelim} to generate the ASIS trees. Here you can provide
12840 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12841 use the @option{-gnatec} switch to set the configuration file,
12842 use the @option{-gnat05} switch if sources should be compiled in
12847 * Switches for gnatpp::
12848 * Formatting Rules::
12851 @node Switches for gnatpp
12852 @section Switches for @command{gnatpp}
12855 The following subsections describe the various switches accepted by
12856 @command{gnatpp}, organized by category.
12859 You specify a switch by supplying a name and generally also a value.
12860 In many cases the values for a switch with a given name are incompatible with
12862 (for example the switch that controls the casing of a reserved word may have
12863 exactly one value: upper case, lower case, or
12864 mixed case) and thus exactly one such switch can be in effect for an
12865 invocation of @command{gnatpp}.
12866 If more than one is supplied, the last one is used.
12867 However, some values for the same switch are mutually compatible.
12868 You may supply several such switches to @command{gnatpp}, but then
12869 each must be specified in full, with both the name and the value.
12870 Abbreviated forms (the name appearing once, followed by each value) are
12872 For example, to set
12873 the alignment of the assignment delimiter both in declarations and in
12874 assignment statements, you must write @option{-A2A3}
12875 (or @option{-A2 -A3}), but not @option{-A23}.
12879 In many cases the set of options for a given qualifier are incompatible with
12880 each other (for example the qualifier that controls the casing of a reserved
12881 word may have exactly one option, which specifies either upper case, lower
12882 case, or mixed case), and thus exactly one such option can be in effect for
12883 an invocation of @command{gnatpp}.
12884 If more than one is supplied, the last one is used.
12885 However, some qualifiers have options that are mutually compatible,
12886 and then you may then supply several such options when invoking
12890 In most cases, it is obvious whether or not the
12891 ^values for a switch with a given name^options for a given qualifier^
12892 are compatible with each other.
12893 When the semantics might not be evident, the summaries below explicitly
12894 indicate the effect.
12897 * Alignment Control::
12899 * Construct Layout Control::
12900 * General Text Layout Control::
12901 * Other Formatting Options::
12902 * Setting the Source Search Path::
12903 * Output File Control::
12904 * Other gnatpp Switches::
12907 @node Alignment Control
12908 @subsection Alignment Control
12909 @cindex Alignment control in @command{gnatpp}
12912 Programs can be easier to read if certain constructs are vertically aligned.
12913 By default all alignments are set ON.
12914 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12915 OFF, and then use one or more of the other
12916 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12917 to activate alignment for specific constructs.
12920 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12924 Set all alignments to ON
12927 @item ^-A0^/ALIGN=OFF^
12928 Set all alignments to OFF
12930 @item ^-A1^/ALIGN=COLONS^
12931 Align @code{:} in declarations
12933 @item ^-A2^/ALIGN=DECLARATIONS^
12934 Align @code{:=} in initializations in declarations
12936 @item ^-A3^/ALIGN=STATEMENTS^
12937 Align @code{:=} in assignment statements
12939 @item ^-A4^/ALIGN=ARROWS^
12940 Align @code{=>} in associations
12942 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12943 Align @code{at} keywords in the component clauses in record
12944 representation clauses
12948 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12951 @node Casing Control
12952 @subsection Casing Control
12953 @cindex Casing control in @command{gnatpp}
12956 @command{gnatpp} allows you to specify the casing for reserved words,
12957 pragma names, attribute designators and identifiers.
12958 For identifiers you may define a
12959 general rule for name casing but also override this rule
12960 via a set of dictionary files.
12962 Three types of casing are supported: lower case, upper case, and mixed case.
12963 Lower and upper case are self-explanatory (but since some letters in
12964 Latin1 and other GNAT-supported character sets
12965 exist only in lower-case form, an upper case conversion will have no
12967 ``Mixed case'' means that the first letter, and also each letter immediately
12968 following an underscore, are converted to their uppercase forms;
12969 all the other letters are converted to their lowercase forms.
12972 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12973 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12974 Attribute designators are lower case
12976 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12977 Attribute designators are upper case
12979 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12980 Attribute designators are mixed case (this is the default)
12982 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12983 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12984 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12985 lower case (this is the default)
12987 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12988 Keywords are upper case
12990 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12991 @item ^-nD^/NAME_CASING=AS_DECLARED^
12992 Name casing for defining occurrences are as they appear in the source file
12993 (this is the default)
12995 @item ^-nU^/NAME_CASING=UPPER_CASE^
12996 Names are in upper case
12998 @item ^-nL^/NAME_CASING=LOWER_CASE^
12999 Names are in lower case
13001 @item ^-nM^/NAME_CASING=MIXED_CASE^
13002 Names are in mixed case
13004 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13005 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13006 Pragma names are lower case
13008 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13009 Pragma names are upper case
13011 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13012 Pragma names are mixed case (this is the default)
13014 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13015 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13016 Use @var{file} as a @emph{dictionary file} that defines
13017 the casing for a set of specified names,
13018 thereby overriding the effect on these names by
13019 any explicit or implicit
13020 ^-n^/NAME_CASING^ switch.
13021 To supply more than one dictionary file,
13022 use ^several @option{-D} switches^a list of files as options^.
13025 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13026 to define the casing for the Ada predefined names and
13027 the names declared in the GNAT libraries.
13029 @item ^-D-^/SPECIFIC_CASING^
13030 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13031 Do not use the default dictionary file;
13032 instead, use the casing
13033 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13038 The structure of a dictionary file, and details on the conventions
13039 used in the default dictionary file, are defined in @ref{Name Casing}.
13041 The @option{^-D-^/SPECIFIC_CASING^} and
13042 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13045 @node Construct Layout Control
13046 @subsection Construct Layout Control
13047 @cindex Layout control in @command{gnatpp}
13050 This group of @command{gnatpp} switches controls the layout of comments and
13051 complex syntactic constructs. See @ref{Formatting Comments} for details
13055 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13056 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13057 All the comments remain unchanged
13059 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13060 GNAT-style comment line indentation (this is the default).
13062 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13063 Reference-manual comment line indentation.
13065 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13066 GNAT-style comment beginning
13068 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13069 Reformat comment blocks
13071 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13072 Keep unchanged special form comments
13074 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13075 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13076 GNAT-style layout (this is the default)
13078 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13081 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13084 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13086 All the VT characters are removed from the comment text. All the HT characters
13087 are expanded with the sequences of space characters to get to the next tab
13090 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13091 @item ^--no-separate-is^/NO_SEPARATE_IS^
13092 Do not place the keyword @code{is} on a separate line in a subprogram body in
13093 case if the spec occupies more then one line.
13095 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13096 @item ^--separate-label^/SEPARATE_LABEL^
13097 Place statement label(s) on a separate line, with the following statement
13100 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13101 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13102 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13103 keyword @code{then} in IF statements on a separate line.
13105 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13106 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13107 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13108 keyword @code{then} in IF statements on a separate line. This option is
13109 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13111 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13112 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13113 Start each USE clause in a context clause from a separate line.
13115 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13116 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13117 Use a separate line for a loop or block statement name, but do not use an extra
13118 indentation level for the statement itself.
13124 The @option{-c1} and @option{-c2} switches are incompatible.
13125 The @option{-c3} and @option{-c4} switches are compatible with each other and
13126 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13127 the other comment formatting switches.
13129 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13134 For the @option{/COMMENTS_LAYOUT} qualifier:
13137 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13139 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13140 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13144 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13145 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13148 @node General Text Layout Control
13149 @subsection General Text Layout Control
13152 These switches allow control over line length and indentation.
13155 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13156 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13157 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13159 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13160 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13161 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13163 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13164 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13165 Indentation level for continuation lines (relative to the line being
13166 continued), @var{nnn} from 1@dots{}9.
13168 value is one less then the (normal) indentation level, unless the
13169 indentation is set to 1 (in which case the default value for continuation
13170 line indentation is also 1)
13173 @node Other Formatting Options
13174 @subsection Other Formatting Options
13177 These switches control the inclusion of missing end/exit labels, and
13178 the indentation level in @b{case} statements.
13181 @item ^-e^/NO_MISSED_LABELS^
13182 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13183 Do not insert missing end/exit labels. An end label is the name of
13184 a construct that may optionally be repeated at the end of the
13185 construct's declaration;
13186 e.g., the names of packages, subprograms, and tasks.
13187 An exit label is the name of a loop that may appear as target
13188 of an exit statement within the loop.
13189 By default, @command{gnatpp} inserts these end/exit labels when
13190 they are absent from the original source. This option suppresses such
13191 insertion, so that the formatted source reflects the original.
13193 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13194 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13195 Insert a Form Feed character after a pragma Page.
13197 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13198 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13199 Do not use an additional indentation level for @b{case} alternatives
13200 and variants if there are @var{nnn} or more (the default
13202 If @var{nnn} is 0, an additional indentation level is
13203 used for @b{case} alternatives and variants regardless of their number.
13206 @node Setting the Source Search Path
13207 @subsection Setting the Source Search Path
13210 To define the search path for the input source file, @command{gnatpp}
13211 uses the same switches as the GNAT compiler, with the same effects.
13214 @item ^-I^/SEARCH=^@var{dir}
13215 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13216 The same as the corresponding gcc switch
13218 @item ^-I-^/NOCURRENT_DIRECTORY^
13219 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13220 The same as the corresponding gcc switch
13222 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13223 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13224 The same as the corresponding gcc switch
13226 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13227 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13228 The same as the corresponding gcc switch
13232 @node Output File Control
13233 @subsection Output File Control
13236 By default the output is sent to the file whose name is obtained by appending
13237 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13238 (if the file with this name already exists, it is unconditionally overwritten).
13239 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13240 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13242 The output may be redirected by the following switches:
13245 @item ^-pipe^/STANDARD_OUTPUT^
13246 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13247 Send the output to @code{Standard_Output}
13249 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13250 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13251 Write the output into @var{output_file}.
13252 If @var{output_file} already exists, @command{gnatpp} terminates without
13253 reading or processing the input file.
13255 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13256 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13257 Write the output into @var{output_file}, overwriting the existing file
13258 (if one is present).
13260 @item ^-r^/REPLACE^
13261 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13262 Replace the input source file with the reformatted output, and copy the
13263 original input source into the file whose name is obtained by appending the
13264 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13265 If a file with this name already exists, @command{gnatpp} terminates without
13266 reading or processing the input file.
13268 @item ^-rf^/OVERRIDING_REPLACE^
13269 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13270 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13271 already exists, it is overwritten.
13273 @item ^-rnb^/REPLACE_NO_BACKUP^
13274 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13275 Replace the input source file with the reformatted output without
13276 creating any backup copy of the input source.
13278 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13279 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13280 Specifies the format of the reformatted output file. The @var{xxx}
13281 ^string specified with the switch^option^ may be either
13283 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13284 @item ``@option{^crlf^CRLF^}''
13285 the same as @option{^crlf^CRLF^}
13286 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13287 @item ``@option{^lf^LF^}''
13288 the same as @option{^unix^UNIX^}
13291 @item ^-W^/RESULT_ENCODING=^@var{e}
13292 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13293 Specify the wide character encoding method used to write the code in the
13295 @var{e} is one of the following:
13303 Upper half encoding
13305 @item ^s^SHIFT_JIS^
13315 Brackets encoding (default value)
13321 Options @option{^-pipe^/STANDARD_OUTPUT^},
13322 @option{^-o^/OUTPUT^} and
13323 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13324 contains only one file to reformat.
13326 @option{^--eol^/END_OF_LINE^}
13328 @option{^-W^/RESULT_ENCODING^}
13329 cannot be used together
13330 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13332 @node Other gnatpp Switches
13333 @subsection Other @code{gnatpp} Switches
13336 The additional @command{gnatpp} switches are defined in this subsection.
13339 @item ^-files @var{filename}^/FILES=@var{filename}^
13340 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13341 Take the argument source files from the specified file. This file should be an
13342 ordinary text file containing file names separated by spaces or
13343 line breaks. You can use this switch more than once in the same call to
13344 @command{gnatpp}. You also can combine this switch with an explicit list of
13347 @item ^-v^/VERBOSE^
13348 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13350 @command{gnatpp} generates version information and then
13351 a trace of the actions it takes to produce or obtain the ASIS tree.
13353 @item ^-w^/WARNINGS^
13354 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13356 @command{gnatpp} generates a warning whenever it cannot provide
13357 a required layout in the result source.
13360 @node Formatting Rules
13361 @section Formatting Rules
13364 The following subsections show how @command{gnatpp} treats ``white space'',
13365 comments, program layout, and name casing.
13366 They provide the detailed descriptions of the switches shown above.
13369 * White Space and Empty Lines::
13370 * Formatting Comments::
13371 * Construct Layout::
13375 @node White Space and Empty Lines
13376 @subsection White Space and Empty Lines
13379 @command{gnatpp} does not have an option to control space characters.
13380 It will add or remove spaces according to the style illustrated by the
13381 examples in the @cite{Ada Reference Manual}.
13383 The only format effectors
13384 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13385 that will appear in the output file are platform-specific line breaks,
13386 and also format effectors within (but not at the end of) comments.
13387 In particular, each horizontal tab character that is not inside
13388 a comment will be treated as a space and thus will appear in the
13389 output file as zero or more spaces depending on
13390 the reformatting of the line in which it appears.
13391 The only exception is a Form Feed character, which is inserted after a
13392 pragma @code{Page} when @option{-ff} is set.
13394 The output file will contain no lines with trailing ``white space'' (spaces,
13397 Empty lines in the original source are preserved
13398 only if they separate declarations or statements.
13399 In such contexts, a
13400 sequence of two or more empty lines is replaced by exactly one empty line.
13401 Note that a blank line will be removed if it separates two ``comment blocks''
13402 (a comment block is a sequence of whole-line comments).
13403 In order to preserve a visual separation between comment blocks, use an
13404 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13405 Likewise, if for some reason you wish to have a sequence of empty lines,
13406 use a sequence of empty comments instead.
13408 @node Formatting Comments
13409 @subsection Formatting Comments
13412 Comments in Ada code are of two kinds:
13415 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13416 ``white space'') on a line
13419 an @emph{end-of-line comment}, which follows some other Ada lexical element
13424 The indentation of a whole-line comment is that of either
13425 the preceding or following line in
13426 the formatted source, depending on switch settings as will be described below.
13428 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13429 between the end of the preceding Ada lexical element and the beginning
13430 of the comment as appear in the original source,
13431 unless either the comment has to be split to
13432 satisfy the line length limitation, or else the next line contains a
13433 whole line comment that is considered a continuation of this end-of-line
13434 comment (because it starts at the same position).
13436 cases, the start of the end-of-line comment is moved right to the nearest
13437 multiple of the indentation level.
13438 This may result in a ``line overflow'' (the right-shifted comment extending
13439 beyond the maximum line length), in which case the comment is split as
13442 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13443 (GNAT-style comment line indentation)
13444 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13445 (reference-manual comment line indentation).
13446 With reference-manual style, a whole-line comment is indented as if it
13447 were a declaration or statement at the same place
13448 (i.e., according to the indentation of the preceding line(s)).
13449 With GNAT style, a whole-line comment that is immediately followed by an
13450 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13451 word @b{begin}, is indented based on the construct that follows it.
13454 @smallexample @c ada
13466 Reference-manual indentation produces:
13468 @smallexample @c ada
13480 while GNAT-style indentation produces:
13482 @smallexample @c ada
13494 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13495 (GNAT style comment beginning) has the following
13500 For each whole-line comment that does not end with two hyphens,
13501 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13502 to ensure that there are at least two spaces between these hyphens and the
13503 first non-blank character of the comment.
13507 For an end-of-line comment, if in the original source the next line is a
13508 whole-line comment that starts at the same position
13509 as the end-of-line comment,
13510 then the whole-line comment (and all whole-line comments
13511 that follow it and that start at the same position)
13512 will start at this position in the output file.
13515 That is, if in the original source we have:
13517 @smallexample @c ada
13520 A := B + C; -- B must be in the range Low1..High1
13521 -- C must be in the range Low2..High2
13522 --B+C will be in the range Low1+Low2..High1+High2
13528 Then in the formatted source we get
13530 @smallexample @c ada
13533 A := B + C; -- B must be in the range Low1..High1
13534 -- C must be in the range Low2..High2
13535 -- B+C will be in the range Low1+Low2..High1+High2
13541 A comment that exceeds the line length limit will be split.
13543 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13544 the line belongs to a reformattable block, splitting the line generates a
13545 @command{gnatpp} warning.
13546 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13547 comments may be reformatted in typical
13548 word processor style (that is, moving words between lines and putting as
13549 many words in a line as possible).
13552 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13553 that has a special format (that is, a character that is neither a letter nor digit
13554 not white space nor line break immediately following the leading @code{--} of
13555 the comment) should be without any change moved from the argument source
13556 into reformatted source. This switch allows to preserve comments that are used
13557 as a special marks in the code (e.g.@: SPARK annotation).
13559 @node Construct Layout
13560 @subsection Construct Layout
13563 In several cases the suggested layout in the Ada Reference Manual includes
13564 an extra level of indentation that many programmers prefer to avoid. The
13565 affected cases include:
13569 @item Record type declaration (RM 3.8)
13571 @item Record representation clause (RM 13.5.1)
13573 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13575 @item Block statement in case if a block has a statement identifier (RM 5.6)
13579 In compact mode (when GNAT style layout or compact layout is set),
13580 the pretty printer uses one level of indentation instead
13581 of two. This is achieved in the record definition and record representation
13582 clause cases by putting the @code{record} keyword on the same line as the
13583 start of the declaration or representation clause, and in the block and loop
13584 case by putting the block or loop header on the same line as the statement
13588 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13589 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13590 layout on the one hand, and uncompact layout
13591 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13592 can be illustrated by the following examples:
13596 @multitable @columnfractions .5 .5
13597 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13600 @smallexample @c ada
13607 @smallexample @c ada
13616 @smallexample @c ada
13618 a at 0 range 0 .. 31;
13619 b at 4 range 0 .. 31;
13623 @smallexample @c ada
13626 a at 0 range 0 .. 31;
13627 b at 4 range 0 .. 31;
13632 @smallexample @c ada
13640 @smallexample @c ada
13650 @smallexample @c ada
13651 Clear : for J in 1 .. 10 loop
13656 @smallexample @c ada
13658 for J in 1 .. 10 loop
13669 GNAT style, compact layout Uncompact layout
13671 type q is record type q is
13672 a : integer; record
13673 b : integer; a : integer;
13674 end record; b : integer;
13677 for q use record for q use
13678 a at 0 range 0 .. 31; record
13679 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
13680 end record; b at 4 range 0 .. 31;
13683 Block : declare Block :
13684 A : Integer := 3; declare
13685 begin A : Integer := 3;
13687 end Block; Proc (A, A);
13690 Clear : for J in 1 .. 10 loop Clear :
13691 A (J) := 0; for J in 1 .. 10 loop
13692 end loop Clear; A (J) := 0;
13699 A further difference between GNAT style layout and compact layout is that
13700 GNAT style layout inserts empty lines as separation for
13701 compound statements, return statements and bodies.
13703 Note that the layout specified by
13704 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13705 for named block and loop statements overrides the layout defined by these
13706 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13707 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13708 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13711 @subsection Name Casing
13714 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13715 the same casing as the corresponding defining identifier.
13717 You control the casing for defining occurrences via the
13718 @option{^-n^/NAME_CASING^} switch.
13720 With @option{-nD} (``as declared'', which is the default),
13723 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13725 defining occurrences appear exactly as in the source file
13726 where they are declared.
13727 The other ^values for this switch^options for this qualifier^ ---
13728 @option{^-nU^UPPER_CASE^},
13729 @option{^-nL^LOWER_CASE^},
13730 @option{^-nM^MIXED_CASE^} ---
13732 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13733 If @command{gnatpp} changes the casing of a defining
13734 occurrence, it analogously changes the casing of all the
13735 usage occurrences of this name.
13737 If the defining occurrence of a name is not in the source compilation unit
13738 currently being processed by @command{gnatpp}, the casing of each reference to
13739 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13740 switch (subject to the dictionary file mechanism described below).
13741 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13743 casing for the defining occurrence of the name.
13745 Some names may need to be spelled with casing conventions that are not
13746 covered by the upper-, lower-, and mixed-case transformations.
13747 You can arrange correct casing by placing such names in a
13748 @emph{dictionary file},
13749 and then supplying a @option{^-D^/DICTIONARY^} switch.
13750 The casing of names from dictionary files overrides
13751 any @option{^-n^/NAME_CASING^} switch.
13753 To handle the casing of Ada predefined names and the names from GNAT libraries,
13754 @command{gnatpp} assumes a default dictionary file.
13755 The name of each predefined entity is spelled with the same casing as is used
13756 for the entity in the @cite{Ada Reference Manual}.
13757 The name of each entity in the GNAT libraries is spelled with the same casing
13758 as is used in the declaration of that entity.
13760 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13761 default dictionary file.
13762 Instead, the casing for predefined and GNAT-defined names will be established
13763 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13764 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13765 will appear as just shown,
13766 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13767 To ensure that even such names are rendered in uppercase,
13768 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13769 (or else, less conveniently, place these names in upper case in a dictionary
13772 A dictionary file is
13773 a plain text file; each line in this file can be either a blank line
13774 (containing only space characters and ASCII.HT characters), an Ada comment
13775 line, or the specification of exactly one @emph{casing schema}.
13777 A casing schema is a string that has the following syntax:
13781 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13783 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13788 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13789 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13791 The casing schema string can be followed by white space and/or an Ada-style
13792 comment; any amount of white space is allowed before the string.
13794 If a dictionary file is passed as
13796 the value of a @option{-D@var{file}} switch
13799 an option to the @option{/DICTIONARY} qualifier
13802 simple name and every identifier, @command{gnatpp} checks if the dictionary
13803 defines the casing for the name or for some of its parts (the term ``subword''
13804 is used below to denote the part of a name which is delimited by ``_'' or by
13805 the beginning or end of the word and which does not contain any ``_'' inside):
13809 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13810 the casing defined by the dictionary; no subwords are checked for this word
13813 for every subword @command{gnatpp} checks if the dictionary contains the
13814 corresponding string of the form @code{*@var{simple_identifier}*},
13815 and if it does, the casing of this @var{simple_identifier} is used
13819 if the whole name does not contain any ``_'' inside, and if for this name
13820 the dictionary contains two entries - one of the form @var{identifier},
13821 and another - of the form *@var{simple_identifier}*, then the first one
13822 is applied to define the casing of this name
13825 if more than one dictionary file is passed as @command{gnatpp} switches, each
13826 dictionary adds new casing exceptions and overrides all the existing casing
13827 exceptions set by the previous dictionaries
13830 when @command{gnatpp} checks if the word or subword is in the dictionary,
13831 this check is not case sensitive
13835 For example, suppose we have the following source to reformat:
13837 @smallexample @c ada
13840 name1 : integer := 1;
13841 name4_name3_name2 : integer := 2;
13842 name2_name3_name4 : Boolean;
13845 name2_name3_name4 := name4_name3_name2 > name1;
13851 And suppose we have two dictionaries:
13868 If @command{gnatpp} is called with the following switches:
13872 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13875 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13880 then we will get the following name casing in the @command{gnatpp} output:
13882 @smallexample @c ada
13885 NAME1 : Integer := 1;
13886 Name4_NAME3_Name2 : Integer := 2;
13887 Name2_NAME3_Name4 : Boolean;
13890 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13895 @c *********************************
13896 @node The GNAT Metric Tool gnatmetric
13897 @chapter The GNAT Metric Tool @command{gnatmetric}
13899 @cindex Metric tool
13902 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13903 for computing various program metrics.
13904 It takes an Ada source file as input and generates a file containing the
13905 metrics data as output. Various switches control which
13906 metrics are computed and output.
13908 @command{gnatmetric} generates and uses the ASIS
13909 tree for the input source and thus requires the input to be syntactically and
13910 semantically legal.
13911 If this condition is not met, @command{gnatmetric} will generate
13912 an error message; no metric information for this file will be
13913 computed and reported.
13915 If the compilation unit contained in the input source depends semantically
13916 upon units in files located outside the current directory, you have to provide
13917 the source search path when invoking @command{gnatmetric}.
13918 If it depends semantically upon units that are contained
13919 in files with names that do not follow the GNAT file naming rules, you have to
13920 provide the configuration file describing the corresponding naming scheme (see
13921 the description of the @command{gnatmetric} switches below.)
13922 Alternatively, you may use a project file and invoke @command{gnatmetric}
13923 through the @command{gnat} driver.
13925 The @command{gnatmetric} command has the form
13928 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13929 @c Expanding @ovar macro inline (explanation in macro def comments)
13930 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13937 @var{switches} specify the metrics to compute and define the destination for
13941 Each @var{filename} is the name (including the extension) of a source
13942 file to process. ``Wildcards'' are allowed, and
13943 the file name may contain path information.
13944 If no @var{filename} is supplied, then the @var{switches} list must contain
13946 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13947 Including both a @option{-files} switch and one or more
13948 @var{filename} arguments is permitted.
13951 @samp{@var{gcc_switches}} is a list of switches for
13952 @command{gcc}. They will be passed on to all compiler invocations made by
13953 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13954 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13955 and use the @option{-gnatec} switch to set the configuration file,
13956 use the @option{-gnat05} switch if sources should be compiled in
13961 * Switches for gnatmetric::
13964 @node Switches for gnatmetric
13965 @section Switches for @command{gnatmetric}
13968 The following subsections describe the various switches accepted by
13969 @command{gnatmetric}, organized by category.
13972 * Output Files Control::
13973 * Disable Metrics For Local Units::
13974 * Specifying a set of metrics to compute::
13975 * Other gnatmetric Switches::
13976 * Generate project-wide metrics::
13979 @node Output Files Control
13980 @subsection Output File Control
13981 @cindex Output file control in @command{gnatmetric}
13984 @command{gnatmetric} has two output formats. It can generate a
13985 textual (human-readable) form, and also XML. By default only textual
13986 output is generated.
13988 When generating the output in textual form, @command{gnatmetric} creates
13989 for each Ada source file a corresponding text file
13990 containing the computed metrics, except for the case when the set of metrics
13991 specified by gnatmetric parameters consists only of metrics that are computed
13992 for the whole set of analyzed sources, but not for each Ada source.
13993 By default, this file is placed in the same directory as where the source
13994 file is located, and its name is obtained
13995 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13998 All the output information generated in XML format is placed in a single
13999 file. By default this file is placed in the current directory and has the
14000 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14002 Some of the computed metrics are summed over the units passed to
14003 @command{gnatmetric}; for example, the total number of lines of code.
14004 By default this information is sent to @file{stdout}, but a file
14005 can be specified with the @option{-og} switch.
14007 The following switches control the @command{gnatmetric} output:
14010 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14012 Generate the XML output
14014 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14016 Generate the XML output and the XML schema file that describes the structure
14017 of the XML metric report, this schema is assigned to the XML file. The schema
14018 file has the same name as the XML output file with @file{.xml} suffix replaced
14021 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14022 @item ^-nt^/NO_TEXT^
14023 Do not generate the output in text form (implies @option{^-x^/XML^})
14025 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14026 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14027 Put text files with detailed metrics into @var{output_dir}
14029 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14030 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14031 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14032 in the name of the output file.
14034 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14035 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14036 Put global metrics into @var{file_name}
14038 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14039 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14040 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14042 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14043 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14044 Use ``short'' source file names in the output. (The @command{gnatmetric}
14045 output includes the name(s) of the Ada source file(s) from which the metrics
14046 are computed. By default each name includes the absolute path. The
14047 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14048 to exclude all directory information from the file names that are output.)
14052 @node Disable Metrics For Local Units
14053 @subsection Disable Metrics For Local Units
14054 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14057 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14059 unit per one source file. It computes line metrics for the whole source
14060 file, and it also computes syntax
14061 and complexity metrics for the file's outermost unit.
14063 By default, @command{gnatmetric} will also compute all metrics for certain
14064 kinds of locally declared program units:
14068 subprogram (and generic subprogram) bodies;
14071 package (and generic package) specs and bodies;
14074 task object and type specifications and bodies;
14077 protected object and type specifications and bodies.
14081 These kinds of entities will be referred to as
14082 @emph{eligible local program units}, or simply @emph{eligible local units},
14083 @cindex Eligible local unit (for @command{gnatmetric})
14084 in the discussion below.
14086 Note that a subprogram declaration, generic instantiation,
14087 or renaming declaration only receives metrics
14088 computation when it appear as the outermost entity
14091 Suppression of metrics computation for eligible local units can be
14092 obtained via the following switch:
14095 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14096 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14097 Do not compute detailed metrics for eligible local program units
14101 @node Specifying a set of metrics to compute
14102 @subsection Specifying a set of metrics to compute
14105 By default all the metrics are computed and reported. The switches
14106 described in this subsection allow you to control, on an individual
14107 basis, whether metrics are computed and
14108 reported. If at least one positive metric
14109 switch is specified (that is, a switch that defines that a given
14110 metric or set of metrics is to be computed), then only
14111 explicitly specified metrics are reported.
14114 * Line Metrics Control::
14115 * Syntax Metrics Control::
14116 * Complexity Metrics Control::
14117 * Coupling Metrics Control::
14120 @node Line Metrics Control
14121 @subsubsection Line Metrics Control
14122 @cindex Line metrics control in @command{gnatmetric}
14125 For any (legal) source file, and for each of its
14126 eligible local program units, @command{gnatmetric} computes the following
14131 the total number of lines;
14134 the total number of code lines (i.e., non-blank lines that are not comments)
14137 the number of comment lines
14140 the number of code lines containing end-of-line comments;
14143 the comment percentage: the ratio between the number of lines that contain
14144 comments and the number of all non-blank lines, expressed as a percentage;
14147 the number of empty lines and lines containing only space characters and/or
14148 format effectors (blank lines)
14151 the average number of code lines in subprogram bodies, task bodies, entry
14152 bodies and statement sequences in package bodies (this metric is only computed
14153 across the whole set of the analyzed units)
14158 @command{gnatmetric} sums the values of the line metrics for all the
14159 files being processed and then generates the cumulative results. The tool
14160 also computes for all the files being processed the average number of code
14163 You can use the following switches to select the specific line metrics
14164 to be computed and reported.
14167 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14170 @cindex @option{--no-lines@var{x}}
14173 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14174 Report all the line metrics
14176 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14177 Do not report any of line metrics
14179 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14180 Report the number of all lines
14182 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14183 Do not report the number of all lines
14185 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14186 Report the number of code lines
14188 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14189 Do not report the number of code lines
14191 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14192 Report the number of comment lines
14194 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14195 Do not report the number of comment lines
14197 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14198 Report the number of code lines containing
14199 end-of-line comments
14201 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14202 Do not report the number of code lines containing
14203 end-of-line comments
14205 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14206 Report the comment percentage in the program text
14208 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14209 Do not report the comment percentage in the program text
14211 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14212 Report the number of blank lines
14214 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14215 Do not report the number of blank lines
14217 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14218 Report the average number of code lines in subprogram bodies, task bodies,
14219 entry bodies and statement sequences in package bodies. The metric is computed
14220 and reported for the whole set of processed Ada sources only.
14222 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14223 Do not report the average number of code lines in subprogram bodies,
14224 task bodies, entry bodies and statement sequences in package bodies.
14228 @node Syntax Metrics Control
14229 @subsubsection Syntax Metrics Control
14230 @cindex Syntax metrics control in @command{gnatmetric}
14233 @command{gnatmetric} computes various syntactic metrics for the
14234 outermost unit and for each eligible local unit:
14237 @item LSLOC (``Logical Source Lines Of Code'')
14238 The total number of declarations and the total number of statements. Note
14239 that the definition of declarations is the one given in the reference
14243 ``Each of the following is defined to be a declaration: any basic_declaration;
14244 an enumeration_literal_specification; a discriminant_specification;
14245 a component_declaration; a loop_parameter_specification; a
14246 parameter_specification; a subprogram_body; an entry_declaration;
14247 an entry_index_specification; a choice_parameter_specification;
14248 a generic_formal_parameter_declaration.''
14250 This means for example that each enumeration literal adds one to the count,
14251 as well as each subprogram parameter.
14253 Thus the results from this metric will be significantly greater than might
14254 be expected from a naive view of counting semicolons.
14256 @item Maximal static nesting level of inner program units
14258 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14259 package, a task unit, a protected unit, a
14260 protected entry, a generic unit, or an explicitly declared subprogram other
14261 than an enumeration literal.''
14263 @item Maximal nesting level of composite syntactic constructs
14264 This corresponds to the notion of the
14265 maximum nesting level in the GNAT built-in style checks
14266 (@pxref{Style Checking})
14270 For the outermost unit in the file, @command{gnatmetric} additionally computes
14271 the following metrics:
14274 @item Public subprograms
14275 This metric is computed for package specs. It is the
14276 number of subprograms and generic subprograms declared in the visible
14277 part (including the visible part of nested packages, protected objects, and
14280 @item All subprograms
14281 This metric is computed for bodies and subunits. The
14282 metric is equal to a total number of subprogram bodies in the compilation
14284 Neither generic instantiations nor renamings-as-a-body nor body stubs
14285 are counted. Any subprogram body is counted, independently of its nesting
14286 level and enclosing constructs. Generic bodies and bodies of protected
14287 subprograms are counted in the same way as ``usual'' subprogram bodies.
14290 This metric is computed for package specs and
14291 generic package declarations. It is the total number of types
14292 that can be referenced from outside this compilation unit, plus the
14293 number of types from all the visible parts of all the visible generic
14294 packages. Generic formal types are not counted. Only types, not subtypes,
14298 Along with the total number of public types, the following
14299 types are counted and reported separately:
14306 Root tagged types (abstract, non-abstract, private, non-private). Type
14307 extensions are @emph{not} counted
14310 Private types (including private extensions)
14321 This metric is computed for any compilation unit. It is equal to the total
14322 number of the declarations of different types given in the compilation unit.
14323 The private and the corresponding full type declaration are counted as one
14324 type declaration. Incomplete type declarations and generic formal types
14326 No distinction is made among different kinds of types (abstract,
14327 private etc.); the total number of types is computed and reported.
14332 By default, all the syntax metrics are computed and reported. You can use the
14333 following switches to select specific syntax metrics.
14337 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14340 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14343 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14344 Report all the syntax metrics
14346 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14347 Do not report any of syntax metrics
14349 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14350 Report the total number of declarations
14352 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14353 Do not report the total number of declarations
14355 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14356 Report the total number of statements
14358 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14359 Do not report the total number of statements
14361 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14362 Report the number of public subprograms in a compilation unit
14364 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14365 Do not report the number of public subprograms in a compilation unit
14367 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14368 Report the number of all the subprograms in a compilation unit
14370 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14371 Do not report the number of all the subprograms in a compilation unit
14373 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14374 Report the number of public types in a compilation unit
14376 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14377 Do not report the number of public types in a compilation unit
14379 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14380 Report the number of all the types in a compilation unit
14382 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14383 Do not report the number of all the types in a compilation unit
14385 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14386 Report the maximal program unit nesting level
14388 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14389 Do not report the maximal program unit nesting level
14391 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14392 Report the maximal construct nesting level
14394 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14395 Do not report the maximal construct nesting level
14399 @node Complexity Metrics Control
14400 @subsubsection Complexity Metrics Control
14401 @cindex Complexity metrics control in @command{gnatmetric}
14404 For a program unit that is an executable body (a subprogram body (including
14405 generic bodies), task body, entry body or a package body containing
14406 its own statement sequence) @command{gnatmetric} computes the following
14407 complexity metrics:
14411 McCabe cyclomatic complexity;
14414 McCabe essential complexity;
14417 maximal loop nesting level;
14420 extra exit points (for subprograms);
14424 The McCabe cyclomatic complexity metric is defined
14425 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14427 According to McCabe, both control statements and short-circuit control forms
14428 should be taken into account when computing cyclomatic complexity. For each
14429 body, we compute three metric values:
14433 the complexity introduced by control
14434 statements only, without taking into account short-circuit forms,
14437 the complexity introduced by short-circuit control forms only, and
14441 cyclomatic complexity, which is the sum of these two values.
14446 The origin of cyclomatic complexity metric is the need to estimate the number
14447 of independent paths in the control flow graph that in turn gives the number
14448 of tests needed to satisfy paths coverage testing completeness criterion.
14449 Considered from the testing point of view, a static Ada @code{loop} (that is,
14450 the @code{loop} statement having static subtype in loop parameter
14451 specification) does not add to cyclomatic complexity. By providing
14452 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14453 may specify that such loops should not be counted when computing the
14454 cyclomatic complexity metric
14456 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14457 counted for the code that is reduced by excluding all the pure structural Ada
14458 control statements. An compound statement is considered as a non-structural
14459 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14460 or if it contains a @code{goto} statement that transfers the control outside
14461 the operator. A selective accept statement with @code{terminate} alternative
14462 is considered as non-structural statement. When computing this metric,
14463 @code{exit} statements are treated in the same way as @code{goto}
14464 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14466 The Ada essential complexity metric defined here is intended to quantify
14467 the extent to which the software is unstructured. It is adapted from
14468 the McCabe essential complexity metric defined in
14469 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14470 suitable for typical Ada usage. For example, short circuit forms
14471 are not penalized as unstructured in the Ada essential complexity metric.
14473 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14474 the code in the exception handlers and in all the nested program units.
14476 By default, all the complexity metrics are computed and reported.
14477 For more fine-grained control you can use
14478 the following switches:
14481 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14484 @cindex @option{--no-complexity@var{x}}
14487 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14488 Report all the complexity metrics
14490 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14491 Do not report any of complexity metrics
14493 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14494 Report the McCabe Cyclomatic Complexity
14496 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14497 Do not report the McCabe Cyclomatic Complexity
14499 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14500 Report the Essential Complexity
14502 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14503 Do not report the Essential Complexity
14505 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14506 Report maximal loop nesting level
14508 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14509 Do not report maximal loop nesting level
14511 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14512 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14513 task bodies, entry bodies and statement sequences in package bodies.
14514 The metric is computed and reported for whole set of processed Ada sources
14517 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14518 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14519 bodies, task bodies, entry bodies and statement sequences in package bodies
14521 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14522 @item ^-ne^/NO_EXITS_AS_GOTOS^
14523 Do not consider @code{exit} statements as @code{goto}s when
14524 computing Essential Complexity
14526 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14527 @item ^--no-static-loop^/NO_STATIC_LOOP^
14528 Do not consider static loops when computing cyclomatic complexity
14530 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14531 Report the extra exit points for subprogram bodies. As an exit point, this
14532 metric counts @code{return} statements and raise statements in case when the
14533 raised exception is not handled in the same body. In case of a function this
14534 metric subtracts 1 from the number of exit points, because a function body
14535 must contain at least one @code{return} statement.
14537 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14538 Do not report the extra exit points for subprogram bodies
14542 @node Coupling Metrics Control
14543 @subsubsection Coupling Metrics Control
14544 @cindex Coupling metrics control in @command{gnatmetric}
14547 @cindex Coupling metrics (in in @command{gnatmetric})
14548 Coupling metrics measure the dependencies between a given entity and other
14549 entities the program consists of. The goal of these metrics is to estimate the
14550 stability of the whole program considered as the collection of entities
14551 (modules, classes etc.).
14553 Gnatmetric computes the following coupling metrics:
14558 @emph{object-oriented coupling} - for classes in traditional object-oriented
14562 @emph{unit coupling} - for all the program units making up a program;
14565 @emph{control coupling} - this metric counts dependencies between a unit and
14566 only those units that define subprograms;
14570 Two kinds of coupling metrics are computed:
14573 @item fan-out coupling (efferent coupling)
14574 @cindex fan-out coupling
14575 @cindex efferent coupling
14576 the number of entities the given entity depends upon. It
14577 estimates in what extent the given entity depends on the changes in
14580 @item fan-in coupling (afferent coupling)
14581 @cindex fan-in coupling
14582 @cindex afferent coupling
14583 the number of entities that depend on a given entity.
14584 It estimates in what extent the ``external world'' depends on the changes in a
14590 Object-oriented coupling metrics are metrics that measure the dependencies
14591 between a given class (or a group of classes) and the other classes in the
14592 program. In this subsection the term ``class'' is used in its traditional
14593 object-oriented programming sense (an instantiable module that contains data
14594 and/or method members). A @emph{category} (of classes) is a group of closely
14595 related classes that are reused and/or modified together.
14597 A class @code{K}'s fan-out coupling is the number of classes
14598 that @code{K} depends upon.
14599 A category's fan-out coupling is the number of classes outside the
14600 category that the classes inside the category depend upon.
14602 A class @code{K}'s fan-in coupling is the number of classes
14603 that depend upon @code{K}.
14604 A category's fan-in coupling is the number of classes outside the
14605 category that depend on classes belonging to the category.
14607 Ada's implementation of the object-oriented paradigm does not use the
14608 traditional class notion, so the definition of the coupling
14609 metrics for Ada maps the class and class category notions
14610 onto Ada constructs.
14612 For the coupling metrics, several kinds of modules -- a library package,
14613 a library generic package, and a library generic package instantiation --
14614 that define a tagged type or an interface type are
14615 considered to be a class. A category consists of a library package (or
14616 a library generic package) that defines a tagged or an interface type,
14617 together with all its descendant (generic) packages that define tagged
14618 or interface types. That is a
14619 category is an Ada hierarchy of library-level program units. So class coupling
14620 in case of Ada is called as tagged coupling, and category coupling - as
14621 hierarchy coupling.
14623 For any package counted as a class, its body and subunits (if any) are
14624 considered together with its spec when counting the dependencies, and coupling
14625 metrics are reported for spec units only. For dependencies between classes,
14626 the Ada semantic dependencies are considered. For object-oriented coupling
14627 metrics, only dependencies on units that are considered as classes, are
14630 For unit and control coupling also not compilation units but program units are
14631 counted. That is, for a package, its spec, its body and its subunits (if any)
14632 are considered as making up one unit, and the dependencies that are counted
14633 are the dependencies of all these compilation units collected together as
14634 the dependencies as a (whole) unit. And metrics are reported for spec
14635 compilation units only (or for a subprogram body unit in case if there is no
14636 separate spec for the given subprogram).
14638 For unit coupling, dependencies between all kinds of program units are
14639 considered. For control coupling, for each unit the dependencies of this unit
14640 upon units that define subprograms are counted, so control fan-out coupling
14641 is reported for all units, but control fan-in coupling - only for the units
14642 that define subprograms.
14649 When computing coupling metrics, @command{gnatmetric} counts only
14650 dependencies between units that are arguments of the gnatmetric call.
14651 Coupling metrics are program-wide (or project-wide) metrics, so to
14652 get a valid result, you should call @command{gnatmetric} for
14653 the whole set of sources that make up your program. It can be done
14654 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14655 option (see @ref{The GNAT Driver and Project Files} for details).
14657 By default, all the coupling metrics are disabled. You can use the following
14658 switches to specify the coupling metrics to be computed and reported:
14663 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14664 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14665 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14666 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14670 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14673 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14674 Report all the coupling metrics
14676 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14677 Report tagged (class) fan-out coupling
14679 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14680 Report tagged (class) fan-in coupling
14682 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14683 Report hierarchy (category) fan-out coupling
14685 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14686 Report hierarchy (category) fan-in coupling
14688 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14689 Report unit fan-out coupling
14691 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14692 Report unit fan-in coupling
14694 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14695 Report control fan-out coupling
14697 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14698 Report control fan-in coupling
14701 @node Other gnatmetric Switches
14702 @subsection Other @code{gnatmetric} Switches
14705 Additional @command{gnatmetric} switches are as follows:
14708 @item ^-files @var{filename}^/FILES=@var{filename}^
14709 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14710 Take the argument source files from the specified file. This file should be an
14711 ordinary text file containing file names separated by spaces or
14712 line breaks. You can use this switch more than once in the same call to
14713 @command{gnatmetric}. You also can combine this switch with
14714 an explicit list of files.
14716 @item ^-v^/VERBOSE^
14717 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14719 @command{gnatmetric} generates version information and then
14720 a trace of sources being processed.
14723 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14727 @node Generate project-wide metrics
14728 @subsection Generate project-wide metrics
14730 In order to compute metrics on all units of a given project, you can use
14731 the @command{gnat} driver along with the @option{-P} option:
14737 If the project @code{proj} depends upon other projects, you can compute
14738 the metrics on the project closure using the @option{-U} option:
14740 gnat metric -Pproj -U
14744 Finally, if not all the units are relevant to a particular main
14745 program in the project closure, you can generate metrics for the set
14746 of units needed to create a given main program (unit closure) using
14747 the @option{-U} option followed by the name of the main unit:
14749 gnat metric -Pproj -U main
14753 @c ***********************************
14754 @node File Name Krunching Using gnatkr
14755 @chapter File Name Krunching Using @code{gnatkr}
14759 This chapter discusses the method used by the compiler to shorten
14760 the default file names chosen for Ada units so that they do not
14761 exceed the maximum length permitted. It also describes the
14762 @code{gnatkr} utility that can be used to determine the result of
14763 applying this shortening.
14767 * Krunching Method::
14768 * Examples of gnatkr Usage::
14772 @section About @code{gnatkr}
14775 The default file naming rule in GNAT
14776 is that the file name must be derived from
14777 the unit name. The exact default rule is as follows:
14780 Take the unit name and replace all dots by hyphens.
14782 If such a replacement occurs in the
14783 second character position of a name, and the first character is
14784 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14785 then replace the dot by the character
14786 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14787 instead of a minus.
14789 The reason for this exception is to avoid clashes
14790 with the standard names for children of System, Ada, Interfaces,
14791 and GNAT, which use the prefixes
14792 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14795 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14796 switch of the compiler activates a ``krunching''
14797 circuit that limits file names to nn characters (where nn is a decimal
14798 integer). For example, using OpenVMS,
14799 where the maximum file name length is
14800 39, the value of nn is usually set to 39, but if you want to generate
14801 a set of files that would be usable if ported to a system with some
14802 different maximum file length, then a different value can be specified.
14803 The default value of 39 for OpenVMS need not be specified.
14805 The @code{gnatkr} utility can be used to determine the krunched name for
14806 a given file, when krunched to a specified maximum length.
14809 @section Using @code{gnatkr}
14812 The @code{gnatkr} command has the form
14816 @c $ gnatkr @var{name} @ovar{length}
14817 @c Expanding @ovar macro inline (explanation in macro def comments)
14818 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14824 $ gnatkr @var{name} /COUNT=nn
14829 @var{name} is the uncrunched file name, derived from the name of the unit
14830 in the standard manner described in the previous section (i.e., in particular
14831 all dots are replaced by hyphens). The file name may or may not have an
14832 extension (defined as a suffix of the form period followed by arbitrary
14833 characters other than period). If an extension is present then it will
14834 be preserved in the output. For example, when krunching @file{hellofile.ads}
14835 to eight characters, the result will be hellofil.ads.
14837 Note: for compatibility with previous versions of @code{gnatkr} dots may
14838 appear in the name instead of hyphens, but the last dot will always be
14839 taken as the start of an extension. So if @code{gnatkr} is given an argument
14840 such as @file{Hello.World.adb} it will be treated exactly as if the first
14841 period had been a hyphen, and for example krunching to eight characters
14842 gives the result @file{hellworl.adb}.
14844 Note that the result is always all lower case (except on OpenVMS where it is
14845 all upper case). Characters of the other case are folded as required.
14847 @var{length} represents the length of the krunched name. The default
14848 when no argument is given is ^8^39^ characters. A length of zero stands for
14849 unlimited, in other words do not chop except for system files where the
14850 implied crunching length is always eight characters.
14853 The output is the krunched name. The output has an extension only if the
14854 original argument was a file name with an extension.
14856 @node Krunching Method
14857 @section Krunching Method
14860 The initial file name is determined by the name of the unit that the file
14861 contains. The name is formed by taking the full expanded name of the
14862 unit and replacing the separating dots with hyphens and
14863 using ^lowercase^uppercase^
14864 for all letters, except that a hyphen in the second character position is
14865 replaced by a ^tilde^dollar sign^ if the first character is
14866 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14867 The extension is @code{.ads} for a
14868 spec and @code{.adb} for a body.
14869 Krunching does not affect the extension, but the file name is shortened to
14870 the specified length by following these rules:
14874 The name is divided into segments separated by hyphens, tildes or
14875 underscores and all hyphens, tildes, and underscores are
14876 eliminated. If this leaves the name short enough, we are done.
14879 If the name is too long, the longest segment is located (left-most
14880 if there are two of equal length), and shortened by dropping
14881 its last character. This is repeated until the name is short enough.
14883 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14884 to fit the name into 8 characters as required by some operating systems.
14887 our-strings-wide_fixed 22
14888 our strings wide fixed 19
14889 our string wide fixed 18
14890 our strin wide fixed 17
14891 our stri wide fixed 16
14892 our stri wide fixe 15
14893 our str wide fixe 14
14894 our str wid fixe 13
14900 Final file name: oustwifi.adb
14904 The file names for all predefined units are always krunched to eight
14905 characters. The krunching of these predefined units uses the following
14906 special prefix replacements:
14910 replaced by @file{^a^A^-}
14913 replaced by @file{^g^G^-}
14916 replaced by @file{^i^I^-}
14919 replaced by @file{^s^S^-}
14922 These system files have a hyphen in the second character position. That
14923 is why normal user files replace such a character with a
14924 ^tilde^dollar sign^, to
14925 avoid confusion with system file names.
14927 As an example of this special rule, consider
14928 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14931 ada-strings-wide_fixed 22
14932 a- strings wide fixed 18
14933 a- string wide fixed 17
14934 a- strin wide fixed 16
14935 a- stri wide fixed 15
14936 a- stri wide fixe 14
14937 a- str wide fixe 13
14943 Final file name: a-stwifi.adb
14947 Of course no file shortening algorithm can guarantee uniqueness over all
14948 possible unit names, and if file name krunching is used then it is your
14949 responsibility to ensure that no name clashes occur. The utility
14950 program @code{gnatkr} is supplied for conveniently determining the
14951 krunched name of a file.
14953 @node Examples of gnatkr Usage
14954 @section Examples of @code{gnatkr} Usage
14961 $ gnatkr very_long_unit_name.ads --> velounna.ads
14962 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14963 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14964 $ gnatkr grandparent-parent-child --> grparchi
14966 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14967 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14970 @node Preprocessing Using gnatprep
14971 @chapter Preprocessing Using @code{gnatprep}
14975 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14977 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14978 special GNAT features.
14979 For further discussion of conditional compilation in general, see
14980 @ref{Conditional Compilation}.
14983 * Preprocessing Symbols::
14985 * Switches for gnatprep::
14986 * Form of Definitions File::
14987 * Form of Input Text for gnatprep::
14990 @node Preprocessing Symbols
14991 @section Preprocessing Symbols
14994 Preprocessing symbols are defined in definition files and referred to in
14995 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14996 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14997 all characters need to be in the ASCII set (no accented letters).
14999 @node Using gnatprep
15000 @section Using @code{gnatprep}
15003 To call @code{gnatprep} use
15006 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15007 @c Expanding @ovar macro inline (explanation in macro def comments)
15008 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15015 is an optional sequence of switches as described in the next section.
15018 is the full name of the input file, which is an Ada source
15019 file containing preprocessor directives.
15022 is the full name of the output file, which is an Ada source
15023 in standard Ada form. When used with GNAT, this file name will
15024 normally have an ads or adb suffix.
15027 is the full name of a text file containing definitions of
15028 preprocessing symbols to be referenced by the preprocessor. This argument is
15029 optional, and can be replaced by the use of the @option{-D} switch.
15033 @node Switches for gnatprep
15034 @section Switches for @code{gnatprep}
15039 @item ^-b^/BLANK_LINES^
15040 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15041 Causes both preprocessor lines and the lines deleted by
15042 preprocessing to be replaced by blank lines in the output source file,
15043 preserving line numbers in the output file.
15045 @item ^-c^/COMMENTS^
15046 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15047 Causes both preprocessor lines and the lines deleted
15048 by preprocessing to be retained in the output source as comments marked
15049 with the special string @code{"--! "}. This option will result in line numbers
15050 being preserved in the output file.
15052 @item ^-C^/REPLACE_IN_COMMENTS^
15053 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15054 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15055 If this option is specified, then comments are scanned and any $symbol
15056 substitutions performed as in program text. This is particularly useful
15057 when structured comments are used (e.g., when writing programs in the
15058 SPARK dialect of Ada). Note that this switch is not available when
15059 doing integrated preprocessing (it would be useless in this context
15060 since comments are ignored by the compiler in any case).
15062 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15063 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15064 Defines a new preprocessing symbol, associated with value. If no value is given
15065 on the command line, then symbol is considered to be @code{True}. This switch
15066 can be used in place of a definition file.
15070 @cindex @option{/REMOVE} (@command{gnatprep})
15071 This is the default setting which causes lines deleted by preprocessing
15072 to be entirely removed from the output file.
15075 @item ^-r^/REFERENCE^
15076 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15077 Causes a @code{Source_Reference} pragma to be generated that
15078 references the original input file, so that error messages will use
15079 the file name of this original file. The use of this switch implies
15080 that preprocessor lines are not to be removed from the file, so its
15081 use will force @option{^-b^/BLANK_LINES^} mode if
15082 @option{^-c^/COMMENTS^}
15083 has not been specified explicitly.
15085 Note that if the file to be preprocessed contains multiple units, then
15086 it will be necessary to @code{gnatchop} the output file from
15087 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15088 in the preprocessed file, it will be respected by
15089 @code{gnatchop ^-r^/REFERENCE^}
15090 so that the final chopped files will correctly refer to the original
15091 input source file for @code{gnatprep}.
15093 @item ^-s^/SYMBOLS^
15094 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15095 Causes a sorted list of symbol names and values to be
15096 listed on the standard output file.
15098 @item ^-u^/UNDEFINED^
15099 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15100 Causes undefined symbols to be treated as having the value FALSE in the context
15101 of a preprocessor test. In the absence of this option, an undefined symbol in
15102 a @code{#if} or @code{#elsif} test will be treated as an error.
15108 Note: if neither @option{-b} nor @option{-c} is present,
15109 then preprocessor lines and
15110 deleted lines are completely removed from the output, unless -r is
15111 specified, in which case -b is assumed.
15114 @node Form of Definitions File
15115 @section Form of Definitions File
15118 The definitions file contains lines of the form
15125 where symbol is a preprocessing symbol, and value is one of the following:
15129 Empty, corresponding to a null substitution
15131 A string literal using normal Ada syntax
15133 Any sequence of characters from the set
15134 (letters, digits, period, underline).
15138 Comment lines may also appear in the definitions file, starting with
15139 the usual @code{--},
15140 and comments may be added to the definitions lines.
15142 @node Form of Input Text for gnatprep
15143 @section Form of Input Text for @code{gnatprep}
15146 The input text may contain preprocessor conditional inclusion lines,
15147 as well as general symbol substitution sequences.
15149 The preprocessor conditional inclusion commands have the form
15154 #if @i{expression} @r{[}then@r{]}
15156 #elsif @i{expression} @r{[}then@r{]}
15158 #elsif @i{expression} @r{[}then@r{]}
15169 In this example, @i{expression} is defined by the following grammar:
15171 @i{expression} ::= <symbol>
15172 @i{expression} ::= <symbol> = "<value>"
15173 @i{expression} ::= <symbol> = <symbol>
15174 @i{expression} ::= <symbol> 'Defined
15175 @i{expression} ::= not @i{expression}
15176 @i{expression} ::= @i{expression} and @i{expression}
15177 @i{expression} ::= @i{expression} or @i{expression}
15178 @i{expression} ::= @i{expression} and then @i{expression}
15179 @i{expression} ::= @i{expression} or else @i{expression}
15180 @i{expression} ::= ( @i{expression} )
15183 The following restriction exists: it is not allowed to have "and" or "or"
15184 following "not" in the same expression without parentheses. For example, this
15191 This should be one of the following:
15199 For the first test (@i{expression} ::= <symbol>) the symbol must have
15200 either the value true or false, that is to say the right-hand of the
15201 symbol definition must be one of the (case-insensitive) literals
15202 @code{True} or @code{False}. If the value is true, then the
15203 corresponding lines are included, and if the value is false, they are
15206 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15207 the symbol has been defined in the definition file or by a @option{-D}
15208 switch on the command line. Otherwise, the test is false.
15210 The equality tests are case insensitive, as are all the preprocessor lines.
15212 If the symbol referenced is not defined in the symbol definitions file,
15213 then the effect depends on whether or not switch @option{-u}
15214 is specified. If so, then the symbol is treated as if it had the value
15215 false and the test fails. If this switch is not specified, then
15216 it is an error to reference an undefined symbol. It is also an error to
15217 reference a symbol that is defined with a value other than @code{True}
15220 The use of the @code{not} operator inverts the sense of this logical test.
15221 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15222 operators, without parentheses. For example, "if not X or Y then" is not
15223 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15225 The @code{then} keyword is optional as shown
15227 The @code{#} must be the first non-blank character on a line, but
15228 otherwise the format is free form. Spaces or tabs may appear between
15229 the @code{#} and the keyword. The keywords and the symbols are case
15230 insensitive as in normal Ada code. Comments may be used on a
15231 preprocessor line, but other than that, no other tokens may appear on a
15232 preprocessor line. Any number of @code{elsif} clauses can be present,
15233 including none at all. The @code{else} is optional, as in Ada.
15235 The @code{#} marking the start of a preprocessor line must be the first
15236 non-blank character on the line, i.e., it must be preceded only by
15237 spaces or horizontal tabs.
15239 Symbol substitution outside of preprocessor lines is obtained by using
15247 anywhere within a source line, except in a comment or within a
15248 string literal. The identifier
15249 following the @code{$} must match one of the symbols defined in the symbol
15250 definition file, and the result is to substitute the value of the
15251 symbol in place of @code{$symbol} in the output file.
15253 Note that although the substitution of strings within a string literal
15254 is not possible, it is possible to have a symbol whose defined value is
15255 a string literal. So instead of setting XYZ to @code{hello} and writing:
15258 Header : String := "$XYZ";
15262 you should set XYZ to @code{"hello"} and write:
15265 Header : String := $XYZ;
15269 and then the substitution will occur as desired.
15271 @node The GNAT Library Browser gnatls
15272 @chapter The GNAT Library Browser @code{gnatls}
15274 @cindex Library browser
15277 @code{gnatls} is a tool that outputs information about compiled
15278 units. It gives the relationship between objects, unit names and source
15279 files. It can also be used to check the source dependencies of a unit
15280 as well as various characteristics.
15282 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15283 driver (see @ref{The GNAT Driver and Project Files}).
15287 * Switches for gnatls::
15288 * Examples of gnatls Usage::
15291 @node Running gnatls
15292 @section Running @code{gnatls}
15295 The @code{gnatls} command has the form
15298 $ gnatls switches @var{object_or_ali_file}
15302 The main argument is the list of object or @file{ali} files
15303 (@pxref{The Ada Library Information Files})
15304 for which information is requested.
15306 In normal mode, without additional option, @code{gnatls} produces a
15307 four-column listing. Each line represents information for a specific
15308 object. The first column gives the full path of the object, the second
15309 column gives the name of the principal unit in this object, the third
15310 column gives the status of the source and the fourth column gives the
15311 full path of the source representing this unit.
15312 Here is a simple example of use:
15316 ^./^[]^demo1.o demo1 DIF demo1.adb
15317 ^./^[]^demo2.o demo2 OK demo2.adb
15318 ^./^[]^hello.o h1 OK hello.adb
15319 ^./^[]^instr-child.o instr.child MOK instr-child.adb
15320 ^./^[]^instr.o instr OK instr.adb
15321 ^./^[]^tef.o tef DIF tef.adb
15322 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
15323 ^./^[]^tgef.o tgef DIF tgef.adb
15327 The first line can be interpreted as follows: the main unit which is
15329 object file @file{demo1.o} is demo1, whose main source is in
15330 @file{demo1.adb}. Furthermore, the version of the source used for the
15331 compilation of demo1 has been modified (DIF). Each source file has a status
15332 qualifier which can be:
15335 @item OK (unchanged)
15336 The version of the source file used for the compilation of the
15337 specified unit corresponds exactly to the actual source file.
15339 @item MOK (slightly modified)
15340 The version of the source file used for the compilation of the
15341 specified unit differs from the actual source file but not enough to
15342 require recompilation. If you use gnatmake with the qualifier
15343 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15344 MOK will not be recompiled.
15346 @item DIF (modified)
15347 No version of the source found on the path corresponds to the source
15348 used to build this object.
15350 @item ??? (file not found)
15351 No source file was found for this unit.
15353 @item HID (hidden, unchanged version not first on PATH)
15354 The version of the source that corresponds exactly to the source used
15355 for compilation has been found on the path but it is hidden by another
15356 version of the same source that has been modified.
15360 @node Switches for gnatls
15361 @section Switches for @code{gnatls}
15364 @code{gnatls} recognizes the following switches:
15368 @cindex @option{--version} @command{gnatls}
15369 Display Copyright and version, then exit disregarding all other options.
15372 @cindex @option{--help} @command{gnatls}
15373 If @option{--version} was not used, display usage, then exit disregarding
15376 @item ^-a^/ALL_UNITS^
15377 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15378 Consider all units, including those of the predefined Ada library.
15379 Especially useful with @option{^-d^/DEPENDENCIES^}.
15381 @item ^-d^/DEPENDENCIES^
15382 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15383 List sources from which specified units depend on.
15385 @item ^-h^/OUTPUT=OPTIONS^
15386 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15387 Output the list of options.
15389 @item ^-o^/OUTPUT=OBJECTS^
15390 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15391 Only output information about object files.
15393 @item ^-s^/OUTPUT=SOURCES^
15394 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15395 Only output information about source files.
15397 @item ^-u^/OUTPUT=UNITS^
15398 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15399 Only output information about compilation units.
15401 @item ^-files^/FILES^=@var{file}
15402 @cindex @option{^-files^/FILES^} (@code{gnatls})
15403 Take as arguments the files listed in text file @var{file}.
15404 Text file @var{file} may contain empty lines that are ignored.
15405 Each nonempty line should contain the name of an existing file.
15406 Several such switches may be specified simultaneously.
15408 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15409 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15410 @itemx ^-I^/SEARCH=^@var{dir}
15411 @itemx ^-I-^/NOCURRENT_DIRECTORY^
15413 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15414 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15415 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15416 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15417 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15418 flags (@pxref{Switches for gnatmake}).
15420 @item --RTS=@var{rts-path}
15421 @cindex @option{--RTS} (@code{gnatls})
15422 Specifies the default location of the runtime library. Same meaning as the
15423 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15425 @item ^-v^/OUTPUT=VERBOSE^
15426 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15427 Verbose mode. Output the complete source, object and project paths. Do not use
15428 the default column layout but instead use long format giving as much as
15429 information possible on each requested units, including special
15430 characteristics such as:
15433 @item Preelaborable
15434 The unit is preelaborable in the Ada sense.
15437 No elaboration code has been produced by the compiler for this unit.
15440 The unit is pure in the Ada sense.
15442 @item Elaborate_Body
15443 The unit contains a pragma Elaborate_Body.
15446 The unit contains a pragma Remote_Types.
15448 @item Shared_Passive
15449 The unit contains a pragma Shared_Passive.
15452 This unit is part of the predefined environment and cannot be modified
15455 @item Remote_Call_Interface
15456 The unit contains a pragma Remote_Call_Interface.
15462 @node Examples of gnatls Usage
15463 @section Example of @code{gnatls} Usage
15467 Example of using the verbose switch. Note how the source and
15468 object paths are affected by the -I switch.
15471 $ gnatls -v -I.. demo1.o
15473 GNATLS 5.03w (20041123-34)
15474 Copyright 1997-2004 Free Software Foundation, Inc.
15476 Source Search Path:
15477 <Current_Directory>
15479 /home/comar/local/adainclude/
15481 Object Search Path:
15482 <Current_Directory>
15484 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15486 Project Search Path:
15487 <Current_Directory>
15488 /home/comar/local/lib/gnat/
15493 Kind => subprogram body
15494 Flags => No_Elab_Code
15495 Source => demo1.adb modified
15499 The following is an example of use of the dependency list.
15500 Note the use of the -s switch
15501 which gives a straight list of source files. This can be useful for
15502 building specialized scripts.
15505 $ gnatls -d demo2.o
15506 ./demo2.o demo2 OK demo2.adb
15512 $ gnatls -d -s -a demo1.o
15514 /home/comar/local/adainclude/ada.ads
15515 /home/comar/local/adainclude/a-finali.ads
15516 /home/comar/local/adainclude/a-filico.ads
15517 /home/comar/local/adainclude/a-stream.ads
15518 /home/comar/local/adainclude/a-tags.ads
15521 /home/comar/local/adainclude/gnat.ads
15522 /home/comar/local/adainclude/g-io.ads
15524 /home/comar/local/adainclude/system.ads
15525 /home/comar/local/adainclude/s-exctab.ads
15526 /home/comar/local/adainclude/s-finimp.ads
15527 /home/comar/local/adainclude/s-finroo.ads
15528 /home/comar/local/adainclude/s-secsta.ads
15529 /home/comar/local/adainclude/s-stalib.ads
15530 /home/comar/local/adainclude/s-stoele.ads
15531 /home/comar/local/adainclude/s-stratt.ads
15532 /home/comar/local/adainclude/s-tasoli.ads
15533 /home/comar/local/adainclude/s-unstyp.ads
15534 /home/comar/local/adainclude/unchconv.ads
15540 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15542 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15543 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15544 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15545 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15546 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15550 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15551 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15553 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15554 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15555 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15556 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15557 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15558 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15559 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15560 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15561 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15562 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15563 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15567 @node Cleaning Up Using gnatclean
15568 @chapter Cleaning Up Using @code{gnatclean}
15570 @cindex Cleaning tool
15573 @code{gnatclean} is a tool that allows the deletion of files produced by the
15574 compiler, binder and linker, including ALI files, object files, tree files,
15575 expanded source files, library files, interface copy source files, binder
15576 generated files and executable files.
15579 * Running gnatclean::
15580 * Switches for gnatclean::
15581 @c * Examples of gnatclean Usage::
15584 @node Running gnatclean
15585 @section Running @code{gnatclean}
15588 The @code{gnatclean} command has the form:
15591 $ gnatclean switches @var{names}
15595 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15596 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15597 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15600 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15601 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15602 the linker. In informative-only mode, specified by switch
15603 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15604 normal mode is listed, but no file is actually deleted.
15606 @node Switches for gnatclean
15607 @section Switches for @code{gnatclean}
15610 @code{gnatclean} recognizes the following switches:
15614 @cindex @option{--version} @command{gnatclean}
15615 Display Copyright and version, then exit disregarding all other options.
15618 @cindex @option{--help} @command{gnatclean}
15619 If @option{--version} was not used, display usage, then exit disregarding
15622 @item ^--subdirs^/SUBDIRS^=subdir
15623 Actual object directory of each project file is the subdirectory subdir of the
15624 object directory specified or defaulted in the project file.
15626 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15627 By default, shared library projects are not allowed to import static library
15628 projects. When this switch is used on the command line, this restriction is
15631 @item ^-c^/COMPILER_FILES_ONLY^
15632 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15633 Only attempt to delete the files produced by the compiler, not those produced
15634 by the binder or the linker. The files that are not to be deleted are library
15635 files, interface copy files, binder generated files and executable files.
15637 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15638 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15639 Indicate that ALI and object files should normally be found in directory
15642 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15643 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15644 When using project files, if some errors or warnings are detected during
15645 parsing and verbose mode is not in effect (no use of switch
15646 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15647 file, rather than its simple file name.
15650 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15651 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15653 @item ^-n^/NODELETE^
15654 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15655 Informative-only mode. Do not delete any files. Output the list of the files
15656 that would have been deleted if this switch was not specified.
15658 @item ^-P^/PROJECT_FILE=^@var{project}
15659 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15660 Use project file @var{project}. Only one such switch can be used.
15661 When cleaning a project file, the files produced by the compilation of the
15662 immediate sources or inherited sources of the project files are to be
15663 deleted. This is not depending on the presence or not of executable names
15664 on the command line.
15667 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15668 Quiet output. If there are no errors, do not output anything, except in
15669 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15670 (switch ^-n^/NODELETE^).
15672 @item ^-r^/RECURSIVE^
15673 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15674 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15675 clean all imported and extended project files, recursively. If this switch
15676 is not specified, only the files related to the main project file are to be
15677 deleted. This switch has no effect if no project file is specified.
15679 @item ^-v^/VERBOSE^
15680 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15683 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15684 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15685 Indicates the verbosity of the parsing of GNAT project files.
15686 @xref{Switches Related to Project Files}.
15688 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15689 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15690 Indicates that external variable @var{name} has the value @var{value}.
15691 The Project Manager will use this value for occurrences of
15692 @code{external(name)} when parsing the project file.
15693 @xref{Switches Related to Project Files}.
15695 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15696 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15697 When searching for ALI and object files, look in directory
15700 @item ^-I^/SEARCH=^@var{dir}
15701 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15702 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15704 @item ^-I-^/NOCURRENT_DIRECTORY^
15705 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15706 @cindex Source files, suppressing search
15707 Do not look for ALI or object files in the directory
15708 where @code{gnatclean} was invoked.
15712 @c @node Examples of gnatclean Usage
15713 @c @section Examples of @code{gnatclean} Usage
15716 @node GNAT and Libraries
15717 @chapter GNAT and Libraries
15718 @cindex Library, building, installing, using
15721 This chapter describes how to build and use libraries with GNAT, and also shows
15722 how to recompile the GNAT run-time library. You should be familiar with the
15723 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15727 * Introduction to Libraries in GNAT::
15728 * General Ada Libraries::
15729 * Stand-alone Ada Libraries::
15730 * Rebuilding the GNAT Run-Time Library::
15733 @node Introduction to Libraries in GNAT
15734 @section Introduction to Libraries in GNAT
15737 A library is, conceptually, a collection of objects which does not have its
15738 own main thread of execution, but rather provides certain services to the
15739 applications that use it. A library can be either statically linked with the
15740 application, in which case its code is directly included in the application,
15741 or, on platforms that support it, be dynamically linked, in which case
15742 its code is shared by all applications making use of this library.
15744 GNAT supports both types of libraries.
15745 In the static case, the compiled code can be provided in different ways. The
15746 simplest approach is to provide directly the set of objects resulting from
15747 compilation of the library source files. Alternatively, you can group the
15748 objects into an archive using whatever commands are provided by the operating
15749 system. For the latter case, the objects are grouped into a shared library.
15751 In the GNAT environment, a library has three types of components:
15757 @xref{The Ada Library Information Files}.
15759 Object files, an archive or a shared library.
15763 A GNAT library may expose all its source files, which is useful for
15764 documentation purposes. Alternatively, it may expose only the units needed by
15765 an external user to make use of the library. That is to say, the specs
15766 reflecting the library services along with all the units needed to compile
15767 those specs, which can include generic bodies or any body implementing an
15768 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15769 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15771 All compilation units comprising an application, including those in a library,
15772 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15773 computes the elaboration order from the @file{ALI} files and this is why they
15774 constitute a mandatory part of GNAT libraries.
15775 @emph{Stand-alone libraries} are the exception to this rule because a specific
15776 library elaboration routine is produced independently of the application(s)
15779 @node General Ada Libraries
15780 @section General Ada Libraries
15783 * Building a library::
15784 * Installing a library::
15785 * Using a library::
15788 @node Building a library
15789 @subsection Building a library
15792 The easiest way to build a library is to use the Project Manager,
15793 which supports a special type of project called a @emph{Library Project}
15794 (@pxref{Library Projects}).
15796 A project is considered a library project, when two project-level attributes
15797 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15798 control different aspects of library configuration, additional optional
15799 project-level attributes can be specified:
15802 This attribute controls whether the library is to be static or dynamic
15804 @item Library_Version
15805 This attribute specifies the library version; this value is used
15806 during dynamic linking of shared libraries to determine if the currently
15807 installed versions of the binaries are compatible.
15809 @item Library_Options
15811 These attributes specify additional low-level options to be used during
15812 library generation, and redefine the actual application used to generate
15817 The GNAT Project Manager takes full care of the library maintenance task,
15818 including recompilation of the source files for which objects do not exist
15819 or are not up to date, assembly of the library archive, and installation of
15820 the library (i.e., copying associated source, object and @file{ALI} files
15821 to the specified location).
15823 Here is a simple library project file:
15824 @smallexample @c ada
15826 for Source_Dirs use ("src1", "src2");
15827 for Object_Dir use "obj";
15828 for Library_Name use "mylib";
15829 for Library_Dir use "lib";
15830 for Library_Kind use "dynamic";
15835 and the compilation command to build and install the library:
15837 @smallexample @c ada
15838 $ gnatmake -Pmy_lib
15842 It is not entirely trivial to perform manually all the steps required to
15843 produce a library. We recommend that you use the GNAT Project Manager
15844 for this task. In special cases where this is not desired, the necessary
15845 steps are discussed below.
15847 There are various possibilities for compiling the units that make up the
15848 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15849 with a conventional script. For simple libraries, it is also possible to create
15850 a dummy main program which depends upon all the packages that comprise the
15851 interface of the library. This dummy main program can then be given to
15852 @command{gnatmake}, which will ensure that all necessary objects are built.
15854 After this task is accomplished, you should follow the standard procedure
15855 of the underlying operating system to produce the static or shared library.
15857 Here is an example of such a dummy program:
15858 @smallexample @c ada
15860 with My_Lib.Service1;
15861 with My_Lib.Service2;
15862 with My_Lib.Service3;
15863 procedure My_Lib_Dummy is
15871 Here are the generic commands that will build an archive or a shared library.
15874 # compiling the library
15875 $ gnatmake -c my_lib_dummy.adb
15877 # we don't need the dummy object itself
15878 $ rm my_lib_dummy.o my_lib_dummy.ali
15880 # create an archive with the remaining objects
15881 $ ar rc libmy_lib.a *.o
15882 # some systems may require "ranlib" to be run as well
15884 # or create a shared library
15885 $ gcc -shared -o libmy_lib.so *.o
15886 # some systems may require the code to have been compiled with -fPIC
15888 # remove the object files that are now in the library
15891 # Make the ALI files read-only so that gnatmake will not try to
15892 # regenerate the objects that are in the library
15897 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15898 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15899 be accessed by the directive @option{-l@var{xxx}} at link time.
15901 @node Installing a library
15902 @subsection Installing a library
15903 @cindex @code{ADA_PROJECT_PATH}
15904 @cindex @code{GPR_PROJECT_PATH}
15907 If you use project files, library installation is part of the library build
15908 process (@pxref{Installing a library with project files}).
15910 When project files are not an option, it is also possible, but not recommended,
15911 to install the library so that the sources needed to use the library are on the
15912 Ada source path and the ALI files & libraries be on the Ada Object path (see
15913 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15914 administrator can place general-purpose libraries in the default compiler
15915 paths, by specifying the libraries' location in the configuration files
15916 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15917 must be located in the GNAT installation tree at the same place as the gcc spec
15918 file. The location of the gcc spec file can be determined as follows:
15924 The configuration files mentioned above have a simple format: each line
15925 must contain one unique directory name.
15926 Those names are added to the corresponding path
15927 in their order of appearance in the file. The names can be either absolute
15928 or relative; in the latter case, they are relative to where theses files
15931 The files @file{ada_source_path} and @file{ada_object_path} might not be
15933 GNAT installation, in which case, GNAT will look for its run-time library in
15934 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15935 objects and @file{ALI} files). When the files exist, the compiler does not
15936 look in @file{adainclude} and @file{adalib}, and thus the
15937 @file{ada_source_path} file
15938 must contain the location for the GNAT run-time sources (which can simply
15939 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15940 contain the location for the GNAT run-time objects (which can simply
15943 You can also specify a new default path to the run-time library at compilation
15944 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15945 the run-time library you want your program to be compiled with. This switch is
15946 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15947 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15949 It is possible to install a library before or after the standard GNAT
15950 library, by reordering the lines in the configuration files. In general, a
15951 library must be installed before the GNAT library if it redefines
15954 @node Using a library
15955 @subsection Using a library
15957 @noindent Once again, the project facility greatly simplifies the use of
15958 libraries. In this context, using a library is just a matter of adding a
15959 @code{with} clause in the user project. For instance, to make use of the
15960 library @code{My_Lib} shown in examples in earlier sections, you can
15963 @smallexample @c projectfile
15970 Even if you have a third-party, non-Ada library, you can still use GNAT's
15971 Project Manager facility to provide a wrapper for it. For example, the
15972 following project, when @code{with}ed by your main project, will link with the
15973 third-party library @file{liba.a}:
15975 @smallexample @c projectfile
15978 for Externally_Built use "true";
15979 for Source_Files use ();
15980 for Library_Dir use "lib";
15981 for Library_Name use "a";
15982 for Library_Kind use "static";
15986 This is an alternative to the use of @code{pragma Linker_Options}. It is
15987 especially interesting in the context of systems with several interdependent
15988 static libraries where finding a proper linker order is not easy and best be
15989 left to the tools having visibility over project dependence information.
15992 In order to use an Ada library manually, you need to make sure that this
15993 library is on both your source and object path
15994 (see @ref{Search Paths and the Run-Time Library (RTL)}
15995 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15996 in an archive or a shared library, you need to specify the desired
15997 library at link time.
15999 For example, you can use the library @file{mylib} installed in
16000 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16003 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16008 This can be expressed more simply:
16013 when the following conditions are met:
16016 @file{/dir/my_lib_src} has been added by the user to the environment
16017 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16018 @file{ada_source_path}
16020 @file{/dir/my_lib_obj} has been added by the user to the environment
16021 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16022 @file{ada_object_path}
16024 a pragma @code{Linker_Options} has been added to one of the sources.
16027 @smallexample @c ada
16028 pragma Linker_Options ("-lmy_lib");
16032 @node Stand-alone Ada Libraries
16033 @section Stand-alone Ada Libraries
16034 @cindex Stand-alone library, building, using
16037 * Introduction to Stand-alone Libraries::
16038 * Building a Stand-alone Library::
16039 * Creating a Stand-alone Library to be used in a non-Ada context::
16040 * Restrictions in Stand-alone Libraries::
16043 @node Introduction to Stand-alone Libraries
16044 @subsection Introduction to Stand-alone Libraries
16047 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16049 elaborate the Ada units that are included in the library. In contrast with
16050 an ordinary library, which consists of all sources, objects and @file{ALI}
16052 library, a SAL may specify a restricted subset of compilation units
16053 to serve as a library interface. In this case, the fully
16054 self-sufficient set of files will normally consist of an objects
16055 archive, the sources of interface units' specs, and the @file{ALI}
16056 files of interface units.
16057 If an interface spec contains a generic unit or an inlined subprogram,
16059 source must also be provided; if the units that must be provided in the source
16060 form depend on other units, the source and @file{ALI} files of those must
16063 The main purpose of a SAL is to minimize the recompilation overhead of client
16064 applications when a new version of the library is installed. Specifically,
16065 if the interface sources have not changed, client applications do not need to
16066 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16067 version, controlled by @code{Library_Version} attribute, is not changed,
16068 then the clients do not need to be relinked.
16070 SALs also allow the library providers to minimize the amount of library source
16071 text exposed to the clients. Such ``information hiding'' might be useful or
16072 necessary for various reasons.
16074 Stand-alone libraries are also well suited to be used in an executable whose
16075 main routine is not written in Ada.
16077 @node Building a Stand-alone Library
16078 @subsection Building a Stand-alone Library
16081 GNAT's Project facility provides a simple way of building and installing
16082 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16083 To be a Stand-alone Library Project, in addition to the two attributes
16084 that make a project a Library Project (@code{Library_Name} and
16085 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16086 @code{Library_Interface} must be defined. For example:
16088 @smallexample @c projectfile
16090 for Library_Dir use "lib_dir";
16091 for Library_Name use "dummy";
16092 for Library_Interface use ("int1", "int1.child");
16097 Attribute @code{Library_Interface} has a non-empty string list value,
16098 each string in the list designating a unit contained in an immediate source
16099 of the project file.
16101 When a Stand-alone Library is built, first the binder is invoked to build
16102 a package whose name depends on the library name
16103 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16104 This binder-generated package includes initialization and
16105 finalization procedures whose
16106 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16108 above). The object corresponding to this package is included in the library.
16110 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16111 calling of these procedures if a static SAL is built, or if a shared SAL
16113 with the project-level attribute @code{Library_Auto_Init} set to
16116 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16117 (those that are listed in attribute @code{Library_Interface}) are copied to
16118 the Library Directory. As a consequence, only the Interface Units may be
16119 imported from Ada units outside of the library. If other units are imported,
16120 the binding phase will fail.
16122 The attribute @code{Library_Src_Dir} may be specified for a
16123 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16124 single string value. Its value must be the path (absolute or relative to the
16125 project directory) of an existing directory. This directory cannot be the
16126 object directory or one of the source directories, but it can be the same as
16127 the library directory. The sources of the Interface
16128 Units of the library that are needed by an Ada client of the library will be
16129 copied to the designated directory, called the Interface Copy directory.
16130 These sources include the specs of the Interface Units, but they may also
16131 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16132 are used, or when there is a generic unit in the spec. Before the sources
16133 are copied to the Interface Copy directory, an attempt is made to delete all
16134 files in the Interface Copy directory.
16136 Building stand-alone libraries by hand is somewhat tedious, but for those
16137 occasions when it is necessary here are the steps that you need to perform:
16140 Compile all library sources.
16143 Invoke the binder with the switch @option{-n} (No Ada main program),
16144 with all the @file{ALI} files of the interfaces, and
16145 with the switch @option{-L} to give specific names to the @code{init}
16146 and @code{final} procedures. For example:
16148 gnatbind -n int1.ali int2.ali -Lsal1
16152 Compile the binder generated file:
16158 Link the dynamic library with all the necessary object files,
16159 indicating to the linker the names of the @code{init} (and possibly
16160 @code{final}) procedures for automatic initialization (and finalization).
16161 The built library should be placed in a directory different from
16162 the object directory.
16165 Copy the @code{ALI} files of the interface to the library directory,
16166 add in this copy an indication that it is an interface to a SAL
16167 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16168 with letter ``P'') and make the modified copy of the @file{ALI} file
16173 Using SALs is not different from using other libraries
16174 (see @ref{Using a library}).
16176 @node Creating a Stand-alone Library to be used in a non-Ada context
16177 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16180 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16183 The only extra step required is to ensure that library interface subprograms
16184 are compatible with the main program, by means of @code{pragma Export}
16185 or @code{pragma Convention}.
16187 Here is an example of simple library interface for use with C main program:
16189 @smallexample @c ada
16190 package My_Package is
16192 procedure Do_Something;
16193 pragma Export (C, Do_Something, "do_something");
16195 procedure Do_Something_Else;
16196 pragma Export (C, Do_Something_Else, "do_something_else");
16202 On the foreign language side, you must provide a ``foreign'' view of the
16203 library interface; remember that it should contain elaboration routines in
16204 addition to interface subprograms.
16206 The example below shows the content of @code{mylib_interface.h} (note
16207 that there is no rule for the naming of this file, any name can be used)
16209 /* the library elaboration procedure */
16210 extern void mylibinit (void);
16212 /* the library finalization procedure */
16213 extern void mylibfinal (void);
16215 /* the interface exported by the library */
16216 extern void do_something (void);
16217 extern void do_something_else (void);
16221 Libraries built as explained above can be used from any program, provided
16222 that the elaboration procedures (named @code{mylibinit} in the previous
16223 example) are called before the library services are used. Any number of
16224 libraries can be used simultaneously, as long as the elaboration
16225 procedure of each library is called.
16227 Below is an example of a C program that uses the @code{mylib} library.
16230 #include "mylib_interface.h"
16235 /* First, elaborate the library before using it */
16238 /* Main program, using the library exported entities */
16240 do_something_else ();
16242 /* Library finalization at the end of the program */
16249 Note that invoking any library finalization procedure generated by
16250 @code{gnatbind} shuts down the Ada run-time environment.
16252 finalization of all Ada libraries must be performed at the end of the program.
16253 No call to these libraries or to the Ada run-time library should be made
16254 after the finalization phase.
16256 @node Restrictions in Stand-alone Libraries
16257 @subsection Restrictions in Stand-alone Libraries
16260 The pragmas listed below should be used with caution inside libraries,
16261 as they can create incompatibilities with other Ada libraries:
16263 @item pragma @code{Locking_Policy}
16264 @item pragma @code{Queuing_Policy}
16265 @item pragma @code{Task_Dispatching_Policy}
16266 @item pragma @code{Unreserve_All_Interrupts}
16270 When using a library that contains such pragmas, the user must make sure
16271 that all libraries use the same pragmas with the same values. Otherwise,
16272 @code{Program_Error} will
16273 be raised during the elaboration of the conflicting
16274 libraries. The usage of these pragmas and its consequences for the user
16275 should therefore be well documented.
16277 Similarly, the traceback in the exception occurrence mechanism should be
16278 enabled or disabled in a consistent manner across all libraries.
16279 Otherwise, Program_Error will be raised during the elaboration of the
16280 conflicting libraries.
16282 If the @code{Version} or @code{Body_Version}
16283 attributes are used inside a library, then you need to
16284 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16285 libraries, so that version identifiers can be properly computed.
16286 In practice these attributes are rarely used, so this is unlikely
16287 to be a consideration.
16289 @node Rebuilding the GNAT Run-Time Library
16290 @section Rebuilding the GNAT Run-Time Library
16291 @cindex GNAT Run-Time Library, rebuilding
16292 @cindex Building the GNAT Run-Time Library
16293 @cindex Rebuilding the GNAT Run-Time Library
16294 @cindex Run-Time Library, rebuilding
16297 It may be useful to recompile the GNAT library in various contexts, the
16298 most important one being the use of partition-wide configuration pragmas
16299 such as @code{Normalize_Scalars}. A special Makefile called
16300 @code{Makefile.adalib} is provided to that effect and can be found in
16301 the directory containing the GNAT library. The location of this
16302 directory depends on the way the GNAT environment has been installed and can
16303 be determined by means of the command:
16310 The last entry in the object search path usually contains the
16311 gnat library. This Makefile contains its own documentation and in
16312 particular the set of instructions needed to rebuild a new library and
16315 @node Using the GNU make Utility
16316 @chapter Using the GNU @code{make} Utility
16320 This chapter offers some examples of makefiles that solve specific
16321 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16322 make, make, GNU @code{make}}), nor does it try to replace the
16323 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16325 All the examples in this section are specific to the GNU version of
16326 make. Although @command{make} is a standard utility, and the basic language
16327 is the same, these examples use some advanced features found only in
16331 * Using gnatmake in a Makefile::
16332 * Automatically Creating a List of Directories::
16333 * Generating the Command Line Switches::
16334 * Overcoming Command Line Length Limits::
16337 @node Using gnatmake in a Makefile
16338 @section Using gnatmake in a Makefile
16343 Complex project organizations can be handled in a very powerful way by
16344 using GNU make combined with gnatmake. For instance, here is a Makefile
16345 which allows you to build each subsystem of a big project into a separate
16346 shared library. Such a makefile allows you to significantly reduce the link
16347 time of very big applications while maintaining full coherence at
16348 each step of the build process.
16350 The list of dependencies are handled automatically by
16351 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16352 the appropriate directories.
16354 Note that you should also read the example on how to automatically
16355 create the list of directories
16356 (@pxref{Automatically Creating a List of Directories})
16357 which might help you in case your project has a lot of subdirectories.
16362 @font@heightrm=cmr8
16365 ## This Makefile is intended to be used with the following directory
16367 ## - The sources are split into a series of csc (computer software components)
16368 ## Each of these csc is put in its own directory.
16369 ## Their name are referenced by the directory names.
16370 ## They will be compiled into shared library (although this would also work
16371 ## with static libraries
16372 ## - The main program (and possibly other packages that do not belong to any
16373 ## csc is put in the top level directory (where the Makefile is).
16374 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16375 ## \_ second_csc (sources) __ lib (will contain the library)
16377 ## Although this Makefile is build for shared library, it is easy to modify
16378 ## to build partial link objects instead (modify the lines with -shared and
16381 ## With this makefile, you can change any file in the system or add any new
16382 ## file, and everything will be recompiled correctly (only the relevant shared
16383 ## objects will be recompiled, and the main program will be re-linked).
16385 # The list of computer software component for your project. This might be
16386 # generated automatically.
16389 # Name of the main program (no extension)
16392 # If we need to build objects with -fPIC, uncomment the following line
16395 # The following variable should give the directory containing libgnat.so
16396 # You can get this directory through 'gnatls -v'. This is usually the last
16397 # directory in the Object_Path.
16400 # The directories for the libraries
16401 # (This macro expands the list of CSC to the list of shared libraries, you
16402 # could simply use the expanded form:
16403 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16404 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16406 $@{MAIN@}: objects $@{LIB_DIR@}
16407 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16408 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16411 # recompile the sources
16412 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16414 # Note: In a future version of GNAT, the following commands will be simplified
16415 # by a new tool, gnatmlib
16417 mkdir -p $@{dir $@@ @}
16418 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16419 cd $@{dir $@@ @} && cp -f ../*.ali .
16421 # The dependencies for the modules
16422 # Note that we have to force the expansion of *.o, since in some cases
16423 # make won't be able to do it itself.
16424 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16425 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16426 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16428 # Make sure all of the shared libraries are in the path before starting the
16431 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16434 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16435 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16436 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16437 $@{RM@} *.o *.ali $@{MAIN@}
16440 @node Automatically Creating a List of Directories
16441 @section Automatically Creating a List of Directories
16444 In most makefiles, you will have to specify a list of directories, and
16445 store it in a variable. For small projects, it is often easier to
16446 specify each of them by hand, since you then have full control over what
16447 is the proper order for these directories, which ones should be
16450 However, in larger projects, which might involve hundreds of
16451 subdirectories, it might be more convenient to generate this list
16454 The example below presents two methods. The first one, although less
16455 general, gives you more control over the list. It involves wildcard
16456 characters, that are automatically expanded by @command{make}. Its
16457 shortcoming is that you need to explicitly specify some of the
16458 organization of your project, such as for instance the directory tree
16459 depth, whether some directories are found in a separate tree, @enddots{}
16461 The second method is the most general one. It requires an external
16462 program, called @command{find}, which is standard on all Unix systems. All
16463 the directories found under a given root directory will be added to the
16469 @font@heightrm=cmr8
16472 # The examples below are based on the following directory hierarchy:
16473 # All the directories can contain any number of files
16474 # ROOT_DIRECTORY -> a -> aa -> aaa
16477 # -> b -> ba -> baa
16480 # This Makefile creates a variable called DIRS, that can be reused any time
16481 # you need this list (see the other examples in this section)
16483 # The root of your project's directory hierarchy
16487 # First method: specify explicitly the list of directories
16488 # This allows you to specify any subset of all the directories you need.
16491 DIRS := a/aa/ a/ab/ b/ba/
16494 # Second method: use wildcards
16495 # Note that the argument(s) to wildcard below should end with a '/'.
16496 # Since wildcards also return file names, we have to filter them out
16497 # to avoid duplicate directory names.
16498 # We thus use make's @code{dir} and @code{sort} functions.
16499 # It sets DIRs to the following value (note that the directories aaa and baa
16500 # are not given, unless you change the arguments to wildcard).
16501 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16504 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16505 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16508 # Third method: use an external program
16509 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16510 # This is the most complete command: it sets DIRs to the following value:
16511 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16514 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16518 @node Generating the Command Line Switches
16519 @section Generating the Command Line Switches
16522 Once you have created the list of directories as explained in the
16523 previous section (@pxref{Automatically Creating a List of Directories}),
16524 you can easily generate the command line arguments to pass to gnatmake.
16526 For the sake of completeness, this example assumes that the source path
16527 is not the same as the object path, and that you have two separate lists
16531 # see "Automatically creating a list of directories" to create
16536 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16537 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16540 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16543 @node Overcoming Command Line Length Limits
16544 @section Overcoming Command Line Length Limits
16547 One problem that might be encountered on big projects is that many
16548 operating systems limit the length of the command line. It is thus hard to give
16549 gnatmake the list of source and object directories.
16551 This example shows how you can set up environment variables, which will
16552 make @command{gnatmake} behave exactly as if the directories had been
16553 specified on the command line, but have a much higher length limit (or
16554 even none on most systems).
16556 It assumes that you have created a list of directories in your Makefile,
16557 using one of the methods presented in
16558 @ref{Automatically Creating a List of Directories}.
16559 For the sake of completeness, we assume that the object
16560 path (where the ALI files are found) is different from the sources patch.
16562 Note a small trick in the Makefile below: for efficiency reasons, we
16563 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16564 expanded immediately by @code{make}. This way we overcome the standard
16565 make behavior which is to expand the variables only when they are
16568 On Windows, if you are using the standard Windows command shell, you must
16569 replace colons with semicolons in the assignments to these variables.
16574 @font@heightrm=cmr8
16577 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16578 # This is the same thing as putting the -I arguments on the command line.
16579 # (the equivalent of using -aI on the command line would be to define
16580 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16581 # You can of course have different values for these variables.
16583 # Note also that we need to keep the previous values of these variables, since
16584 # they might have been set before running 'make' to specify where the GNAT
16585 # library is installed.
16587 # see "Automatically creating a list of directories" to create these
16593 space:=$@{empty@} $@{empty@}
16594 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16595 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16596 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16597 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16598 export ADA_INCLUDE_PATH
16599 export ADA_OBJECTS_PATH
16606 @node Memory Management Issues
16607 @chapter Memory Management Issues
16610 This chapter describes some useful memory pools provided in the GNAT library
16611 and in particular the GNAT Debug Pool facility, which can be used to detect
16612 incorrect uses of access values (including ``dangling references'').
16614 It also describes the @command{gnatmem} tool, which can be used to track down
16619 * Some Useful Memory Pools::
16620 * The GNAT Debug Pool Facility::
16622 * The gnatmem Tool::
16626 @node Some Useful Memory Pools
16627 @section Some Useful Memory Pools
16628 @findex Memory Pool
16629 @cindex storage, pool
16632 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16633 storage pool. Allocations use the standard system call @code{malloc} while
16634 deallocations use the standard system call @code{free}. No reclamation is
16635 performed when the pool goes out of scope. For performance reasons, the
16636 standard default Ada allocators/deallocators do not use any explicit storage
16637 pools but if they did, they could use this storage pool without any change in
16638 behavior. That is why this storage pool is used when the user
16639 manages to make the default implicit allocator explicit as in this example:
16640 @smallexample @c ada
16641 type T1 is access Something;
16642 -- no Storage pool is defined for T2
16643 type T2 is access Something_Else;
16644 for T2'Storage_Pool use T1'Storage_Pool;
16645 -- the above is equivalent to
16646 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16650 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16651 pool. The allocation strategy is similar to @code{Pool_Local}'s
16652 except that the all
16653 storage allocated with this pool is reclaimed when the pool object goes out of
16654 scope. This pool provides a explicit mechanism similar to the implicit one
16655 provided by several Ada 83 compilers for allocations performed through a local
16656 access type and whose purpose was to reclaim memory when exiting the
16657 scope of a given local access. As an example, the following program does not
16658 leak memory even though it does not perform explicit deallocation:
16660 @smallexample @c ada
16661 with System.Pool_Local;
16662 procedure Pooloc1 is
16663 procedure Internal is
16664 type A is access Integer;
16665 X : System.Pool_Local.Unbounded_Reclaim_Pool;
16666 for A'Storage_Pool use X;
16669 for I in 1 .. 50 loop
16674 for I in 1 .. 100 loop
16681 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16682 @code{Storage_Size} is specified for an access type.
16683 The whole storage for the pool is
16684 allocated at once, usually on the stack at the point where the access type is
16685 elaborated. It is automatically reclaimed when exiting the scope where the
16686 access type is defined. This package is not intended to be used directly by the
16687 user and it is implicitly used for each such declaration:
16689 @smallexample @c ada
16690 type T1 is access Something;
16691 for T1'Storage_Size use 10_000;
16694 @node The GNAT Debug Pool Facility
16695 @section The GNAT Debug Pool Facility
16697 @cindex storage, pool, memory corruption
16700 The use of unchecked deallocation and unchecked conversion can easily
16701 lead to incorrect memory references. The problems generated by such
16702 references are usually difficult to tackle because the symptoms can be
16703 very remote from the origin of the problem. In such cases, it is
16704 very helpful to detect the problem as early as possible. This is the
16705 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16707 In order to use the GNAT specific debugging pool, the user must
16708 associate a debug pool object with each of the access types that may be
16709 related to suspected memory problems. See Ada Reference Manual 13.11.
16710 @smallexample @c ada
16711 type Ptr is access Some_Type;
16712 Pool : GNAT.Debug_Pools.Debug_Pool;
16713 for Ptr'Storage_Pool use Pool;
16717 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16718 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16719 allow the user to redefine allocation and deallocation strategies. They
16720 also provide a checkpoint for each dereference, through the use of
16721 the primitive operation @code{Dereference} which is implicitly called at
16722 each dereference of an access value.
16724 Once an access type has been associated with a debug pool, operations on
16725 values of the type may raise four distinct exceptions,
16726 which correspond to four potential kinds of memory corruption:
16729 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16731 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16733 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16735 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16739 For types associated with a Debug_Pool, dynamic allocation is performed using
16740 the standard GNAT allocation routine. References to all allocated chunks of
16741 memory are kept in an internal dictionary. Several deallocation strategies are
16742 provided, whereupon the user can choose to release the memory to the system,
16743 keep it allocated for further invalid access checks, or fill it with an easily
16744 recognizable pattern for debug sessions. The memory pattern is the old IBM
16745 hexadecimal convention: @code{16#DEADBEEF#}.
16747 See the documentation in the file g-debpoo.ads for more information on the
16748 various strategies.
16750 Upon each dereference, a check is made that the access value denotes a
16751 properly allocated memory location. Here is a complete example of use of
16752 @code{Debug_Pools}, that includes typical instances of memory corruption:
16753 @smallexample @c ada
16757 with Gnat.Io; use Gnat.Io;
16758 with Unchecked_Deallocation;
16759 with Unchecked_Conversion;
16760 with GNAT.Debug_Pools;
16761 with System.Storage_Elements;
16762 with Ada.Exceptions; use Ada.Exceptions;
16763 procedure Debug_Pool_Test is
16765 type T is access Integer;
16766 type U is access all T;
16768 P : GNAT.Debug_Pools.Debug_Pool;
16769 for T'Storage_Pool use P;
16771 procedure Free is new Unchecked_Deallocation (Integer, T);
16772 function UC is new Unchecked_Conversion (U, T);
16775 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16785 Put_Line (Integer'Image(B.all));
16787 when E : others => Put_Line ("raised: " & Exception_Name (E));
16792 when E : others => Put_Line ("raised: " & Exception_Name (E));
16796 Put_Line (Integer'Image(B.all));
16798 when E : others => Put_Line ("raised: " & Exception_Name (E));
16803 when E : others => Put_Line ("raised: " & Exception_Name (E));
16806 end Debug_Pool_Test;
16810 The debug pool mechanism provides the following precise diagnostics on the
16811 execution of this erroneous program:
16814 Total allocated bytes : 0
16815 Total deallocated bytes : 0
16816 Current Water Mark: 0
16820 Total allocated bytes : 8
16821 Total deallocated bytes : 0
16822 Current Water Mark: 8
16825 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16826 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16827 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16828 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16830 Total allocated bytes : 8
16831 Total deallocated bytes : 4
16832 Current Water Mark: 4
16837 @node The gnatmem Tool
16838 @section The @command{gnatmem} Tool
16842 The @code{gnatmem} utility monitors dynamic allocation and
16843 deallocation activity in a program, and displays information about
16844 incorrect deallocations and possible sources of memory leaks.
16845 It is designed to work in association with a static runtime library
16846 only and in this context provides three types of information:
16849 General information concerning memory management, such as the total
16850 number of allocations and deallocations, the amount of allocated
16851 memory and the high water mark, i.e.@: the largest amount of allocated
16852 memory in the course of program execution.
16855 Backtraces for all incorrect deallocations, that is to say deallocations
16856 which do not correspond to a valid allocation.
16859 Information on each allocation that is potentially the origin of a memory
16864 * Running gnatmem::
16865 * Switches for gnatmem::
16866 * Example of gnatmem Usage::
16869 @node Running gnatmem
16870 @subsection Running @code{gnatmem}
16873 @code{gnatmem} makes use of the output created by the special version of
16874 allocation and deallocation routines that record call information. This
16875 allows to obtain accurate dynamic memory usage history at a minimal cost to
16876 the execution speed. Note however, that @code{gnatmem} is not supported on
16877 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16878 Solaris and Windows NT/2000/XP (x86).
16881 The @code{gnatmem} command has the form
16884 @c $ gnatmem @ovar{switches} user_program
16885 @c Expanding @ovar macro inline (explanation in macro def comments)
16886 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16890 The program must have been linked with the instrumented version of the
16891 allocation and deallocation routines. This is done by linking with the
16892 @file{libgmem.a} library. For correct symbolic backtrace information,
16893 the user program should be compiled with debugging options
16894 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16897 $ gnatmake -g my_program -largs -lgmem
16901 As library @file{libgmem.a} contains an alternate body for package
16902 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16903 when an executable is linked with library @file{libgmem.a}. It is then not
16904 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16907 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16908 This file contains information about all allocations and deallocations
16909 performed by the program. It is produced by the instrumented allocations and
16910 deallocations routines and will be used by @code{gnatmem}.
16912 In order to produce symbolic backtrace information for allocations and
16913 deallocations performed by the GNAT run-time library, you need to use a
16914 version of that library that has been compiled with the @option{-g} switch
16915 (see @ref{Rebuilding the GNAT Run-Time Library}).
16917 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16918 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16919 @option{-i} switch, gnatmem will assume that this file can be found in the
16920 current directory. For example, after you have executed @file{my_program},
16921 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16924 $ gnatmem my_program
16928 This will produce the output with the following format:
16930 *************** debut cc
16932 $ gnatmem my_program
16936 Total number of allocations : 45
16937 Total number of deallocations : 6
16938 Final Water Mark (non freed mem) : 11.29 Kilobytes
16939 High Water Mark : 11.40 Kilobytes
16944 Allocation Root # 2
16945 -------------------
16946 Number of non freed allocations : 11
16947 Final Water Mark (non freed mem) : 1.16 Kilobytes
16948 High Water Mark : 1.27 Kilobytes
16950 my_program.adb:23 my_program.alloc
16956 The first block of output gives general information. In this case, the
16957 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16958 Unchecked_Deallocation routine occurred.
16961 Subsequent paragraphs display information on all allocation roots.
16962 An allocation root is a specific point in the execution of the program
16963 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16964 construct. This root is represented by an execution backtrace (or subprogram
16965 call stack). By default the backtrace depth for allocations roots is 1, so
16966 that a root corresponds exactly to a source location. The backtrace can
16967 be made deeper, to make the root more specific.
16969 @node Switches for gnatmem
16970 @subsection Switches for @code{gnatmem}
16973 @code{gnatmem} recognizes the following switches:
16978 @cindex @option{-q} (@code{gnatmem})
16979 Quiet. Gives the minimum output needed to identify the origin of the
16980 memory leaks. Omits statistical information.
16983 @cindex @var{N} (@code{gnatmem})
16984 N is an integer literal (usually between 1 and 10) which controls the
16985 depth of the backtraces defining allocation root. The default value for
16986 N is 1. The deeper the backtrace, the more precise the localization of
16987 the root. Note that the total number of roots can depend on this
16988 parameter. This parameter must be specified @emph{before} the name of the
16989 executable to be analyzed, to avoid ambiguity.
16992 @cindex @option{-b} (@code{gnatmem})
16993 This switch has the same effect as just depth parameter.
16995 @item -i @var{file}
16996 @cindex @option{-i} (@code{gnatmem})
16997 Do the @code{gnatmem} processing starting from @file{file}, rather than
16998 @file{gmem.out} in the current directory.
17001 @cindex @option{-m} (@code{gnatmem})
17002 This switch causes @code{gnatmem} to mask the allocation roots that have less
17003 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17004 examine even the roots that didn't result in leaks.
17007 @cindex @option{-s} (@code{gnatmem})
17008 This switch causes @code{gnatmem} to sort the allocation roots according to the
17009 specified order of sort criteria, each identified by a single letter. The
17010 currently supported criteria are @code{n, h, w} standing respectively for
17011 number of unfreed allocations, high watermark, and final watermark
17012 corresponding to a specific root. The default order is @code{nwh}.
17016 @node Example of gnatmem Usage
17017 @subsection Example of @code{gnatmem} Usage
17020 The following example shows the use of @code{gnatmem}
17021 on a simple memory-leaking program.
17022 Suppose that we have the following Ada program:
17024 @smallexample @c ada
17027 with Unchecked_Deallocation;
17028 procedure Test_Gm is
17030 type T is array (1..1000) of Integer;
17031 type Ptr is access T;
17032 procedure Free is new Unchecked_Deallocation (T, Ptr);
17035 procedure My_Alloc is
17040 procedure My_DeAlloc is
17048 for I in 1 .. 5 loop
17049 for J in I .. 5 loop
17060 The program needs to be compiled with debugging option and linked with
17061 @code{gmem} library:
17064 $ gnatmake -g test_gm -largs -lgmem
17068 Then we execute the program as usual:
17075 Then @code{gnatmem} is invoked simply with
17081 which produces the following output (result may vary on different platforms):
17086 Total number of allocations : 18
17087 Total number of deallocations : 5
17088 Final Water Mark (non freed mem) : 53.00 Kilobytes
17089 High Water Mark : 56.90 Kilobytes
17091 Allocation Root # 1
17092 -------------------
17093 Number of non freed allocations : 11
17094 Final Water Mark (non freed mem) : 42.97 Kilobytes
17095 High Water Mark : 46.88 Kilobytes
17097 test_gm.adb:11 test_gm.my_alloc
17099 Allocation Root # 2
17100 -------------------
17101 Number of non freed allocations : 1
17102 Final Water Mark (non freed mem) : 10.02 Kilobytes
17103 High Water Mark : 10.02 Kilobytes
17105 s-secsta.adb:81 system.secondary_stack.ss_init
17107 Allocation Root # 3
17108 -------------------
17109 Number of non freed allocations : 1
17110 Final Water Mark (non freed mem) : 12 Bytes
17111 High Water Mark : 12 Bytes
17113 s-secsta.adb:181 system.secondary_stack.ss_init
17117 Note that the GNAT run time contains itself a certain number of
17118 allocations that have no corresponding deallocation,
17119 as shown here for root #2 and root
17120 #3. This is a normal behavior when the number of non-freed allocations
17121 is one, it allocates dynamic data structures that the run time needs for
17122 the complete lifetime of the program. Note also that there is only one
17123 allocation root in the user program with a single line back trace:
17124 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17125 program shows that 'My_Alloc' is called at 2 different points in the
17126 source (line 21 and line 24). If those two allocation roots need to be
17127 distinguished, the backtrace depth parameter can be used:
17130 $ gnatmem 3 test_gm
17134 which will give the following output:
17139 Total number of allocations : 18
17140 Total number of deallocations : 5
17141 Final Water Mark (non freed mem) : 53.00 Kilobytes
17142 High Water Mark : 56.90 Kilobytes
17144 Allocation Root # 1
17145 -------------------
17146 Number of non freed allocations : 10
17147 Final Water Mark (non freed mem) : 39.06 Kilobytes
17148 High Water Mark : 42.97 Kilobytes
17150 test_gm.adb:11 test_gm.my_alloc
17151 test_gm.adb:24 test_gm
17152 b_test_gm.c:52 main
17154 Allocation Root # 2
17155 -------------------
17156 Number of non freed allocations : 1
17157 Final Water Mark (non freed mem) : 10.02 Kilobytes
17158 High Water Mark : 10.02 Kilobytes
17160 s-secsta.adb:81 system.secondary_stack.ss_init
17161 s-secsta.adb:283 <system__secondary_stack___elabb>
17162 b_test_gm.c:33 adainit
17164 Allocation Root # 3
17165 -------------------
17166 Number of non freed allocations : 1
17167 Final Water Mark (non freed mem) : 3.91 Kilobytes
17168 High Water Mark : 3.91 Kilobytes
17170 test_gm.adb:11 test_gm.my_alloc
17171 test_gm.adb:21 test_gm
17172 b_test_gm.c:52 main
17174 Allocation Root # 4
17175 -------------------
17176 Number of non freed allocations : 1
17177 Final Water Mark (non freed mem) : 12 Bytes
17178 High Water Mark : 12 Bytes
17180 s-secsta.adb:181 system.secondary_stack.ss_init
17181 s-secsta.adb:283 <system__secondary_stack___elabb>
17182 b_test_gm.c:33 adainit
17186 The allocation root #1 of the first example has been split in 2 roots #1
17187 and #3 thanks to the more precise associated backtrace.
17191 @node Stack Related Facilities
17192 @chapter Stack Related Facilities
17195 This chapter describes some useful tools associated with stack
17196 checking and analysis. In
17197 particular, it deals with dynamic and static stack usage measurements.
17200 * Stack Overflow Checking::
17201 * Static Stack Usage Analysis::
17202 * Dynamic Stack Usage Analysis::
17205 @node Stack Overflow Checking
17206 @section Stack Overflow Checking
17207 @cindex Stack Overflow Checking
17208 @cindex -fstack-check
17211 For most operating systems, @command{gcc} does not perform stack overflow
17212 checking by default. This means that if the main environment task or
17213 some other task exceeds the available stack space, then unpredictable
17214 behavior will occur. Most native systems offer some level of protection by
17215 adding a guard page at the end of each task stack. This mechanism is usually
17216 not enough for dealing properly with stack overflow situations because
17217 a large local variable could ``jump'' above the guard page.
17218 Furthermore, when the
17219 guard page is hit, there may not be any space left on the stack for executing
17220 the exception propagation code. Enabling stack checking avoids
17223 To activate stack checking, compile all units with the gcc option
17224 @option{-fstack-check}. For example:
17227 gcc -c -fstack-check package1.adb
17231 Units compiled with this option will generate extra instructions to check
17232 that any use of the stack (for procedure calls or for declaring local
17233 variables in declare blocks) does not exceed the available stack space.
17234 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17236 For declared tasks, the stack size is controlled by the size
17237 given in an applicable @code{Storage_Size} pragma or by the value specified
17238 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17239 the default size as defined in the GNAT runtime otherwise.
17241 For the environment task, the stack size depends on
17242 system defaults and is unknown to the compiler. Stack checking
17243 may still work correctly if a fixed
17244 size stack is allocated, but this cannot be guaranteed.
17246 To ensure that a clean exception is signalled for stack
17247 overflow, set the environment variable
17248 @env{GNAT_STACK_LIMIT} to indicate the maximum
17249 stack area that can be used, as in:
17250 @cindex GNAT_STACK_LIMIT
17253 SET GNAT_STACK_LIMIT 1600
17257 The limit is given in kilobytes, so the above declaration would
17258 set the stack limit of the environment task to 1.6 megabytes.
17259 Note that the only purpose of this usage is to limit the amount
17260 of stack used by the environment task. If it is necessary to
17261 increase the amount of stack for the environment task, then this
17262 is an operating systems issue, and must be addressed with the
17263 appropriate operating systems commands.
17266 To have a fixed size stack in the environment task, the stack must be put
17267 in the P0 address space and its size specified. Use these switches to
17271 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17275 The quotes are required to keep case. The number after @samp{STACK=} is the
17276 size of the environmental task stack in pagelets (512 bytes). In this example
17277 the stack size is about 2 megabytes.
17280 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17281 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
17282 more details about the @option{/p0image} qualifier and the @option{stack}
17286 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17287 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17288 stack in kilobytes. For example:
17291 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17295 @node Static Stack Usage Analysis
17296 @section Static Stack Usage Analysis
17297 @cindex Static Stack Usage Analysis
17298 @cindex -fstack-usage
17301 A unit compiled with @option{-fstack-usage} will generate an extra file
17303 the maximum amount of stack used, on a per-function basis.
17304 The file has the same
17305 basename as the target object file with a @file{.su} extension.
17306 Each line of this file is made up of three fields:
17310 The name of the function.
17314 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17317 The second field corresponds to the size of the known part of the function
17320 The qualifier @code{static} means that the function frame size
17322 It usually means that all local variables have a static size.
17323 In this case, the second field is a reliable measure of the function stack
17326 The qualifier @code{dynamic} means that the function frame size is not static.
17327 It happens mainly when some local variables have a dynamic size. When this
17328 qualifier appears alone, the second field is not a reliable measure
17329 of the function stack analysis. When it is qualified with @code{bounded}, it
17330 means that the second field is a reliable maximum of the function stack
17333 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17334 subprogram whose stack usage might be larger than the specified amount of
17335 bytes. The wording is in keeping with the qualifier documented above.
17337 @node Dynamic Stack Usage Analysis
17338 @section Dynamic Stack Usage Analysis
17341 It is possible to measure the maximum amount of stack used by a task, by
17342 adding a switch to @command{gnatbind}, as:
17345 $ gnatbind -u0 file
17349 With this option, at each task termination, its stack usage is output on
17351 It is not always convenient to output the stack usage when the program
17352 is still running. Hence, it is possible to delay this output until program
17353 termination. for a given number of tasks specified as the argument of the
17354 @option{-u} option. For instance:
17357 $ gnatbind -u100 file
17361 will buffer the stack usage information of the first 100 tasks to terminate and
17362 output this info at program termination. Results are displayed in four
17366 Index | Task Name | Stack Size | Stack Usage
17373 is a number associated with each task.
17376 is the name of the task analyzed.
17379 is the maximum size for the stack.
17382 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17383 is not entirely analyzed, and it's not possible to know exactly how
17384 much has actually been used.
17389 The environment task stack, e.g., the stack that contains the main unit, is
17390 only processed when the environment variable GNAT_STACK_LIMIT is set.
17393 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17394 stack usage reports at run-time. See its body for the details.
17396 @c *********************************
17398 @c *********************************
17399 @node Verifying Properties Using gnatcheck
17400 @chapter Verifying Properties Using @command{gnatcheck}
17402 @cindex @command{gnatcheck}
17405 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17406 of Ada source files according to a given set of semantic rules.
17409 In order to check compliance with a given rule, @command{gnatcheck} has to
17410 semantically analyze the Ada sources.
17411 Therefore, checks can only be performed on
17412 legal Ada units. Moreover, when a unit depends semantically upon units located
17413 outside the current directory, the source search path has to be provided when
17414 calling @command{gnatcheck}, either through a specified project file or
17415 through @command{gnatcheck} switches.
17417 For full details, refer to @cite{GNATcheck Reference Manual} document.
17420 @c *********************************
17421 @node Creating Sample Bodies Using gnatstub
17422 @chapter Creating Sample Bodies Using @command{gnatstub}
17426 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17427 for library unit declarations.
17429 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17430 driver (see @ref{The GNAT Driver and Project Files}).
17432 To create a body stub, @command{gnatstub} has to compile the library
17433 unit declaration. Therefore, bodies can be created only for legal
17434 library units. Moreover, if a library unit depends semantically upon
17435 units located outside the current directory, you have to provide
17436 the source search path when calling @command{gnatstub}, see the description
17437 of @command{gnatstub} switches below.
17439 By default, all the program unit body stubs generated by @code{gnatstub}
17440 raise the predefined @code{Program_Error} exception, which will catch
17441 accidental calls of generated stubs. This behavior can be changed with
17442 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17445 * Running gnatstub::
17446 * Switches for gnatstub::
17449 @node Running gnatstub
17450 @section Running @command{gnatstub}
17453 @command{gnatstub} has the command-line interface of the form
17456 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17457 @c Expanding @ovar macro inline (explanation in macro def comments)
17458 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17465 is the name of the source file that contains a library unit declaration
17466 for which a body must be created. The file name may contain the path
17468 The file name does not have to follow the GNAT file name conventions. If the
17470 does not follow GNAT file naming conventions, the name of the body file must
17472 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17473 If the file name follows the GNAT file naming
17474 conventions and the name of the body file is not provided,
17477 of the body file from the argument file name by replacing the @file{.ads}
17479 with the @file{.adb} suffix.
17482 indicates the directory in which the body stub is to be placed (the default
17486 @item @samp{@var{gcc_switches}} is a list of switches for
17487 @command{gcc}. They will be passed on to all compiler invocations made by
17488 @command{gnatelim} to generate the ASIS trees. Here you can provide
17489 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17490 use the @option{-gnatec} switch to set the configuration file,
17491 use the @option{-gnat05} switch if sources should be compiled in
17495 is an optional sequence of switches as described in the next section
17498 @node Switches for gnatstub
17499 @section Switches for @command{gnatstub}
17505 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17506 If the destination directory already contains a file with the name of the
17508 for the argument spec file, replace it with the generated body stub.
17510 @item ^-hs^/HEADER=SPEC^
17511 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17512 Put the comment header (i.e., all the comments preceding the
17513 compilation unit) from the source of the library unit declaration
17514 into the body stub.
17516 @item ^-hg^/HEADER=GENERAL^
17517 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17518 Put a sample comment header into the body stub.
17520 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17521 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17522 Use the content of the file as the comment header for a generated body stub.
17526 @cindex @option{-IDIR} (@command{gnatstub})
17528 @cindex @option{-I-} (@command{gnatstub})
17531 @item /NOCURRENT_DIRECTORY
17532 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17534 ^These switches have ^This switch has^ the same meaning as in calls to
17536 ^They define ^It defines ^ the source search path in the call to
17537 @command{gcc} issued
17538 by @command{gnatstub} to compile an argument source file.
17540 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17541 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17542 This switch has the same meaning as in calls to @command{gcc}.
17543 It defines the additional configuration file to be passed to the call to
17544 @command{gcc} issued
17545 by @command{gnatstub} to compile an argument source file.
17547 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17548 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17549 (@var{n} is a non-negative integer). Set the maximum line length in the
17550 body stub to @var{n}; the default is 79. The maximum value that can be
17551 specified is 32767. Note that in the special case of configuration
17552 pragma files, the maximum is always 32767 regardless of whether or
17553 not this switch appears.
17555 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17556 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17557 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17558 the generated body sample to @var{n}.
17559 The default indentation is 3.
17561 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17562 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17563 Order local bodies alphabetically. (By default local bodies are ordered
17564 in the same way as the corresponding local specs in the argument spec file.)
17566 @item ^-i^/INDENTATION=^@var{n}
17567 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17568 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17570 @item ^-k^/TREE_FILE=SAVE^
17571 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17572 Do not remove the tree file (i.e., the snapshot of the compiler internal
17573 structures used by @command{gnatstub}) after creating the body stub.
17575 @item ^-l^/LINE_LENGTH=^@var{n}
17576 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17577 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17579 @item ^--no-exception^/NO_EXCEPTION^
17580 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17581 void raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17582 This is not always possible for function stubs.
17584 @item ^--no-local-header^/NO_LOCAL_HEADER^
17585 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17586 Do not place local comment header with unit name before body stub for a
17589 @item ^-o ^/BODY=^@var{body-name}
17590 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17591 Body file name. This should be set if the argument file name does not
17593 the GNAT file naming
17594 conventions. If this switch is omitted the default name for the body will be
17596 from the argument file name according to the GNAT file naming conventions.
17599 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17600 Quiet mode: do not generate a confirmation when a body is
17601 successfully created, and do not generate a message when a body is not
17605 @item ^-r^/TREE_FILE=REUSE^
17606 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17607 Reuse the tree file (if it exists) instead of creating it. Instead of
17608 creating the tree file for the library unit declaration, @command{gnatstub}
17609 tries to find it in the current directory and use it for creating
17610 a body. If the tree file is not found, no body is created. This option
17611 also implies @option{^-k^/SAVE^}, whether or not
17612 the latter is set explicitly.
17614 @item ^-t^/TREE_FILE=OVERWRITE^
17615 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17616 Overwrite the existing tree file. If the current directory already
17617 contains the file which, according to the GNAT file naming rules should
17618 be considered as a tree file for the argument source file,
17620 will refuse to create the tree file needed to create a sample body
17621 unless this option is set.
17623 @item ^-v^/VERBOSE^
17624 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17625 Verbose mode: generate version information.
17629 @c *********************************
17630 @node Generating Ada Bindings for C and C++ headers
17631 @chapter Generating Ada Bindings for C and C++ headers
17635 GNAT now comes with a binding generator for C and C++ headers which is
17636 intended to do 95% of the tedious work of generating Ada specs from C
17637 or C++ header files.
17639 Note that this capability is not intended to generate 100% correct Ada specs,
17640 and will is some cases require manual adjustments, although it can often
17641 be used out of the box in practice.
17643 Some of the known limitations include:
17646 @item only very simple character constant macros are translated into Ada
17647 constants. Function macros (macros with arguments) are partially translated
17648 as comments, to be completed manually if needed.
17649 @item some extensions (e.g. vector types) are not supported
17650 @item pointers to pointers or complex structures are mapped to System.Address
17651 @item identifiers with identical name (except casing) will generate compilation
17652 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
17655 The code generated is using the Ada 2005 syntax, which makes it
17656 easier to interface with other languages than previous versions of Ada.
17659 * Running the binding generator::
17660 * Generating bindings for C++ headers::
17664 @node Running the binding generator
17665 @section Running the binding generator
17668 The binding generator is part of the @command{gcc} compiler and can be
17669 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
17670 spec files for the header files specified on the command line, and all
17671 header files needed by these files transitively. For example:
17674 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
17675 $ gcc -c -gnat05 *.ads
17678 will generate, under GNU/Linux, the following files: @file{time_h.ads},
17679 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
17680 correspond to the files @file{/usr/include/time.h},
17681 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
17682 mode these Ada specs.
17684 The @code{-C} switch tells @command{gcc} to extract comments from headers,
17685 and will attempt to generate corresponding Ada comments.
17687 If you want to generate a single Ada file and not the transitive closure, you
17688 can use instead the @option{-fdump-ada-spec-slim} switch.
17690 Note that we recommend when possible to use the @command{g++} driver to
17691 generate bindings, even for most C headers, since this will in general
17692 generate better Ada specs. For generating bindings for C++ headers, it is
17693 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
17694 is equivalent in this case. If @command{g++} cannot work on your C headers
17695 because of incompatibilities between C and C++, then you can fallback to
17696 @command{gcc} instead.
17698 For an example of better bindings generated from the C++ front-end,
17699 the name of the parameters (when available) are actually ignored by the C
17700 front-end. Consider the following C header:
17703 extern void foo (int variable);
17706 with the C front-end, @code{variable} is ignored, and the above is handled as:
17709 extern void foo (int);
17712 generating a generic:
17715 procedure foo (param1 : int);
17718 with the C++ front-end, the name is available, and we generate:
17721 procedure foo (variable : int);
17724 In some cases, the generated bindings will be more complete or more meaningful
17725 when defining some macros, which you can do via the @option{-D} switch. This
17726 is for example the case with @file{Xlib.h} under GNU/Linux:
17729 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
17732 The above will generate more complete bindings than a straight call without
17733 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
17735 In other cases, it is not possible to parse a header file in a stand alone
17736 manner, because other include files need to be included first. In this
17737 case, the solution is to create a small header file including the needed
17738 @code{#include} and possible @code{#define} directives. For example, to
17739 generate Ada bindings for @file{readline/readline.h}, you need to first
17740 include @file{stdio.h}, so you can create a file with the following two
17741 lines in e.g. @file{readline1.h}:
17745 #include <readline/readline.h>
17748 and then generate Ada bindings from this file:
17751 $ g++ -c -fdump-ada-spec readline1.h
17754 @node Generating bindings for C++ headers
17755 @section Generating bindings for C++ headers
17758 Generating bindings for C++ headers is done using the same options, always
17759 with the @command{g++} compiler.
17761 In this mode, C++ classes will be mapped to Ada tagged types, constructors
17762 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
17763 multiple inheritance of abstract classes will be mapped to Ada interfaces
17764 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
17765 information on interfacing to C++).
17767 For example, given the following C++ header file:
17774 virtual int Number_Of_Teeth () = 0;
17779 virtual void Set_Owner (char* Name) = 0;
17785 virtual void Set_Age (int New_Age);
17788 class Dog : Animal, Carnivore, Domestic @{
17793 virtual int Number_Of_Teeth ();
17794 virtual void Set_Owner (char* Name);
17802 The corresponding Ada code is generated:
17804 @smallexample @c ada
17807 package Class_Carnivore is
17808 type Carnivore is limited interface;
17809 pragma Import (CPP, Carnivore);
17811 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
17813 use Class_Carnivore;
17815 package Class_Domestic is
17816 type Domestic is limited interface;
17817 pragma Import (CPP, Domestic);
17819 procedure Set_Owner
17820 (this : access Domestic;
17821 Name : Interfaces.C.Strings.chars_ptr) is abstract;
17823 use Class_Domestic;
17825 package Class_Animal is
17826 type Animal is tagged limited record
17827 Age_Count : aliased int;
17829 pragma Import (CPP, Animal);
17831 procedure Set_Age (this : access Animal; New_Age : int);
17832 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
17836 package Class_Dog is
17837 type Dog is new Animal and Carnivore and Domestic with record
17838 Tooth_Count : aliased int;
17839 Owner : Interfaces.C.Strings.chars_ptr;
17841 pragma Import (CPP, Dog);
17843 function Number_Of_Teeth (this : access Dog) return int;
17844 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
17846 procedure Set_Owner
17847 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
17848 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
17850 function New_Dog return Dog;
17851 pragma CPP_Constructor (New_Dog);
17852 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
17863 @item -fdump-ada-spec
17864 @cindex @option{-fdump-ada-spec} (@command{gcc})
17865 Generate Ada spec files for the given header files transitively (including
17866 all header files that these headers depend upon).
17868 @item -fdump-ada-spec-slim
17869 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
17870 Generate Ada spec files for the header files specified on the command line
17874 @cindex @option{-C} (@command{gcc})
17875 Extract comments from headers and generate Ada comments in the Ada spec files.
17878 @node Other Utility Programs
17879 @chapter Other Utility Programs
17882 This chapter discusses some other utility programs available in the Ada
17886 * Using Other Utility Programs with GNAT::
17887 * The External Symbol Naming Scheme of GNAT::
17888 * Converting Ada Files to html with gnathtml::
17889 * Installing gnathtml::
17896 @node Using Other Utility Programs with GNAT
17897 @section Using Other Utility Programs with GNAT
17900 The object files generated by GNAT are in standard system format and in
17901 particular the debugging information uses this format. This means
17902 programs generated by GNAT can be used with existing utilities that
17903 depend on these formats.
17906 In general, any utility program that works with C will also often work with
17907 Ada programs generated by GNAT. This includes software utilities such as
17908 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17912 @node The External Symbol Naming Scheme of GNAT
17913 @section The External Symbol Naming Scheme of GNAT
17916 In order to interpret the output from GNAT, when using tools that are
17917 originally intended for use with other languages, it is useful to
17918 understand the conventions used to generate link names from the Ada
17921 All link names are in all lowercase letters. With the exception of library
17922 procedure names, the mechanism used is simply to use the full expanded
17923 Ada name with dots replaced by double underscores. For example, suppose
17924 we have the following package spec:
17926 @smallexample @c ada
17937 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17938 the corresponding link name is @code{qrs__mn}.
17940 Of course if a @code{pragma Export} is used this may be overridden:
17942 @smallexample @c ada
17947 pragma Export (Var1, C, External_Name => "var1_name");
17949 pragma Export (Var2, C, Link_Name => "var2_link_name");
17956 In this case, the link name for @var{Var1} is whatever link name the
17957 C compiler would assign for the C function @var{var1_name}. This typically
17958 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17959 system conventions, but other possibilities exist. The link name for
17960 @var{Var2} is @var{var2_link_name}, and this is not operating system
17964 One exception occurs for library level procedures. A potential ambiguity
17965 arises between the required name @code{_main} for the C main program,
17966 and the name we would otherwise assign to an Ada library level procedure
17967 called @code{Main} (which might well not be the main program).
17969 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17970 names. So if we have a library level procedure such as
17972 @smallexample @c ada
17975 procedure Hello (S : String);
17981 the external name of this procedure will be @var{_ada_hello}.
17984 @node Converting Ada Files to html with gnathtml
17985 @section Converting Ada Files to HTML with @code{gnathtml}
17988 This @code{Perl} script allows Ada source files to be browsed using
17989 standard Web browsers. For installation procedure, see the section
17990 @xref{Installing gnathtml}.
17992 Ada reserved keywords are highlighted in a bold font and Ada comments in
17993 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17994 switch to suppress the generation of cross-referencing information, user
17995 defined variables and types will appear in a different color; you will
17996 be able to click on any identifier and go to its declaration.
17998 The command line is as follow:
18000 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18001 @c Expanding @ovar macro inline (explanation in macro def comments)
18002 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18006 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18007 an html file for every ada file, and a global file called @file{index.htm}.
18008 This file is an index of every identifier defined in the files.
18010 The available ^switches^options^ are the following ones:
18014 @cindex @option{-83} (@code{gnathtml})
18015 Only the Ada 83 subset of keywords will be highlighted.
18017 @item -cc @var{color}
18018 @cindex @option{-cc} (@code{gnathtml})
18019 This option allows you to change the color used for comments. The default
18020 value is green. The color argument can be any name accepted by html.
18023 @cindex @option{-d} (@code{gnathtml})
18024 If the Ada files depend on some other files (for instance through
18025 @code{with} clauses, the latter files will also be converted to html.
18026 Only the files in the user project will be converted to html, not the files
18027 in the run-time library itself.
18030 @cindex @option{-D} (@code{gnathtml})
18031 This command is the same as @option{-d} above, but @command{gnathtml} will
18032 also look for files in the run-time library, and generate html files for them.
18034 @item -ext @var{extension}
18035 @cindex @option{-ext} (@code{gnathtml})
18036 This option allows you to change the extension of the generated HTML files.
18037 If you do not specify an extension, it will default to @file{htm}.
18040 @cindex @option{-f} (@code{gnathtml})
18041 By default, gnathtml will generate html links only for global entities
18042 ('with'ed units, global variables and types,@dots{}). If you specify
18043 @option{-f} on the command line, then links will be generated for local
18046 @item -l @var{number}
18047 @cindex @option{-l} (@code{gnathtml})
18048 If this ^switch^option^ is provided and @var{number} is not 0, then
18049 @code{gnathtml} will number the html files every @var{number} line.
18052 @cindex @option{-I} (@code{gnathtml})
18053 Specify a directory to search for library files (@file{.ALI} files) and
18054 source files. You can provide several -I switches on the command line,
18055 and the directories will be parsed in the order of the command line.
18058 @cindex @option{-o} (@code{gnathtml})
18059 Specify the output directory for html files. By default, gnathtml will
18060 saved the generated html files in a subdirectory named @file{html/}.
18062 @item -p @var{file}
18063 @cindex @option{-p} (@code{gnathtml})
18064 If you are using Emacs and the most recent Emacs Ada mode, which provides
18065 a full Integrated Development Environment for compiling, checking,
18066 running and debugging applications, you may use @file{.gpr} files
18067 to give the directories where Emacs can find sources and object files.
18069 Using this ^switch^option^, you can tell gnathtml to use these files.
18070 This allows you to get an html version of your application, even if it
18071 is spread over multiple directories.
18073 @item -sc @var{color}
18074 @cindex @option{-sc} (@code{gnathtml})
18075 This ^switch^option^ allows you to change the color used for symbol
18077 The default value is red. The color argument can be any name accepted by html.
18079 @item -t @var{file}
18080 @cindex @option{-t} (@code{gnathtml})
18081 This ^switch^option^ provides the name of a file. This file contains a list of
18082 file names to be converted, and the effect is exactly as though they had
18083 appeared explicitly on the command line. This
18084 is the recommended way to work around the command line length limit on some
18089 @node Installing gnathtml
18090 @section Installing @code{gnathtml}
18093 @code{Perl} needs to be installed on your machine to run this script.
18094 @code{Perl} is freely available for almost every architecture and
18095 Operating System via the Internet.
18097 On Unix systems, you may want to modify the first line of the script
18098 @code{gnathtml}, to explicitly tell the Operating system where Perl
18099 is. The syntax of this line is:
18101 #!full_path_name_to_perl
18105 Alternatively, you may run the script using the following command line:
18108 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18109 @c Expanding @ovar macro inline (explanation in macro def comments)
18110 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18119 The GNAT distribution provides an Ada 95 template for the HP Language
18120 Sensitive Editor (LSE), a component of DECset. In order to
18121 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18128 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18129 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18130 the collection phase with the /DEBUG qualifier.
18133 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18134 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18135 $ RUN/DEBUG <PROGRAM_NAME>
18141 @c ******************************
18142 @node Code Coverage and Profiling
18143 @chapter Code Coverage and Profiling
18144 @cindex Code Coverage
18148 This chapter describes how to use @code{gcov} - coverage testing tool - and
18149 @code{gprof} - profiler tool - on your Ada programs.
18152 * Code Coverage of Ada Programs using gcov::
18153 * Profiling an Ada Program using gprof::
18156 @node Code Coverage of Ada Programs using gcov
18157 @section Code Coverage of Ada Programs using gcov
18159 @cindex -fprofile-arcs
18160 @cindex -ftest-coverage
18162 @cindex Code Coverage
18165 @code{gcov} is a test coverage program: it analyzes the execution of a given
18166 program on selected tests, to help you determine the portions of the program
18167 that are still untested.
18169 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18170 User's Guide. You can refer to this documentation for a more complete
18173 This chapter provides a quick startup guide, and
18174 details some Gnat-specific features.
18177 * Quick startup guide::
18181 @node Quick startup guide
18182 @subsection Quick startup guide
18184 In order to perform coverage analysis of a program using @code{gcov}, 3
18189 Code instrumentation during the compilation process
18191 Execution of the instrumented program
18193 Execution of the @code{gcov} tool to generate the result.
18196 The code instrumentation needed by gcov is created at the object level:
18197 The source code is not modified in any way, because the instrumentation code is
18198 inserted by gcc during the compilation process. To compile your code with code
18199 coverage activated, you need to recompile your whole project using the
18201 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18202 @code{-fprofile-arcs}.
18205 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18206 -largs -fprofile-arcs
18209 This compilation process will create @file{.gcno} files together with
18210 the usual object files.
18212 Once the program is compiled with coverage instrumentation, you can
18213 run it as many times as needed - on portions of a test suite for
18214 example. The first execution will produce @file{.gcda} files at the
18215 same location as the @file{.gcno} files. The following executions
18216 will update those files, so that a cumulative result of the covered
18217 portions of the program is generated.
18219 Finally, you need to call the @code{gcov} tool. The different options of
18220 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18222 This will create annotated source files with a @file{.gcov} extension:
18223 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18225 @node Gnat specifics
18226 @subsection Gnat specifics
18228 Because Ada semantics, portions of the source code may be shared among
18229 several object files. This is the case for example when generics are
18230 involved, when inlining is active or when declarations generate initialisation
18231 calls. In order to take
18232 into account this shared code, you need to call @code{gcov} on all
18233 source files of the tested program at once.
18235 The list of source files might exceed the system's maximum command line
18236 length. In order to bypass this limitation, a new mechanism has been
18237 implemented in @code{gcov}: you can now list all your project's files into a
18238 text file, and provide this file to gcov as a parameter, preceded by a @@
18239 (e.g. @samp{gcov @@mysrclist.txt}).
18241 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18242 not supported as there can be unresolved symbols during the final link.
18244 @node Profiling an Ada Program using gprof
18245 @section Profiling an Ada Program using gprof
18251 This section is not meant to be an exhaustive documentation of @code{gprof}.
18252 Full documentation for it can be found in the GNU Profiler User's Guide
18253 documentation that is part of this GNAT distribution.
18255 Profiling a program helps determine the parts of a program that are executed
18256 most often, and are therefore the most time-consuming.
18258 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18259 better handle Ada programs and multitasking.
18260 It is currently supported on the following platforms
18265 solaris sparc/sparc64/x86
18271 In order to profile a program using @code{gprof}, 3 steps are needed:
18275 Code instrumentation, requiring a full recompilation of the project with the
18278 Execution of the program under the analysis conditions, i.e. with the desired
18281 Analysis of the results using the @code{gprof} tool.
18285 The following sections detail the different steps, and indicate how
18286 to interpret the results:
18288 * Compilation for profiling::
18289 * Program execution::
18291 * Interpretation of profiling results::
18294 @node Compilation for profiling
18295 @subsection Compilation for profiling
18299 In order to profile a program the first step is to tell the compiler
18300 to generate the necessary profiling information. The compiler switch to be used
18301 is @code{-pg}, which must be added to other compilation switches. This
18302 switch needs to be specified both during compilation and link stages, and can
18303 be specified once when using gnatmake:
18306 gnatmake -f -pg -P my_project
18310 Note that only the objects that were compiled with the @samp{-pg} switch will
18311 be profiled; if you need to profile your whole project, use the @samp{-f}
18312 gnatmake switch to force full recompilation.
18314 @node Program execution
18315 @subsection Program execution
18318 Once the program has been compiled for profiling, you can run it as usual.
18320 The only constraint imposed by profiling is that the program must terminate
18321 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18324 Once the program completes execution, a data file called @file{gmon.out} is
18325 generated in the directory where the program was launched from. If this file
18326 already exists, it will be overwritten.
18328 @node Running gprof
18329 @subsection Running gprof
18332 The @code{gprof} tool is called as follow:
18335 gprof my_prog gmon.out
18346 The complete form of the gprof command line is the following:
18349 gprof [^switches^options^] [executable [data-file]]
18353 @code{gprof} supports numerous ^switch^options^. The order of these
18354 ^switch^options^ does not matter. The full list of options can be found in
18355 the GNU Profiler User's Guide documentation that comes with this documentation.
18357 The following is the subset of those switches that is most relevant:
18361 @item --demangle[=@var{style}]
18362 @itemx --no-demangle
18363 @cindex @option{--demangle} (@code{gprof})
18364 These options control whether symbol names should be demangled when
18365 printing output. The default is to demangle C++ symbols. The
18366 @code{--no-demangle} option may be used to turn off demangling. Different
18367 compilers have different mangling styles. The optional demangling style
18368 argument can be used to choose an appropriate demangling style for your
18369 compiler, in particular Ada symbols generated by GNAT can be demangled using
18370 @code{--demangle=gnat}.
18372 @item -e @var{function_name}
18373 @cindex @option{-e} (@code{gprof})
18374 The @samp{-e @var{function}} option tells @code{gprof} not to print
18375 information about the function @var{function_name} (and its
18376 children@dots{}) in the call graph. The function will still be listed
18377 as a child of any functions that call it, but its index number will be
18378 shown as @samp{[not printed]}. More than one @samp{-e} option may be
18379 given; only one @var{function_name} may be indicated with each @samp{-e}
18382 @item -E @var{function_name}
18383 @cindex @option{-E} (@code{gprof})
18384 The @code{-E @var{function}} option works like the @code{-e} option, but
18385 execution time spent in the function (and children who were not called from
18386 anywhere else), will not be used to compute the percentages-of-time for
18387 the call graph. More than one @samp{-E} option may be given; only one
18388 @var{function_name} may be indicated with each @samp{-E} option.
18390 @item -f @var{function_name}
18391 @cindex @option{-f} (@code{gprof})
18392 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18393 call graph to the function @var{function_name} and its children (and
18394 their children@dots{}). More than one @samp{-f} option may be given;
18395 only one @var{function_name} may be indicated with each @samp{-f}
18398 @item -F @var{function_name}
18399 @cindex @option{-F} (@code{gprof})
18400 The @samp{-F @var{function}} option works like the @code{-f} option, but
18401 only time spent in the function and its children (and their
18402 children@dots{}) will be used to determine total-time and
18403 percentages-of-time for the call graph. More than one @samp{-F} option
18404 may be given; only one @var{function_name} may be indicated with each
18405 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
18409 @node Interpretation of profiling results
18410 @subsection Interpretation of profiling results
18414 The results of the profiling analysis are represented by two arrays: the
18415 'flat profile' and the 'call graph'. Full documentation of those outputs
18416 can be found in the GNU Profiler User's Guide.
18418 The flat profile shows the time spent in each function of the program, and how
18419 many time it has been called. This allows you to locate easily the most
18420 time-consuming functions.
18422 The call graph shows, for each subprogram, the subprograms that call it,
18423 and the subprograms that it calls. It also provides an estimate of the time
18424 spent in each of those callers/called subprograms.
18427 @c ******************************
18428 @node Running and Debugging Ada Programs
18429 @chapter Running and Debugging Ada Programs
18433 This chapter discusses how to debug Ada programs.
18435 It applies to GNAT on the Alpha OpenVMS platform;
18436 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18437 since HP has implemented Ada support in the OpenVMS debugger on I64.
18440 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18444 The illegality may be a violation of the static semantics of Ada. In
18445 that case GNAT diagnoses the constructs in the program that are illegal.
18446 It is then a straightforward matter for the user to modify those parts of
18450 The illegality may be a violation of the dynamic semantics of Ada. In
18451 that case the program compiles and executes, but may generate incorrect
18452 results, or may terminate abnormally with some exception.
18455 When presented with a program that contains convoluted errors, GNAT
18456 itself may terminate abnormally without providing full diagnostics on
18457 the incorrect user program.
18461 * The GNAT Debugger GDB::
18463 * Introduction to GDB Commands::
18464 * Using Ada Expressions::
18465 * Calling User-Defined Subprograms::
18466 * Using the Next Command in a Function::
18469 * Debugging Generic Units::
18470 * Remote Debugging using gdbserver::
18471 * GNAT Abnormal Termination or Failure to Terminate::
18472 * Naming Conventions for GNAT Source Files::
18473 * Getting Internal Debugging Information::
18474 * Stack Traceback::
18480 @node The GNAT Debugger GDB
18481 @section The GNAT Debugger GDB
18484 @code{GDB} is a general purpose, platform-independent debugger that
18485 can be used to debug mixed-language programs compiled with @command{gcc},
18486 and in particular is capable of debugging Ada programs compiled with
18487 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18488 complex Ada data structures.
18490 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18492 located in the GNU:[DOCS] directory,
18494 for full details on the usage of @code{GDB}, including a section on
18495 its usage on programs. This manual should be consulted for full
18496 details. The section that follows is a brief introduction to the
18497 philosophy and use of @code{GDB}.
18499 When GNAT programs are compiled, the compiler optionally writes debugging
18500 information into the generated object file, including information on
18501 line numbers, and on declared types and variables. This information is
18502 separate from the generated code. It makes the object files considerably
18503 larger, but it does not add to the size of the actual executable that
18504 will be loaded into memory, and has no impact on run-time performance. The
18505 generation of debug information is triggered by the use of the
18506 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18507 used to carry out the compilations. It is important to emphasize that
18508 the use of these options does not change the generated code.
18510 The debugging information is written in standard system formats that
18511 are used by many tools, including debuggers and profilers. The format
18512 of the information is typically designed to describe C types and
18513 semantics, but GNAT implements a translation scheme which allows full
18514 details about Ada types and variables to be encoded into these
18515 standard C formats. Details of this encoding scheme may be found in
18516 the file exp_dbug.ads in the GNAT source distribution. However, the
18517 details of this encoding are, in general, of no interest to a user,
18518 since @code{GDB} automatically performs the necessary decoding.
18520 When a program is bound and linked, the debugging information is
18521 collected from the object files, and stored in the executable image of
18522 the program. Again, this process significantly increases the size of
18523 the generated executable file, but it does not increase the size of
18524 the executable program itself. Furthermore, if this program is run in
18525 the normal manner, it runs exactly as if the debug information were
18526 not present, and takes no more actual memory.
18528 However, if the program is run under control of @code{GDB}, the
18529 debugger is activated. The image of the program is loaded, at which
18530 point it is ready to run. If a run command is given, then the program
18531 will run exactly as it would have if @code{GDB} were not present. This
18532 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
18533 entirely non-intrusive until a breakpoint is encountered. If no
18534 breakpoint is ever hit, the program will run exactly as it would if no
18535 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18536 the debugging information and can respond to user commands to inspect
18537 variables, and more generally to report on the state of execution.
18541 @section Running GDB
18544 This section describes how to initiate the debugger.
18545 @c The above sentence is really just filler, but it was otherwise
18546 @c clumsy to get the first paragraph nonindented given the conditional
18547 @c nature of the description
18550 The debugger can be launched from a @code{GPS} menu or
18551 directly from the command line. The description below covers the latter use.
18552 All the commands shown can be used in the @code{GPS} debug console window,
18553 but there are usually more GUI-based ways to achieve the same effect.
18556 The command to run @code{GDB} is
18559 $ ^gdb program^GDB PROGRAM^
18563 where @code{^program^PROGRAM^} is the name of the executable file. This
18564 activates the debugger and results in a prompt for debugger commands.
18565 The simplest command is simply @code{run}, which causes the program to run
18566 exactly as if the debugger were not present. The following section
18567 describes some of the additional commands that can be given to @code{GDB}.
18569 @c *******************************
18570 @node Introduction to GDB Commands
18571 @section Introduction to GDB Commands
18574 @code{GDB} contains a large repertoire of commands. @xref{Top,,
18575 Debugging with GDB, gdb, Debugging with GDB},
18577 located in the GNU:[DOCS] directory,
18579 for extensive documentation on the use
18580 of these commands, together with examples of their use. Furthermore,
18581 the command @command{help} invoked from within GDB activates a simple help
18582 facility which summarizes the available commands and their options.
18583 In this section we summarize a few of the most commonly
18584 used commands to give an idea of what @code{GDB} is about. You should create
18585 a simple program with debugging information and experiment with the use of
18586 these @code{GDB} commands on the program as you read through the
18590 @item set args @var{arguments}
18591 The @var{arguments} list above is a list of arguments to be passed to
18592 the program on a subsequent run command, just as though the arguments
18593 had been entered on a normal invocation of the program. The @code{set args}
18594 command is not needed if the program does not require arguments.
18597 The @code{run} command causes execution of the program to start from
18598 the beginning. If the program is already running, that is to say if
18599 you are currently positioned at a breakpoint, then a prompt will ask
18600 for confirmation that you want to abandon the current execution and
18603 @item breakpoint @var{location}
18604 The breakpoint command sets a breakpoint, that is to say a point at which
18605 execution will halt and @code{GDB} will await further
18606 commands. @var{location} is
18607 either a line number within a file, given in the format @code{file:linenumber},
18608 or it is the name of a subprogram. If you request that a breakpoint be set on
18609 a subprogram that is overloaded, a prompt will ask you to specify on which of
18610 those subprograms you want to breakpoint. You can also
18611 specify that all of them should be breakpointed. If the program is run
18612 and execution encounters the breakpoint, then the program
18613 stops and @code{GDB} signals that the breakpoint was encountered by
18614 printing the line of code before which the program is halted.
18616 @item catch exception @var{name}
18617 This command causes the program execution to stop whenever exception
18618 @var{name} is raised. If @var{name} is omitted, then the execution is
18619 suspended when any exception is raised.
18621 @item print @var{expression}
18622 This will print the value of the given expression. Most simple
18623 Ada expression formats are properly handled by @code{GDB}, so the expression
18624 can contain function calls, variables, operators, and attribute references.
18627 Continues execution following a breakpoint, until the next breakpoint or the
18628 termination of the program.
18631 Executes a single line after a breakpoint. If the next statement
18632 is a subprogram call, execution continues into (the first statement of)
18633 the called subprogram.
18636 Executes a single line. If this line is a subprogram call, executes and
18637 returns from the call.
18640 Lists a few lines around the current source location. In practice, it
18641 is usually more convenient to have a separate edit window open with the
18642 relevant source file displayed. Successive applications of this command
18643 print subsequent lines. The command can be given an argument which is a
18644 line number, in which case it displays a few lines around the specified one.
18647 Displays a backtrace of the call chain. This command is typically
18648 used after a breakpoint has occurred, to examine the sequence of calls that
18649 leads to the current breakpoint. The display includes one line for each
18650 activation record (frame) corresponding to an active subprogram.
18653 At a breakpoint, @code{GDB} can display the values of variables local
18654 to the current frame. The command @code{up} can be used to
18655 examine the contents of other active frames, by moving the focus up
18656 the stack, that is to say from callee to caller, one frame at a time.
18659 Moves the focus of @code{GDB} down from the frame currently being
18660 examined to the frame of its callee (the reverse of the previous command),
18662 @item frame @var{n}
18663 Inspect the frame with the given number. The value 0 denotes the frame
18664 of the current breakpoint, that is to say the top of the call stack.
18669 The above list is a very short introduction to the commands that
18670 @code{GDB} provides. Important additional capabilities, including conditional
18671 breakpoints, the ability to execute command sequences on a breakpoint,
18672 the ability to debug at the machine instruction level and many other
18673 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
18674 Debugging with GDB}. Note that most commands can be abbreviated
18675 (for example, c for continue, bt for backtrace).
18677 @node Using Ada Expressions
18678 @section Using Ada Expressions
18679 @cindex Ada expressions
18682 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18683 extensions. The philosophy behind the design of this subset is
18687 That @code{GDB} should provide basic literals and access to operations for
18688 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18689 leaving more sophisticated computations to subprograms written into the
18690 program (which therefore may be called from @code{GDB}).
18693 That type safety and strict adherence to Ada language restrictions
18694 are not particularly important to the @code{GDB} user.
18697 That brevity is important to the @code{GDB} user.
18701 Thus, for brevity, the debugger acts as if there were
18702 implicit @code{with} and @code{use} clauses in effect for all user-written
18703 packages, thus making it unnecessary to fully qualify most names with
18704 their packages, regardless of context. Where this causes ambiguity,
18705 @code{GDB} asks the user's intent.
18707 For details on the supported Ada syntax, see @ref{Top,, Debugging with
18708 GDB, gdb, Debugging with GDB}.
18710 @node Calling User-Defined Subprograms
18711 @section Calling User-Defined Subprograms
18714 An important capability of @code{GDB} is the ability to call user-defined
18715 subprograms while debugging. This is achieved simply by entering
18716 a subprogram call statement in the form:
18719 call subprogram-name (parameters)
18723 The keyword @code{call} can be omitted in the normal case where the
18724 @code{subprogram-name} does not coincide with any of the predefined
18725 @code{GDB} commands.
18727 The effect is to invoke the given subprogram, passing it the
18728 list of parameters that is supplied. The parameters can be expressions and
18729 can include variables from the program being debugged. The
18730 subprogram must be defined
18731 at the library level within your program, and @code{GDB} will call the
18732 subprogram within the environment of your program execution (which
18733 means that the subprogram is free to access or even modify variables
18734 within your program).
18736 The most important use of this facility is in allowing the inclusion of
18737 debugging routines that are tailored to particular data structures
18738 in your program. Such debugging routines can be written to provide a suitably
18739 high-level description of an abstract type, rather than a low-level dump
18740 of its physical layout. After all, the standard
18741 @code{GDB print} command only knows the physical layout of your
18742 types, not their abstract meaning. Debugging routines can provide information
18743 at the desired semantic level and are thus enormously useful.
18745 For example, when debugging GNAT itself, it is crucial to have access to
18746 the contents of the tree nodes used to represent the program internally.
18747 But tree nodes are represented simply by an integer value (which in turn
18748 is an index into a table of nodes).
18749 Using the @code{print} command on a tree node would simply print this integer
18750 value, which is not very useful. But the PN routine (defined in file
18751 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18752 a useful high level representation of the tree node, which includes the
18753 syntactic category of the node, its position in the source, the integers
18754 that denote descendant nodes and parent node, as well as varied
18755 semantic information. To study this example in more detail, you might want to
18756 look at the body of the PN procedure in the stated file.
18758 @node Using the Next Command in a Function
18759 @section Using the Next Command in a Function
18762 When you use the @code{next} command in a function, the current source
18763 location will advance to the next statement as usual. A special case
18764 arises in the case of a @code{return} statement.
18766 Part of the code for a return statement is the ``epilog'' of the function.
18767 This is the code that returns to the caller. There is only one copy of
18768 this epilog code, and it is typically associated with the last return
18769 statement in the function if there is more than one return. In some
18770 implementations, this epilog is associated with the first statement
18773 The result is that if you use the @code{next} command from a return
18774 statement that is not the last return statement of the function you
18775 may see a strange apparent jump to the last return statement or to
18776 the start of the function. You should simply ignore this odd jump.
18777 The value returned is always that from the first return statement
18778 that was stepped through.
18780 @node Ada Exceptions
18781 @section Stopping when Ada Exceptions are Raised
18785 You can set catchpoints that stop the program execution when your program
18786 raises selected exceptions.
18789 @item catch exception
18790 Set a catchpoint that stops execution whenever (any task in the) program
18791 raises any exception.
18793 @item catch exception @var{name}
18794 Set a catchpoint that stops execution whenever (any task in the) program
18795 raises the exception @var{name}.
18797 @item catch exception unhandled
18798 Set a catchpoint that stops executing whenever (any task in the) program
18799 raises an exception for which there is no handler.
18801 @item info exceptions
18802 @itemx info exceptions @var{regexp}
18803 The @code{info exceptions} command permits the user to examine all defined
18804 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18805 argument, prints out only those exceptions whose name matches @var{regexp}.
18813 @code{GDB} allows the following task-related commands:
18817 This command shows a list of current Ada tasks, as in the following example:
18824 ID TID P-ID Thread Pri State Name
18825 1 8088000 0 807e000 15 Child Activation Wait main_task
18826 2 80a4000 1 80ae000 15 Accept/Select Wait b
18827 3 809a800 1 80a4800 15 Child Activation Wait a
18828 * 4 80ae800 3 80b8000 15 Running c
18832 In this listing, the asterisk before the first task indicates it to be the
18833 currently running task. The first column lists the task ID that is used
18834 to refer to tasks in the following commands.
18836 @item break @var{linespec} task @var{taskid}
18837 @itemx break @var{linespec} task @var{taskid} if @dots{}
18838 @cindex Breakpoints and tasks
18839 These commands are like the @code{break @dots{} thread @dots{}}.
18840 @var{linespec} specifies source lines.
18842 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18843 to specify that you only want @code{GDB} to stop the program when a
18844 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18845 numeric task identifiers assigned by @code{GDB}, shown in the first
18846 column of the @samp{info tasks} display.
18848 If you do not specify @samp{task @var{taskid}} when you set a
18849 breakpoint, the breakpoint applies to @emph{all} tasks of your
18852 You can use the @code{task} qualifier on conditional breakpoints as
18853 well; in this case, place @samp{task @var{taskid}} before the
18854 breakpoint condition (before the @code{if}).
18856 @item task @var{taskno}
18857 @cindex Task switching
18859 This command allows to switch to the task referred by @var{taskno}. In
18860 particular, This allows to browse the backtrace of the specified
18861 task. It is advised to switch back to the original task before
18862 continuing execution otherwise the scheduling of the program may be
18867 For more detailed information on the tasking support,
18868 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
18870 @node Debugging Generic Units
18871 @section Debugging Generic Units
18872 @cindex Debugging Generic Units
18876 GNAT always uses code expansion for generic instantiation. This means that
18877 each time an instantiation occurs, a complete copy of the original code is
18878 made, with appropriate substitutions of formals by actuals.
18880 It is not possible to refer to the original generic entities in
18881 @code{GDB}, but it is always possible to debug a particular instance of
18882 a generic, by using the appropriate expanded names. For example, if we have
18884 @smallexample @c ada
18889 generic package k is
18890 procedure kp (v1 : in out integer);
18894 procedure kp (v1 : in out integer) is
18900 package k1 is new k;
18901 package k2 is new k;
18903 var : integer := 1;
18916 Then to break on a call to procedure kp in the k2 instance, simply
18920 (gdb) break g.k2.kp
18924 When the breakpoint occurs, you can step through the code of the
18925 instance in the normal manner and examine the values of local variables, as for
18928 @node Remote Debugging using gdbserver
18929 @section Remote Debugging using gdbserver
18930 @cindex Remote Debugging using gdbserver
18933 On platforms where gdbserver is supported, it is possible to use this tool
18934 to debug your application remotely. This can be useful in situations
18935 where the program needs to be run on a target host that is different
18936 from the host used for development, particularly when the target has
18937 a limited amount of resources (either CPU and/or memory).
18939 To do so, start your program using gdbserver on the target machine.
18940 gdbserver then automatically suspends the execution of your program
18941 at its entry point, waiting for a debugger to connect to it. The
18942 following commands starts an application and tells gdbserver to
18943 wait for a connection with the debugger on localhost port 4444.
18946 $ gdbserver localhost:4444 program
18947 Process program created; pid = 5685
18948 Listening on port 4444
18951 Once gdbserver has started listening, we can tell the debugger to establish
18952 a connection with this gdbserver, and then start the same debugging session
18953 as if the program was being debugged on the same host, directly under
18954 the control of GDB.
18958 (gdb) target remote targethost:4444
18959 Remote debugging using targethost:4444
18960 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18962 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18966 Breakpoint 1, foo () at foo.adb:4
18970 It is also possible to use gdbserver to attach to an already running
18971 program, in which case the execution of that program is simply suspended
18972 until the connection between the debugger and gdbserver is established.
18974 For more information on how to use gdbserver, @ref{Top, Server, Using
18975 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
18976 for gdbserver on x86-linux, x86-windows and x86_64-linux.
18978 @node GNAT Abnormal Termination or Failure to Terminate
18979 @section GNAT Abnormal Termination or Failure to Terminate
18980 @cindex GNAT Abnormal Termination or Failure to Terminate
18983 When presented with programs that contain serious errors in syntax
18985 GNAT may on rare occasions experience problems in operation, such
18987 segmentation fault or illegal memory access, raising an internal
18988 exception, terminating abnormally, or failing to terminate at all.
18989 In such cases, you can activate
18990 various features of GNAT that can help you pinpoint the construct in your
18991 program that is the likely source of the problem.
18993 The following strategies are presented in increasing order of
18994 difficulty, corresponding to your experience in using GNAT and your
18995 familiarity with compiler internals.
18999 Run @command{gcc} with the @option{-gnatf}. This first
19000 switch causes all errors on a given line to be reported. In its absence,
19001 only the first error on a line is displayed.
19003 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19004 are encountered, rather than after compilation is terminated. If GNAT
19005 terminates prematurely or goes into an infinite loop, the last error
19006 message displayed may help to pinpoint the culprit.
19009 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19010 mode, @command{gcc} produces ongoing information about the progress of the
19011 compilation and provides the name of each procedure as code is
19012 generated. This switch allows you to find which Ada procedure was being
19013 compiled when it encountered a code generation problem.
19016 @cindex @option{-gnatdc} switch
19017 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19018 switch that does for the front-end what @option{^-v^VERBOSE^} does
19019 for the back end. The system prints the name of each unit,
19020 either a compilation unit or nested unit, as it is being analyzed.
19022 Finally, you can start
19023 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19024 front-end of GNAT, and can be run independently (normally it is just
19025 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19026 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19027 @code{where} command is the first line of attack; the variable
19028 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19029 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19030 which the execution stopped, and @code{input_file name} indicates the name of
19034 @node Naming Conventions for GNAT Source Files
19035 @section Naming Conventions for GNAT Source Files
19038 In order to examine the workings of the GNAT system, the following
19039 brief description of its organization may be helpful:
19043 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19046 All files prefixed with @file{^par^PAR^} are components of the parser. The
19047 numbers correspond to chapters of the Ada Reference Manual. For example,
19048 parsing of select statements can be found in @file{par-ch9.adb}.
19051 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19052 numbers correspond to chapters of the Ada standard. For example, all
19053 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19054 addition, some features of the language require sufficient special processing
19055 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19056 dynamic dispatching, etc.
19059 All files prefixed with @file{^exp^EXP^} perform normalization and
19060 expansion of the intermediate representation (abstract syntax tree, or AST).
19061 these files use the same numbering scheme as the parser and semantics files.
19062 For example, the construction of record initialization procedures is done in
19063 @file{exp_ch3.adb}.
19066 The files prefixed with @file{^bind^BIND^} implement the binder, which
19067 verifies the consistency of the compilation, determines an order of
19068 elaboration, and generates the bind file.
19071 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19072 data structures used by the front-end.
19075 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19076 the abstract syntax tree as produced by the parser.
19079 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19080 all entities, computed during semantic analysis.
19083 Library management issues are dealt with in files with prefix
19089 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19090 defined in Annex A.
19095 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19096 defined in Annex B.
19100 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19101 both language-defined children and GNAT run-time routines.
19105 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19106 general-purpose packages, fully documented in their specs. All
19107 the other @file{.c} files are modifications of common @command{gcc} files.
19110 @node Getting Internal Debugging Information
19111 @section Getting Internal Debugging Information
19114 Most compilers have internal debugging switches and modes. GNAT
19115 does also, except GNAT internal debugging switches and modes are not
19116 secret. A summary and full description of all the compiler and binder
19117 debug flags are in the file @file{debug.adb}. You must obtain the
19118 sources of the compiler to see the full detailed effects of these flags.
19120 The switches that print the source of the program (reconstructed from
19121 the internal tree) are of general interest for user programs, as are the
19123 the full internal tree, and the entity table (the symbol table
19124 information). The reconstructed source provides a readable version of the
19125 program after the front-end has completed analysis and expansion,
19126 and is useful when studying the performance of specific constructs.
19127 For example, constraint checks are indicated, complex aggregates
19128 are replaced with loops and assignments, and tasking primitives
19129 are replaced with run-time calls.
19131 @node Stack Traceback
19132 @section Stack Traceback
19134 @cindex stack traceback
19135 @cindex stack unwinding
19138 Traceback is a mechanism to display the sequence of subprogram calls that
19139 leads to a specified execution point in a program. Often (but not always)
19140 the execution point is an instruction at which an exception has been raised.
19141 This mechanism is also known as @i{stack unwinding} because it obtains
19142 its information by scanning the run-time stack and recovering the activation
19143 records of all active subprograms. Stack unwinding is one of the most
19144 important tools for program debugging.
19146 The first entry stored in traceback corresponds to the deepest calling level,
19147 that is to say the subprogram currently executing the instruction
19148 from which we want to obtain the traceback.
19150 Note that there is no runtime performance penalty when stack traceback
19151 is enabled, and no exception is raised during program execution.
19154 * Non-Symbolic Traceback::
19155 * Symbolic Traceback::
19158 @node Non-Symbolic Traceback
19159 @subsection Non-Symbolic Traceback
19160 @cindex traceback, non-symbolic
19163 Note: this feature is not supported on all platforms. See
19164 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19168 * Tracebacks From an Unhandled Exception::
19169 * Tracebacks From Exception Occurrences (non-symbolic)::
19170 * Tracebacks From Anywhere in a Program (non-symbolic)::
19173 @node Tracebacks From an Unhandled Exception
19174 @subsubsection Tracebacks From an Unhandled Exception
19177 A runtime non-symbolic traceback is a list of addresses of call instructions.
19178 To enable this feature you must use the @option{-E}
19179 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19180 of exception information. You can retrieve this information using the
19181 @code{addr2line} tool.
19183 Here is a simple example:
19185 @smallexample @c ada
19191 raise Constraint_Error;
19206 $ gnatmake stb -bargs -E
19209 Execution terminated by unhandled exception
19210 Exception name: CONSTRAINT_ERROR
19212 Call stack traceback locations:
19213 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19217 As we see the traceback lists a sequence of addresses for the unhandled
19218 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19219 guess that this exception come from procedure P1. To translate these
19220 addresses into the source lines where the calls appear, the
19221 @code{addr2line} tool, described below, is invaluable. The use of this tool
19222 requires the program to be compiled with debug information.
19225 $ gnatmake -g stb -bargs -E
19228 Execution terminated by unhandled exception
19229 Exception name: CONSTRAINT_ERROR
19231 Call stack traceback locations:
19232 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19234 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19235 0x4011f1 0x77e892a4
19237 00401373 at d:/stb/stb.adb:5
19238 0040138B at d:/stb/stb.adb:10
19239 0040139C at d:/stb/stb.adb:14
19240 00401335 at d:/stb/b~stb.adb:104
19241 004011C4 at /build/@dots{}/crt1.c:200
19242 004011F1 at /build/@dots{}/crt1.c:222
19243 77E892A4 in ?? at ??:0
19247 The @code{addr2line} tool has several other useful options:
19251 to get the function name corresponding to any location
19253 @item --demangle=gnat
19254 to use the gnat decoding mode for the function names. Note that
19255 for binutils version 2.9.x the option is simply @option{--demangle}.
19259 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19260 0x40139c 0x401335 0x4011c4 0x4011f1
19262 00401373 in stb.p1 at d:/stb/stb.adb:5
19263 0040138B in stb.p2 at d:/stb/stb.adb:10
19264 0040139C in stb at d:/stb/stb.adb:14
19265 00401335 in main at d:/stb/b~stb.adb:104
19266 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19267 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19271 From this traceback we can see that the exception was raised in
19272 @file{stb.adb} at line 5, which was reached from a procedure call in
19273 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19274 which contains the call to the main program.
19275 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19276 and the output will vary from platform to platform.
19278 It is also possible to use @code{GDB} with these traceback addresses to debug
19279 the program. For example, we can break at a given code location, as reported
19280 in the stack traceback:
19286 Furthermore, this feature is not implemented inside Windows DLL. Only
19287 the non-symbolic traceback is reported in this case.
19290 (gdb) break *0x401373
19291 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19295 It is important to note that the stack traceback addresses
19296 do not change when debug information is included. This is particularly useful
19297 because it makes it possible to release software without debug information (to
19298 minimize object size), get a field report that includes a stack traceback
19299 whenever an internal bug occurs, and then be able to retrieve the sequence
19300 of calls with the same program compiled with debug information.
19302 @node Tracebacks From Exception Occurrences (non-symbolic)
19303 @subsubsection Tracebacks From Exception Occurrences
19306 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19307 The stack traceback is attached to the exception information string, and can
19308 be retrieved in an exception handler within the Ada program, by means of the
19309 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19311 @smallexample @c ada
19313 with Ada.Exceptions;
19318 use Ada.Exceptions;
19326 Text_IO.Put_Line (Exception_Information (E));
19340 This program will output:
19345 Exception name: CONSTRAINT_ERROR
19346 Message: stb.adb:12
19347 Call stack traceback locations:
19348 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19351 @node Tracebacks From Anywhere in a Program (non-symbolic)
19352 @subsubsection Tracebacks From Anywhere in a Program
19355 It is also possible to retrieve a stack traceback from anywhere in a
19356 program. For this you need to
19357 use the @code{GNAT.Traceback} API. This package includes a procedure called
19358 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19359 display procedures described below. It is not necessary to use the
19360 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19361 is invoked explicitly.
19364 In the following example we compute a traceback at a specific location in
19365 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19366 convert addresses to strings:
19368 @smallexample @c ada
19370 with GNAT.Traceback;
19371 with GNAT.Debug_Utilities;
19377 use GNAT.Traceback;
19380 TB : Tracebacks_Array (1 .. 10);
19381 -- We are asking for a maximum of 10 stack frames.
19383 -- Len will receive the actual number of stack frames returned.
19385 Call_Chain (TB, Len);
19387 Text_IO.Put ("In STB.P1 : ");
19389 for K in 1 .. Len loop
19390 Text_IO.Put (Debug_Utilities.Image (TB (K)));
19411 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19412 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19416 You can then get further information by invoking the @code{addr2line}
19417 tool as described earlier (note that the hexadecimal addresses
19418 need to be specified in C format, with a leading ``0x'').
19420 @node Symbolic Traceback
19421 @subsection Symbolic Traceback
19422 @cindex traceback, symbolic
19425 A symbolic traceback is a stack traceback in which procedure names are
19426 associated with each code location.
19429 Note that this feature is not supported on all platforms. See
19430 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19431 list of currently supported platforms.
19434 Note that the symbolic traceback requires that the program be compiled
19435 with debug information. If it is not compiled with debug information
19436 only the non-symbolic information will be valid.
19439 * Tracebacks From Exception Occurrences (symbolic)::
19440 * Tracebacks From Anywhere in a Program (symbolic)::
19443 @node Tracebacks From Exception Occurrences (symbolic)
19444 @subsubsection Tracebacks From Exception Occurrences
19446 @smallexample @c ada
19448 with GNAT.Traceback.Symbolic;
19454 raise Constraint_Error;
19471 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19476 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19479 0040149F in stb.p1 at stb.adb:8
19480 004014B7 in stb.p2 at stb.adb:13
19481 004014CF in stb.p3 at stb.adb:18
19482 004015DD in ada.stb at stb.adb:22
19483 00401461 in main at b~stb.adb:168
19484 004011C4 in __mingw_CRTStartup at crt1.c:200
19485 004011F1 in mainCRTStartup at crt1.c:222
19486 77E892A4 in ?? at ??:0
19490 In the above example the ``.\'' syntax in the @command{gnatmake} command
19491 is currently required by @command{addr2line} for files that are in
19492 the current working directory.
19493 Moreover, the exact sequence of linker options may vary from platform
19495 The above @option{-largs} section is for Windows platforms. By contrast,
19496 under Unix there is no need for the @option{-largs} section.
19497 Differences across platforms are due to details of linker implementation.
19499 @node Tracebacks From Anywhere in a Program (symbolic)
19500 @subsubsection Tracebacks From Anywhere in a Program
19503 It is possible to get a symbolic stack traceback
19504 from anywhere in a program, just as for non-symbolic tracebacks.
19505 The first step is to obtain a non-symbolic
19506 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19507 information. Here is an example:
19509 @smallexample @c ada
19511 with GNAT.Traceback;
19512 with GNAT.Traceback.Symbolic;
19517 use GNAT.Traceback;
19518 use GNAT.Traceback.Symbolic;
19521 TB : Tracebacks_Array (1 .. 10);
19522 -- We are asking for a maximum of 10 stack frames.
19524 -- Len will receive the actual number of stack frames returned.
19526 Call_Chain (TB, Len);
19527 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19540 @c ******************************
19542 @node Compatibility with HP Ada
19543 @chapter Compatibility with HP Ada
19544 @cindex Compatibility
19549 @cindex Compatibility between GNAT and HP Ada
19550 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19551 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19552 GNAT is highly compatible
19553 with HP Ada, and it should generally be straightforward to port code
19554 from the HP Ada environment to GNAT. However, there are a few language
19555 and implementation differences of which the user must be aware. These
19556 differences are discussed in this chapter. In
19557 addition, the operating environment and command structure for the
19558 compiler are different, and these differences are also discussed.
19560 For further details on these and other compatibility issues,
19561 see Appendix E of the HP publication
19562 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19564 Except where otherwise indicated, the description of GNAT for OpenVMS
19565 applies to both the Alpha and I64 platforms.
19567 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19568 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19570 The discussion in this chapter addresses specifically the implementation
19571 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19572 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19573 GNAT always follows the Alpha implementation.
19575 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19576 attributes are recognized, although only a subset of them can sensibly
19577 be implemented. The description of pragmas in
19578 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19579 indicates whether or not they are applicable to non-VMS systems.
19582 * Ada Language Compatibility::
19583 * Differences in the Definition of Package System::
19584 * Language-Related Features::
19585 * The Package STANDARD::
19586 * The Package SYSTEM::
19587 * Tasking and Task-Related Features::
19588 * Pragmas and Pragma-Related Features::
19589 * Library of Predefined Units::
19591 * Main Program Definition::
19592 * Implementation-Defined Attributes::
19593 * Compiler and Run-Time Interfacing::
19594 * Program Compilation and Library Management::
19596 * Implementation Limits::
19597 * Tools and Utilities::
19600 @node Ada Language Compatibility
19601 @section Ada Language Compatibility
19604 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19605 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19606 with Ada 83, and therefore Ada 83 programs will compile
19607 and run under GNAT with
19608 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
19609 provides details on specific incompatibilities.
19611 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
19612 as well as the pragma @code{ADA_83}, to force the compiler to
19613 operate in Ada 83 mode. This mode does not guarantee complete
19614 conformance to Ada 83, but in practice is sufficient to
19615 eliminate most sources of incompatibilities.
19616 In particular, it eliminates the recognition of the
19617 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
19618 in Ada 83 programs is legal, and handles the cases of packages
19619 with optional bodies, and generics that instantiate unconstrained
19620 types without the use of @code{(<>)}.
19622 @node Differences in the Definition of Package System
19623 @section Differences in the Definition of Package @code{System}
19626 An Ada compiler is allowed to add
19627 implementation-dependent declarations to package @code{System}.
19629 GNAT does not take advantage of this permission, and the version of
19630 @code{System} provided by GNAT exactly matches that defined in the Ada
19633 However, HP Ada adds an extensive set of declarations to package
19635 as fully documented in the HP Ada manuals. To minimize changes required
19636 for programs that make use of these extensions, GNAT provides the pragma
19637 @code{Extend_System} for extending the definition of package System. By using:
19638 @cindex pragma @code{Extend_System}
19639 @cindex @code{Extend_System} pragma
19641 @smallexample @c ada
19644 pragma Extend_System (Aux_DEC);
19650 the set of definitions in @code{System} is extended to include those in
19651 package @code{System.Aux_DEC}.
19652 @cindex @code{System.Aux_DEC} package
19653 @cindex @code{Aux_DEC} package (child of @code{System})
19654 These definitions are incorporated directly into package @code{System},
19655 as though they had been declared there. For a
19656 list of the declarations added, see the spec of this package,
19657 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
19658 @cindex @file{s-auxdec.ads} file
19659 The pragma @code{Extend_System} is a configuration pragma, which means that
19660 it can be placed in the file @file{gnat.adc}, so that it will automatically
19661 apply to all subsequent compilations. See @ref{Configuration Pragmas},
19662 for further details.
19664 An alternative approach that avoids the use of the non-standard
19665 @code{Extend_System} pragma is to add a context clause to the unit that
19666 references these facilities:
19668 @smallexample @c ada
19670 with System.Aux_DEC;
19671 use System.Aux_DEC;
19676 The effect is not quite semantically identical to incorporating
19677 the declarations directly into package @code{System},
19678 but most programs will not notice a difference
19679 unless they use prefix notation (e.g.@: @code{System.Integer_8})
19680 to reference the entities directly in package @code{System}.
19681 For units containing such references,
19682 the prefixes must either be removed, or the pragma @code{Extend_System}
19685 @node Language-Related Features
19686 @section Language-Related Features
19689 The following sections highlight differences in types,
19690 representations of types, operations, alignment, and
19694 * Integer Types and Representations::
19695 * Floating-Point Types and Representations::
19696 * Pragmas Float_Representation and Long_Float::
19697 * Fixed-Point Types and Representations::
19698 * Record and Array Component Alignment::
19699 * Address Clauses::
19700 * Other Representation Clauses::
19703 @node Integer Types and Representations
19704 @subsection Integer Types and Representations
19707 The set of predefined integer types is identical in HP Ada and GNAT.
19708 Furthermore the representation of these integer types is also identical,
19709 including the capability of size clauses forcing biased representation.
19712 HP Ada for OpenVMS Alpha systems has defined the
19713 following additional integer types in package @code{System}:
19730 @code{LARGEST_INTEGER}
19734 In GNAT, the first four of these types may be obtained from the
19735 standard Ada package @code{Interfaces}.
19736 Alternatively, by use of the pragma @code{Extend_System}, identical
19737 declarations can be referenced directly in package @code{System}.
19738 On both GNAT and HP Ada, the maximum integer size is 64 bits.
19740 @node Floating-Point Types and Representations
19741 @subsection Floating-Point Types and Representations
19742 @cindex Floating-Point types
19745 The set of predefined floating-point types is identical in HP Ada and GNAT.
19746 Furthermore the representation of these floating-point
19747 types is also identical. One important difference is that the default
19748 representation for HP Ada is @code{VAX_Float}, but the default representation
19751 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
19752 pragma @code{Float_Representation} as described in the HP Ada
19754 For example, the declarations:
19756 @smallexample @c ada
19758 type F_Float is digits 6;
19759 pragma Float_Representation (VAX_Float, F_Float);
19764 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
19766 This set of declarations actually appears in @code{System.Aux_DEC},
19768 the full set of additional floating-point declarations provided in
19769 the HP Ada version of package @code{System}.
19770 This and similar declarations may be accessed in a user program
19771 by using pragma @code{Extend_System}. The use of this
19772 pragma, and the related pragma @code{Long_Float} is described in further
19773 detail in the following section.
19775 @node Pragmas Float_Representation and Long_Float
19776 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
19779 HP Ada provides the pragma @code{Float_Representation}, which
19780 acts as a program library switch to allow control over
19781 the internal representation chosen for the predefined
19782 floating-point types declared in the package @code{Standard}.
19783 The format of this pragma is as follows:
19785 @smallexample @c ada
19787 pragma Float_Representation(VAX_Float | IEEE_Float);
19792 This pragma controls the representation of floating-point
19797 @code{VAX_Float} specifies that floating-point
19798 types are represented by default with the VAX system hardware types
19799 @code{F-floating}, @code{D-floating}, @code{G-floating}.
19800 Note that the @code{H-floating}
19801 type was available only on VAX systems, and is not available
19802 in either HP Ada or GNAT.
19805 @code{IEEE_Float} specifies that floating-point
19806 types are represented by default with the IEEE single and
19807 double floating-point types.
19811 GNAT provides an identical implementation of the pragma
19812 @code{Float_Representation}, except that it functions as a
19813 configuration pragma. Note that the
19814 notion of configuration pragma corresponds closely to the
19815 HP Ada notion of a program library switch.
19817 When no pragma is used in GNAT, the default is @code{IEEE_Float},
19819 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
19820 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
19821 advisable to change the format of numbers passed to standard library
19822 routines, and if necessary explicit type conversions may be needed.
19824 The use of @code{IEEE_Float} is recommended in GNAT since it is more
19825 efficient, and (given that it conforms to an international standard)
19826 potentially more portable.
19827 The situation in which @code{VAX_Float} may be useful is in interfacing
19828 to existing code and data that expect the use of @code{VAX_Float}.
19829 In such a situation use the predefined @code{VAX_Float}
19830 types in package @code{System}, as extended by
19831 @code{Extend_System}. For example, use @code{System.F_Float}
19832 to specify the 32-bit @code{F-Float} format.
19835 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
19836 to allow control over the internal representation chosen
19837 for the predefined type @code{Long_Float} and for floating-point
19838 type declarations with digits specified in the range 7 .. 15.
19839 The format of this pragma is as follows:
19841 @smallexample @c ada
19843 pragma Long_Float (D_FLOAT | G_FLOAT);
19847 @node Fixed-Point Types and Representations
19848 @subsection Fixed-Point Types and Representations
19851 On HP Ada for OpenVMS Alpha systems, rounding is
19852 away from zero for both positive and negative numbers.
19853 Therefore, @code{+0.5} rounds to @code{1},
19854 and @code{-0.5} rounds to @code{-1}.
19856 On GNAT the results of operations
19857 on fixed-point types are in accordance with the Ada
19858 rules. In particular, results of operations on decimal
19859 fixed-point types are truncated.
19861 @node Record and Array Component Alignment
19862 @subsection Record and Array Component Alignment
19865 On HP Ada for OpenVMS Alpha, all non-composite components
19866 are aligned on natural boundaries. For example, 1-byte
19867 components are aligned on byte boundaries, 2-byte
19868 components on 2-byte boundaries, 4-byte components on 4-byte
19869 byte boundaries, and so on. The OpenVMS Alpha hardware
19870 runs more efficiently with naturally aligned data.
19872 On GNAT, alignment rules are compatible
19873 with HP Ada for OpenVMS Alpha.
19875 @node Address Clauses
19876 @subsection Address Clauses
19879 In HP Ada and GNAT, address clauses are supported for
19880 objects and imported subprograms.
19881 The predefined type @code{System.Address} is a private type
19882 in both compilers on Alpha OpenVMS, with the same representation
19883 (it is simply a machine pointer). Addition, subtraction, and comparison
19884 operations are available in the standard Ada package
19885 @code{System.Storage_Elements}, or in package @code{System}
19886 if it is extended to include @code{System.Aux_DEC} using a
19887 pragma @code{Extend_System} as previously described.
19889 Note that code that @code{with}'s both this extended package @code{System}
19890 and the package @code{System.Storage_Elements} should not @code{use}
19891 both packages, or ambiguities will result. In general it is better
19892 not to mix these two sets of facilities. The Ada package was
19893 designed specifically to provide the kind of features that HP Ada
19894 adds directly to package @code{System}.
19896 The type @code{System.Address} is a 64-bit integer type in GNAT for
19897 I64 OpenVMS. For more information,
19898 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19900 GNAT is compatible with HP Ada in its handling of address
19901 clauses, except for some limitations in
19902 the form of address clauses for composite objects with
19903 initialization. Such address clauses are easily replaced
19904 by the use of an explicitly-defined constant as described
19905 in the Ada Reference Manual (13.1(22)). For example, the sequence
19908 @smallexample @c ada
19910 X, Y : Integer := Init_Func;
19911 Q : String (X .. Y) := "abc";
19913 for Q'Address use Compute_Address;
19918 will be rejected by GNAT, since the address cannot be computed at the time
19919 that @code{Q} is declared. To achieve the intended effect, write instead:
19921 @smallexample @c ada
19924 X, Y : Integer := Init_Func;
19925 Q_Address : constant Address := Compute_Address;
19926 Q : String (X .. Y) := "abc";
19928 for Q'Address use Q_Address;
19934 which will be accepted by GNAT (and other Ada compilers), and is also
19935 compatible with Ada 83. A fuller description of the restrictions
19936 on address specifications is found in @ref{Top, GNAT Reference Manual,
19937 About This Guide, gnat_rm, GNAT Reference Manual}.
19939 @node Other Representation Clauses
19940 @subsection Other Representation Clauses
19943 GNAT implements in a compatible manner all the representation
19944 clauses supported by HP Ada. In addition, GNAT
19945 implements the representation clause forms that were introduced in Ada 95,
19946 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
19948 @node The Package STANDARD
19949 @section The Package @code{STANDARD}
19952 The package @code{STANDARD}, as implemented by HP Ada, is fully
19953 described in the @cite{Ada Reference Manual} and in the
19954 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
19955 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
19957 In addition, HP Ada supports the Latin-1 character set in
19958 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
19959 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
19960 the type @code{WIDE_CHARACTER}.
19962 The floating-point types supported by GNAT are those
19963 supported by HP Ada, but the defaults are different, and are controlled by
19964 pragmas. See @ref{Floating-Point Types and Representations}, for details.
19966 @node The Package SYSTEM
19967 @section The Package @code{SYSTEM}
19970 HP Ada provides a specific version of the package
19971 @code{SYSTEM} for each platform on which the language is implemented.
19972 For the complete spec of the package @code{SYSTEM}, see
19973 Appendix F of the @cite{HP Ada Language Reference Manual}.
19975 On HP Ada, the package @code{SYSTEM} includes the following conversion
19978 @item @code{TO_ADDRESS(INTEGER)}
19980 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
19982 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
19984 @item @code{TO_INTEGER(ADDRESS)}
19986 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
19988 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
19989 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
19993 By default, GNAT supplies a version of @code{SYSTEM} that matches
19994 the definition given in the @cite{Ada Reference Manual}.
19996 is a subset of the HP system definitions, which is as
19997 close as possible to the original definitions. The only difference
19998 is that the definition of @code{SYSTEM_NAME} is different:
20000 @smallexample @c ada
20002 type Name is (SYSTEM_NAME_GNAT);
20003 System_Name : constant Name := SYSTEM_NAME_GNAT;
20008 Also, GNAT adds the Ada declarations for
20009 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20011 However, the use of the following pragma causes GNAT
20012 to extend the definition of package @code{SYSTEM} so that it
20013 encompasses the full set of HP-specific extensions,
20014 including the functions listed above:
20016 @smallexample @c ada
20018 pragma Extend_System (Aux_DEC);
20023 The pragma @code{Extend_System} is a configuration pragma that
20024 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20025 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20027 HP Ada does not allow the recompilation of the package
20028 @code{SYSTEM}. Instead HP Ada provides several pragmas
20029 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20030 to modify values in the package @code{SYSTEM}.
20031 On OpenVMS Alpha systems, the pragma
20032 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20033 its single argument.
20035 GNAT does permit the recompilation of package @code{SYSTEM} using
20036 the special switch @option{-gnatg}, and this switch can be used if
20037 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20038 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20039 or @code{MEMORY_SIZE} by any other means.
20041 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20042 enumeration literal @code{SYSTEM_NAME_GNAT}.
20044 The definitions provided by the use of
20046 @smallexample @c ada
20047 pragma Extend_System (AUX_Dec);
20051 are virtually identical to those provided by the HP Ada 83 package
20052 @code{SYSTEM}. One important difference is that the name of the
20054 function for type @code{UNSIGNED_LONGWORD} is changed to
20055 @code{TO_ADDRESS_LONG}.
20056 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20057 discussion of why this change was necessary.
20060 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20062 an extension to Ada 83 not strictly compatible with the reference manual.
20063 GNAT, in order to be exactly compatible with the standard,
20064 does not provide this capability. In HP Ada 83, the
20065 point of this definition is to deal with a call like:
20067 @smallexample @c ada
20068 TO_ADDRESS (16#12777#);
20072 Normally, according to Ada 83 semantics, one would expect this to be
20073 ambiguous, since it matches both the @code{INTEGER} and
20074 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20075 However, in HP Ada 83, there is no ambiguity, since the
20076 definition using @i{universal_integer} takes precedence.
20078 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20080 not possible to be 100% compatible. Since there are many programs using
20081 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20083 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20084 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20086 @smallexample @c ada
20087 function To_Address (X : Integer) return Address;
20088 pragma Pure_Function (To_Address);
20090 function To_Address_Long (X : Unsigned_Longword) return Address;
20091 pragma Pure_Function (To_Address_Long);
20095 This means that programs using @code{TO_ADDRESS} for
20096 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20098 @node Tasking and Task-Related Features
20099 @section Tasking and Task-Related Features
20102 This section compares the treatment of tasking in GNAT
20103 and in HP Ada for OpenVMS Alpha.
20104 The GNAT description applies to both Alpha and I64 OpenVMS.
20105 For detailed information on tasking in
20106 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20107 relevant run-time reference manual.
20110 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20111 * Assigning Task IDs::
20112 * Task IDs and Delays::
20113 * Task-Related Pragmas::
20114 * Scheduling and Task Priority::
20116 * External Interrupts::
20119 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20120 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20123 On OpenVMS Alpha systems, each Ada task (except a passive
20124 task) is implemented as a single stream of execution
20125 that is created and managed by the kernel. On these
20126 systems, HP Ada tasking support is based on DECthreads,
20127 an implementation of the POSIX standard for threads.
20129 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20130 code that calls DECthreads routines can be used together.
20131 The interaction between Ada tasks and DECthreads routines
20132 can have some benefits. For example when on OpenVMS Alpha,
20133 HP Ada can call C code that is already threaded.
20135 GNAT uses the facilities of DECthreads,
20136 and Ada tasks are mapped to threads.
20138 @node Assigning Task IDs
20139 @subsection Assigning Task IDs
20142 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20143 the environment task that executes the main program. On
20144 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20145 that have been created but are not yet activated.
20147 On OpenVMS Alpha systems, task IDs are assigned at
20148 activation. On GNAT systems, task IDs are also assigned at
20149 task creation but do not have the same form or values as
20150 task ID values in HP Ada. There is no null task, and the
20151 environment task does not have a specific task ID value.
20153 @node Task IDs and Delays
20154 @subsection Task IDs and Delays
20157 On OpenVMS Alpha systems, tasking delays are implemented
20158 using Timer System Services. The Task ID is used for the
20159 identification of the timer request (the @code{REQIDT} parameter).
20160 If Timers are used in the application take care not to use
20161 @code{0} for the identification, because cancelling such a timer
20162 will cancel all timers and may lead to unpredictable results.
20164 @node Task-Related Pragmas
20165 @subsection Task-Related Pragmas
20168 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20169 specification of the size of the guard area for a task
20170 stack. (The guard area forms an area of memory that has no
20171 read or write access and thus helps in the detection of
20172 stack overflow.) On OpenVMS Alpha systems, if the pragma
20173 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20174 area is created. In the absence of a pragma @code{TASK_STORAGE},
20175 a default guard area is created.
20177 GNAT supplies the following task-related pragmas:
20180 @item @code{TASK_INFO}
20182 This pragma appears within a task definition and
20183 applies to the task in which it appears. The argument
20184 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20186 @item @code{TASK_STORAGE}
20188 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20189 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20190 @code{SUPPRESS}, and @code{VOLATILE}.
20192 @node Scheduling and Task Priority
20193 @subsection Scheduling and Task Priority
20196 HP Ada implements the Ada language requirement that
20197 when two tasks are eligible for execution and they have
20198 different priorities, the lower priority task does not
20199 execute while the higher priority task is waiting. The HP
20200 Ada Run-Time Library keeps a task running until either the
20201 task is suspended or a higher priority task becomes ready.
20203 On OpenVMS Alpha systems, the default strategy is round-
20204 robin with preemption. Tasks of equal priority take turns
20205 at the processor. A task is run for a certain period of
20206 time and then placed at the tail of the ready queue for
20207 its priority level.
20209 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20210 which can be used to enable or disable round-robin
20211 scheduling of tasks with the same priority.
20212 See the relevant HP Ada run-time reference manual for
20213 information on using the pragmas to control HP Ada task
20216 GNAT follows the scheduling rules of Annex D (Real-Time
20217 Annex) of the @cite{Ada Reference Manual}. In general, this
20218 scheduling strategy is fully compatible with HP Ada
20219 although it provides some additional constraints (as
20220 fully documented in Annex D).
20221 GNAT implements time slicing control in a manner compatible with
20222 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20223 are identical to the HP Ada 83 pragma of the same name.
20224 Note that it is not possible to mix GNAT tasking and
20225 HP Ada 83 tasking in the same program, since the two run-time
20226 libraries are not compatible.
20228 @node The Task Stack
20229 @subsection The Task Stack
20232 In HP Ada, a task stack is allocated each time a
20233 non-passive task is activated. As soon as the task is
20234 terminated, the storage for the task stack is deallocated.
20235 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20236 a default stack size is used. Also, regardless of the size
20237 specified, some additional space is allocated for task
20238 management purposes. On OpenVMS Alpha systems, at least
20239 one page is allocated.
20241 GNAT handles task stacks in a similar manner. In accordance with
20242 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20243 an alternative method for controlling the task stack size.
20244 The specification of the attribute @code{T'STORAGE_SIZE} is also
20245 supported in a manner compatible with HP Ada.
20247 @node External Interrupts
20248 @subsection External Interrupts
20251 On HP Ada, external interrupts can be associated with task entries.
20252 GNAT is compatible with HP Ada in its handling of external interrupts.
20254 @node Pragmas and Pragma-Related Features
20255 @section Pragmas and Pragma-Related Features
20258 Both HP Ada and GNAT supply all language-defined pragmas
20259 as specified by the Ada 83 standard. GNAT also supplies all
20260 language-defined pragmas introduced by Ada 95 and Ada 2005.
20261 In addition, GNAT implements the implementation-defined pragmas
20265 @item @code{AST_ENTRY}
20267 @item @code{COMMON_OBJECT}
20269 @item @code{COMPONENT_ALIGNMENT}
20271 @item @code{EXPORT_EXCEPTION}
20273 @item @code{EXPORT_FUNCTION}
20275 @item @code{EXPORT_OBJECT}
20277 @item @code{EXPORT_PROCEDURE}
20279 @item @code{EXPORT_VALUED_PROCEDURE}
20281 @item @code{FLOAT_REPRESENTATION}
20285 @item @code{IMPORT_EXCEPTION}
20287 @item @code{IMPORT_FUNCTION}
20289 @item @code{IMPORT_OBJECT}
20291 @item @code{IMPORT_PROCEDURE}
20293 @item @code{IMPORT_VALUED_PROCEDURE}
20295 @item @code{INLINE_GENERIC}
20297 @item @code{INTERFACE_NAME}
20299 @item @code{LONG_FLOAT}
20301 @item @code{MAIN_STORAGE}
20303 @item @code{PASSIVE}
20305 @item @code{PSECT_OBJECT}
20307 @item @code{SHARE_GENERIC}
20309 @item @code{SUPPRESS_ALL}
20311 @item @code{TASK_STORAGE}
20313 @item @code{TIME_SLICE}
20319 These pragmas are all fully implemented, with the exception of @code{TITLE},
20320 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20321 recognized, but which have no
20322 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20323 use of Ada protected objects. In GNAT, all generics are inlined.
20325 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20326 a separate subprogram specification which must appear before the
20329 GNAT also supplies a number of implementation-defined pragmas including the
20333 @item @code{ABORT_DEFER}
20335 @item @code{ADA_83}
20337 @item @code{ADA_95}
20339 @item @code{ADA_05}
20341 @item @code{Ada_2005}
20343 @item @code{Ada_12}
20345 @item @code{Ada_2012}
20347 @item @code{ANNOTATE}
20349 @item @code{ASSERT}
20351 @item @code{C_PASS_BY_COPY}
20353 @item @code{CPP_CLASS}
20355 @item @code{CPP_CONSTRUCTOR}
20357 @item @code{CPP_DESTRUCTOR}
20361 @item @code{EXTEND_SYSTEM}
20363 @item @code{LINKER_ALIAS}
20365 @item @code{LINKER_SECTION}
20367 @item @code{MACHINE_ATTRIBUTE}
20369 @item @code{NO_RETURN}
20371 @item @code{PURE_FUNCTION}
20373 @item @code{SOURCE_FILE_NAME}
20375 @item @code{SOURCE_REFERENCE}
20377 @item @code{TASK_INFO}
20379 @item @code{UNCHECKED_UNION}
20381 @item @code{UNIMPLEMENTED_UNIT}
20383 @item @code{UNIVERSAL_DATA}
20385 @item @code{UNSUPPRESS}
20387 @item @code{WARNINGS}
20389 @item @code{WEAK_EXTERNAL}
20393 For full details on these and other GNAT implementation-defined pragmas,
20394 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20398 * Restrictions on the Pragma INLINE::
20399 * Restrictions on the Pragma INTERFACE::
20400 * Restrictions on the Pragma SYSTEM_NAME::
20403 @node Restrictions on the Pragma INLINE
20404 @subsection Restrictions on Pragma @code{INLINE}
20407 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20409 @item Parameters cannot have a task type.
20411 @item Function results cannot be task types, unconstrained
20412 array types, or unconstrained types with discriminants.
20414 @item Bodies cannot declare the following:
20416 @item Subprogram body or stub (imported subprogram is allowed)
20420 @item Generic declarations
20422 @item Instantiations
20426 @item Access types (types derived from access types allowed)
20428 @item Array or record types
20430 @item Dependent tasks
20432 @item Direct recursive calls of subprogram or containing
20433 subprogram, directly or via a renaming
20439 In GNAT, the only restriction on pragma @code{INLINE} is that the
20440 body must occur before the call if both are in the same
20441 unit, and the size must be appropriately small. There are
20442 no other specific restrictions which cause subprograms to
20443 be incapable of being inlined.
20445 @node Restrictions on the Pragma INTERFACE
20446 @subsection Restrictions on Pragma @code{INTERFACE}
20449 The following restrictions on pragma @code{INTERFACE}
20450 are enforced by both HP Ada and GNAT:
20452 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
20453 Default is the default on OpenVMS Alpha systems.
20455 @item Parameter passing: Language specifies default
20456 mechanisms but can be overridden with an @code{EXPORT} pragma.
20459 @item Ada: Use internal Ada rules.
20461 @item Bliss, C: Parameters must be mode @code{in}; cannot be
20462 record or task type. Result cannot be a string, an
20463 array, or a record.
20465 @item Fortran: Parameters cannot have a task type. Result cannot
20466 be a string, an array, or a record.
20471 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20472 record parameters for all languages.
20474 @node Restrictions on the Pragma SYSTEM_NAME
20475 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
20478 For HP Ada for OpenVMS Alpha, the enumeration literal
20479 for the type @code{NAME} is @code{OPENVMS_AXP}.
20480 In GNAT, the enumeration
20481 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20483 @node Library of Predefined Units
20484 @section Library of Predefined Units
20487 A library of predefined units is provided as part of the
20488 HP Ada and GNAT implementations. HP Ada does not provide
20489 the package @code{MACHINE_CODE} but instead recommends importing
20492 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20493 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20495 The HP Ada Predefined Library units are modified to remove post-Ada 83
20496 incompatibilities and to make them interoperable with GNAT
20497 (@pxref{Changes to DECLIB}, for details).
20498 The units are located in the @file{DECLIB} directory.
20500 The GNAT RTL is contained in
20501 the @file{ADALIB} directory, and
20502 the default search path is set up to find @code{DECLIB} units in preference
20503 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20504 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20507 * Changes to DECLIB::
20510 @node Changes to DECLIB
20511 @subsection Changes to @code{DECLIB}
20514 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20515 compatibility are minor and include the following:
20518 @item Adjusting the location of pragmas and record representation
20519 clauses to obey Ada 95 (and thus Ada 2005) rules
20521 @item Adding the proper notation to generic formal parameters
20522 that take unconstrained types in instantiation
20524 @item Adding pragma @code{ELABORATE_BODY} to package specs
20525 that have package bodies not otherwise allowed
20527 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20528 ``@code{PROTECTD}''.
20529 Currently these are found only in the @code{STARLET} package spec.
20531 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20532 where the address size is constrained to 32 bits.
20536 None of the above changes is visible to users.
20542 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20545 @item Command Language Interpreter (CLI interface)
20547 @item DECtalk Run-Time Library (DTK interface)
20549 @item Librarian utility routines (LBR interface)
20551 @item General Purpose Run-Time Library (LIB interface)
20553 @item Math Run-Time Library (MTH interface)
20555 @item National Character Set Run-Time Library (NCS interface)
20557 @item Compiled Code Support Run-Time Library (OTS interface)
20559 @item Parallel Processing Run-Time Library (PPL interface)
20561 @item Screen Management Run-Time Library (SMG interface)
20563 @item Sort Run-Time Library (SOR interface)
20565 @item String Run-Time Library (STR interface)
20567 @item STARLET System Library
20570 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
20572 @item X Windows Toolkit (XT interface)
20574 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
20578 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20579 directory, on both the Alpha and I64 OpenVMS platforms.
20581 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20583 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20584 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20585 @code{Xt}, and @code{X_Lib}
20586 causing the default X/Motif sharable image libraries to be linked in. This
20587 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20588 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20590 It may be necessary to edit these options files to update or correct the
20591 library names if, for example, the newer X/Motif bindings from
20592 @file{ADA$EXAMPLES}
20593 had been (previous to installing GNAT) copied and renamed to supersede the
20594 default @file{ADA$PREDEFINED} versions.
20597 * Shared Libraries and Options Files::
20598 * Interfaces to C::
20601 @node Shared Libraries and Options Files
20602 @subsection Shared Libraries and Options Files
20605 When using the HP Ada
20606 predefined X and Motif bindings, the linking with their sharable images is
20607 done automatically by @command{GNAT LINK}.
20608 When using other X and Motif bindings, you need
20609 to add the corresponding sharable images to the command line for
20610 @code{GNAT LINK}. When linking with shared libraries, or with
20611 @file{.OPT} files, you must
20612 also add them to the command line for @command{GNAT LINK}.
20614 A shared library to be used with GNAT is built in the same way as other
20615 libraries under VMS. The VMS Link command can be used in standard fashion.
20617 @node Interfaces to C
20618 @subsection Interfaces to C
20622 provides the following Ada types and operations:
20625 @item C types package (@code{C_TYPES})
20627 @item C strings (@code{C_TYPES.NULL_TERMINATED})
20629 @item Other_types (@code{SHORT_INT})
20633 Interfacing to C with GNAT, you can use the above approach
20634 described for HP Ada or the facilities of Annex B of
20635 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
20636 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
20637 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
20639 The @option{-gnatF} qualifier forces default and explicit
20640 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
20641 to be uppercased for compatibility with the default behavior
20642 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
20644 @node Main Program Definition
20645 @section Main Program Definition
20648 The following section discusses differences in the
20649 definition of main programs on HP Ada and GNAT.
20650 On HP Ada, main programs are defined to meet the
20651 following conditions:
20653 @item Procedure with no formal parameters (returns @code{0} upon
20656 @item Procedure with no formal parameters (returns @code{42} when
20657 an unhandled exception is raised)
20659 @item Function with no formal parameters whose returned value
20660 is of a discrete type
20662 @item Procedure with one @code{out} formal of a discrete type for
20663 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
20668 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
20669 a main function or main procedure returns a discrete
20670 value whose size is less than 64 bits (32 on VAX systems),
20671 the value is zero- or sign-extended as appropriate.
20672 On GNAT, main programs are defined as follows:
20674 @item Must be a non-generic, parameterless subprogram that
20675 is either a procedure or function returning an Ada
20676 @code{STANDARD.INTEGER} (the predefined type)
20678 @item Cannot be a generic subprogram or an instantiation of a
20682 @node Implementation-Defined Attributes
20683 @section Implementation-Defined Attributes
20686 GNAT provides all HP Ada implementation-defined
20689 @node Compiler and Run-Time Interfacing
20690 @section Compiler and Run-Time Interfacing
20693 HP Ada provides the following qualifiers to pass options to the linker
20696 @item @option{/WAIT} and @option{/SUBMIT}
20698 @item @option{/COMMAND}
20700 @item @option{/@r{[}NO@r{]}MAP}
20702 @item @option{/OUTPUT=@var{file-spec}}
20704 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20708 To pass options to the linker, GNAT provides the following
20712 @item @option{/EXECUTABLE=@var{exec-name}}
20714 @item @option{/VERBOSE}
20716 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20720 For more information on these switches, see
20721 @ref{Switches for gnatlink}.
20722 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
20723 to control optimization. HP Ada also supplies the
20726 @item @code{OPTIMIZE}
20728 @item @code{INLINE}
20730 @item @code{INLINE_GENERIC}
20732 @item @code{SUPPRESS_ALL}
20734 @item @code{PASSIVE}
20738 In GNAT, optimization is controlled strictly by command
20739 line parameters, as described in the corresponding section of this guide.
20740 The HP pragmas for control of optimization are
20741 recognized but ignored.
20743 Note that in GNAT, the default is optimization off, whereas in HP Ada
20744 the default is that optimization is turned on.
20746 @node Program Compilation and Library Management
20747 @section Program Compilation and Library Management
20750 HP Ada and GNAT provide a comparable set of commands to
20751 build programs. HP Ada also provides a program library,
20752 which is a concept that does not exist on GNAT. Instead,
20753 GNAT provides directories of sources that are compiled as
20756 The following table summarizes
20757 the HP Ada commands and provides
20758 equivalent GNAT commands. In this table, some GNAT
20759 equivalents reflect the fact that GNAT does not use the
20760 concept of a program library. Instead, it uses a model
20761 in which collections of source and object files are used
20762 in a manner consistent with other languages like C and
20763 Fortran. Therefore, standard system file commands are used
20764 to manipulate these elements. Those GNAT commands are marked with
20766 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
20769 @multitable @columnfractions .35 .65
20771 @item @emph{HP Ada Command}
20772 @tab @emph{GNAT Equivalent / Description}
20774 @item @command{ADA}
20775 @tab @command{GNAT COMPILE}@*
20776 Invokes the compiler to compile one or more Ada source files.
20778 @item @command{ACS ATTACH}@*
20779 @tab [No equivalent]@*
20780 Switches control of terminal from current process running the program
20783 @item @command{ACS CHECK}
20784 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20785 Forms the execution closure of one
20786 or more compiled units and checks completeness and currency.
20788 @item @command{ACS COMPILE}
20789 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20790 Forms the execution closure of one or
20791 more specified units, checks completeness and currency,
20792 identifies units that have revised source files, compiles same,
20793 and recompiles units that are or will become obsolete.
20794 Also completes incomplete generic instantiations.
20796 @item @command{ACS COPY FOREIGN}
20798 Copies a foreign object file into the program library as a
20801 @item @command{ACS COPY UNIT}
20803 Copies a compiled unit from one program library to another.
20805 @item @command{ACS CREATE LIBRARY}
20806 @tab Create /directory (*)@*
20807 Creates a program library.
20809 @item @command{ACS CREATE SUBLIBRARY}
20810 @tab Create /directory (*)@*
20811 Creates a program sublibrary.
20813 @item @command{ACS DELETE LIBRARY}
20815 Deletes a program library and its contents.
20817 @item @command{ACS DELETE SUBLIBRARY}
20819 Deletes a program sublibrary and its contents.
20821 @item @command{ACS DELETE UNIT}
20822 @tab Delete file (*)@*
20823 On OpenVMS systems, deletes one or more compiled units from
20824 the current program library.
20826 @item @command{ACS DIRECTORY}
20827 @tab Directory (*)@*
20828 On OpenVMS systems, lists units contained in the current
20831 @item @command{ACS ENTER FOREIGN}
20833 Allows the import of a foreign body as an Ada library
20834 spec and enters a reference to a pointer.
20836 @item @command{ACS ENTER UNIT}
20838 Enters a reference (pointer) from the current program library to
20839 a unit compiled into another program library.
20841 @item @command{ACS EXIT}
20842 @tab [No equivalent]@*
20843 Exits from the program library manager.
20845 @item @command{ACS EXPORT}
20847 Creates an object file that contains system-specific object code
20848 for one or more units. With GNAT, object files can simply be copied
20849 into the desired directory.
20851 @item @command{ACS EXTRACT SOURCE}
20853 Allows access to the copied source file for each Ada compilation unit
20855 @item @command{ACS HELP}
20856 @tab @command{HELP GNAT}@*
20857 Provides online help.
20859 @item @command{ACS LINK}
20860 @tab @command{GNAT LINK}@*
20861 Links an object file containing Ada units into an executable file.
20863 @item @command{ACS LOAD}
20865 Loads (partially compiles) Ada units into the program library.
20866 Allows loading a program from a collection of files into a library
20867 without knowing the relationship among units.
20869 @item @command{ACS MERGE}
20871 Merges into the current program library, one or more units from
20872 another library where they were modified.
20874 @item @command{ACS RECOMPILE}
20875 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20876 Recompiles from external or copied source files any obsolete
20877 unit in the closure. Also, completes any incomplete generic
20880 @item @command{ACS REENTER}
20881 @tab @command{GNAT MAKE}@*
20882 Reenters current references to units compiled after last entered
20883 with the @command{ACS ENTER UNIT} command.
20885 @item @command{ACS SET LIBRARY}
20886 @tab Set default (*)@*
20887 Defines a program library to be the compilation context as well
20888 as the target library for compiler output and commands in general.
20890 @item @command{ACS SET PRAGMA}
20891 @tab Edit @file{gnat.adc} (*)@*
20892 Redefines specified values of the library characteristics
20893 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20894 and @code{Float_Representation}.
20896 @item @command{ACS SET SOURCE}
20897 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20898 Defines the source file search list for the @command{ACS COMPILE} command.
20900 @item @command{ACS SHOW LIBRARY}
20901 @tab Directory (*)@*
20902 Lists information about one or more program libraries.
20904 @item @command{ACS SHOW PROGRAM}
20905 @tab [No equivalent]@*
20906 Lists information about the execution closure of one or
20907 more units in the program library.
20909 @item @command{ACS SHOW SOURCE}
20910 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20911 Shows the source file search used when compiling units.
20913 @item @command{ACS SHOW VERSION}
20914 @tab Compile with @option{VERBOSE} option
20915 Displays the version number of the compiler and program library
20918 @item @command{ACS SPAWN}
20919 @tab [No equivalent]@*
20920 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20923 @item @command{ACS VERIFY}
20924 @tab [No equivalent]@*
20925 Performs a series of consistency checks on a program library to
20926 determine whether the library structure and library files are in
20933 @section Input-Output
20936 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
20937 Management Services (RMS) to perform operations on
20941 HP Ada and GNAT predefine an identical set of input-
20942 output packages. To make the use of the
20943 generic @code{TEXT_IO} operations more convenient, HP Ada
20944 provides predefined library packages that instantiate the
20945 integer and floating-point operations for the predefined
20946 integer and floating-point types as shown in the following table.
20948 @multitable @columnfractions .45 .55
20949 @item @emph{Package Name} @tab Instantiation
20951 @item @code{INTEGER_TEXT_IO}
20952 @tab @code{INTEGER_IO(INTEGER)}
20954 @item @code{SHORT_INTEGER_TEXT_IO}
20955 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20957 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20958 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20960 @item @code{FLOAT_TEXT_IO}
20961 @tab @code{FLOAT_IO(FLOAT)}
20963 @item @code{LONG_FLOAT_TEXT_IO}
20964 @tab @code{FLOAT_IO(LONG_FLOAT)}
20968 The HP Ada predefined packages and their operations
20969 are implemented using OpenVMS Alpha files and input-output
20970 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
20971 Familiarity with the following is recommended:
20973 @item RMS file organizations and access methods
20975 @item OpenVMS file specifications and directories
20977 @item OpenVMS File Definition Language (FDL)
20981 GNAT provides I/O facilities that are completely
20982 compatible with HP Ada. The distribution includes the
20983 standard HP Ada versions of all I/O packages, operating
20984 in a manner compatible with HP Ada. In particular, the
20985 following packages are by default the HP Ada (Ada 83)
20986 versions of these packages rather than the renamings
20987 suggested in Annex J of the Ada Reference Manual:
20989 @item @code{TEXT_IO}
20991 @item @code{SEQUENTIAL_IO}
20993 @item @code{DIRECT_IO}
20997 The use of the standard child package syntax (for
20998 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21000 GNAT provides HP-compatible predefined instantiations
21001 of the @code{TEXT_IO} packages, and also
21002 provides the standard predefined instantiations required
21003 by the @cite{Ada Reference Manual}.
21005 For further information on how GNAT interfaces to the file
21006 system or how I/O is implemented in programs written in
21007 mixed languages, see @ref{Implementation of the Standard I/O,,,
21008 gnat_rm, GNAT Reference Manual}.
21009 This chapter covers the following:
21011 @item Standard I/O packages
21013 @item @code{FORM} strings
21015 @item @code{ADA.DIRECT_IO}
21017 @item @code{ADA.SEQUENTIAL_IO}
21019 @item @code{ADA.TEXT_IO}
21021 @item Stream pointer positioning
21023 @item Reading and writing non-regular files
21025 @item @code{GET_IMMEDIATE}
21027 @item Treating @code{TEXT_IO} files as streams
21034 @node Implementation Limits
21035 @section Implementation Limits
21038 The following table lists implementation limits for HP Ada
21040 @multitable @columnfractions .60 .20 .20
21042 @item @emph{Compilation Parameter}
21047 @item In a subprogram or entry declaration, maximum number of
21048 formal parameters that are of an unconstrained record type
21053 @item Maximum identifier length (number of characters)
21058 @item Maximum number of characters in a source line
21063 @item Maximum collection size (number of bytes)
21068 @item Maximum number of discriminants for a record type
21073 @item Maximum number of formal parameters in an entry or
21074 subprogram declaration
21079 @item Maximum number of dimensions in an array type
21084 @item Maximum number of library units and subunits in a compilation.
21089 @item Maximum number of library units and subunits in an execution.
21094 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21095 or @code{PSECT_OBJECT}
21100 @item Maximum number of enumeration literals in an enumeration type
21106 @item Maximum number of lines in a source file
21111 @item Maximum number of bits in any object
21116 @item Maximum size of the static portion of a stack frame (approximate)
21121 @node Tools and Utilities
21122 @section Tools and Utilities
21125 The following table lists some of the OpenVMS development tools
21126 available for HP Ada, and the corresponding tools for
21127 use with @value{EDITION} on Alpha and I64 platforms.
21128 Aside from the debugger, all the OpenVMS tools identified are part
21129 of the DECset package.
21132 @c Specify table in TeX since Texinfo does a poor job
21136 \settabs\+Language-Sensitive Editor\quad
21137 &Product with HP Ada\quad
21140 &\it Product with HP Ada
21141 & \it Product with @value{EDITION}\cr
21143 \+Code Management System
21147 \+Language-Sensitive Editor
21149 & emacs or HP LSE (Alpha)\cr
21159 & OpenVMS Debug (I64)\cr
21161 \+Source Code Analyzer /
21178 \+Coverage Analyzer
21182 \+Module Management
21184 & Not applicable\cr
21194 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
21195 @c the TeX version above for the printed version
21197 @c @multitable @columnfractions .3 .4 .4
21198 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
21200 @tab @i{Tool with HP Ada}
21201 @tab @i{Tool with @value{EDITION}}
21202 @item Code Management@*System
21205 @item Language-Sensitive@*Editor
21207 @tab emacs or HP LSE (Alpha)
21216 @tab OpenVMS Debug (I64)
21217 @item Source Code Analyzer /@*Cross Referencer
21221 @tab HP Digital Test@*Manager (DTM)
21223 @item Performance and@*Coverage Analyzer
21226 @item Module Management@*System
21228 @tab Not applicable
21235 @c **************************************
21236 @node Platform-Specific Information for the Run-Time Libraries
21237 @appendix Platform-Specific Information for the Run-Time Libraries
21238 @cindex Tasking and threads libraries
21239 @cindex Threads libraries and tasking
21240 @cindex Run-time libraries (platform-specific information)
21243 The GNAT run-time implementation may vary with respect to both the
21244 underlying threads library and the exception handling scheme.
21245 For threads support, one or more of the following are supplied:
21247 @item @b{native threads library}, a binding to the thread package from
21248 the underlying operating system
21250 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21251 POSIX thread package
21255 For exception handling, either or both of two models are supplied:
21257 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21258 Most programs should experience a substantial speed improvement by
21259 being compiled with a ZCX run-time.
21260 This is especially true for
21261 tasking applications or applications with many exception handlers.}
21262 @cindex Zero-Cost Exceptions
21263 @cindex ZCX (Zero-Cost Exceptions)
21264 which uses binder-generated tables that
21265 are interrogated at run time to locate a handler
21267 @item @b{setjmp / longjmp} (``SJLJ''),
21268 @cindex setjmp/longjmp Exception Model
21269 @cindex SJLJ (setjmp/longjmp Exception Model)
21270 which uses dynamically-set data to establish
21271 the set of handlers
21275 This appendix summarizes which combinations of threads and exception support
21276 are supplied on various GNAT platforms.
21277 It then shows how to select a particular library either
21278 permanently or temporarily,
21279 explains the properties of (and tradeoffs among) the various threads
21280 libraries, and provides some additional
21281 information about several specific platforms.
21284 * Summary of Run-Time Configurations::
21285 * Specifying a Run-Time Library::
21286 * Choosing the Scheduling Policy::
21287 * Solaris-Specific Considerations::
21288 * Linux-Specific Considerations::
21289 * AIX-Specific Considerations::
21290 * Irix-Specific Considerations::
21291 * RTX-Specific Considerations::
21292 * HP-UX-Specific Considerations::
21295 @node Summary of Run-Time Configurations
21296 @section Summary of Run-Time Configurations
21298 @multitable @columnfractions .30 .70
21299 @item @b{alpha-openvms}
21300 @item @code{@ @ }@i{rts-native (default)}
21301 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21302 @item @code{@ @ @ @ }Exceptions @tab ZCX
21304 @item @b{alpha-tru64}
21305 @item @code{@ @ }@i{rts-native (default)}
21306 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21307 @item @code{@ @ @ @ }Exceptions @tab ZCX
21309 @item @code{@ @ }@i{rts-sjlj}
21310 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21311 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21313 @item @b{ia64-hp_linux}
21314 @item @code{@ @ }@i{rts-native (default)}
21315 @item @code{@ @ @ @ }Tasking @tab pthread library
21316 @item @code{@ @ @ @ }Exceptions @tab ZCX
21318 @item @b{ia64-hpux}
21319 @item @code{@ @ }@i{rts-native (default)}
21320 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21321 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21323 @item @b{ia64-openvms}
21324 @item @code{@ @ }@i{rts-native (default)}
21325 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21326 @item @code{@ @ @ @ }Exceptions @tab ZCX
21328 @item @b{ia64-sgi_linux}
21329 @item @code{@ @ }@i{rts-native (default)}
21330 @item @code{@ @ @ @ }Tasking @tab pthread library
21331 @item @code{@ @ @ @ }Exceptions @tab ZCX
21333 @item @b{mips-irix}
21334 @item @code{@ @ }@i{rts-native (default)}
21335 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
21336 @item @code{@ @ @ @ }Exceptions @tab ZCX
21339 @item @code{@ @ }@i{rts-native (default)}
21340 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21341 @item @code{@ @ @ @ }Exceptions @tab ZCX
21343 @item @code{@ @ }@i{rts-sjlj}
21344 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21345 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21348 @item @code{@ @ }@i{rts-native (default)}
21349 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21350 @item @code{@ @ @ @ }Exceptions @tab ZCX
21352 @item @code{@ @ }@i{rts-sjlj}
21353 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21354 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21356 @item @b{ppc-darwin}
21357 @item @code{@ @ }@i{rts-native (default)}
21358 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
21359 @item @code{@ @ @ @ }Exceptions @tab ZCX
21361 @item @b{sparc-solaris} @tab
21362 @item @code{@ @ }@i{rts-native (default)}
21363 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21364 @item @code{@ @ @ @ }Exceptions @tab ZCX
21366 @item @code{@ @ }@i{rts-pthread}
21367 @item @code{@ @ @ @ }Tasking @tab pthread library
21368 @item @code{@ @ @ @ }Exceptions @tab ZCX
21370 @item @code{@ @ }@i{rts-sjlj}
21371 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21372 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21374 @item @b{sparc64-solaris} @tab
21375 @item @code{@ @ }@i{rts-native (default)}
21376 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21377 @item @code{@ @ @ @ }Exceptions @tab ZCX
21379 @item @b{x86-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
21389 @item @code{@ @ }@i{rts-native (default)}
21390 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
21391 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21393 @item @b{x86-solaris}
21394 @item @code{@ @ }@i{rts-native (default)}
21395 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
21396 @item @code{@ @ @ @ }Exceptions @tab ZCX
21398 @item @code{@ @ }@i{rts-sjlj}
21399 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21400 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21402 @item @b{x86-windows}
21403 @item @code{@ @ }@i{rts-native (default)}
21404 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21405 @item @code{@ @ @ @ }Exceptions @tab ZCX
21407 @item @code{@ @ }@i{rts-sjlj}
21408 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21409 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21411 @item @b{x86-windows-rtx}
21412 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21413 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
21414 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21416 @item @code{@ @ }@i{rts-rtx-w32}
21417 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
21418 @item @code{@ @ @ @ }Exceptions @tab ZCX
21420 @item @b{x86_64-linux}
21421 @item @code{@ @ }@i{rts-native (default)}
21422 @item @code{@ @ @ @ }Tasking @tab pthread library
21423 @item @code{@ @ @ @ }Exceptions @tab ZCX
21425 @item @code{@ @ }@i{rts-sjlj}
21426 @item @code{@ @ @ @ }Tasking @tab pthread library
21427 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21431 @node Specifying a Run-Time Library
21432 @section Specifying a Run-Time Library
21435 The @file{adainclude} subdirectory containing the sources of the GNAT
21436 run-time library, and the @file{adalib} subdirectory containing the
21437 @file{ALI} files and the static and/or shared GNAT library, are located
21438 in the gcc target-dependent area:
21441 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21445 As indicated above, on some platforms several run-time libraries are supplied.
21446 These libraries are installed in the target dependent area and
21447 contain a complete source and binary subdirectory. The detailed description
21448 below explains the differences between the different libraries in terms of
21449 their thread support.
21451 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21452 This default run time is selected by the means of soft links.
21453 For example on x86-linux:
21459 +--- adainclude----------+
21461 +--- adalib-----------+ |
21463 +--- rts-native | |
21465 | +--- adainclude <---+
21467 | +--- adalib <----+
21478 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21479 these soft links can be modified with the following commands:
21483 $ rm -f adainclude adalib
21484 $ ln -s rts-sjlj/adainclude adainclude
21485 $ ln -s rts-sjlj/adalib adalib
21489 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21490 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21491 @file{$target/ada_object_path}.
21493 Selecting another run-time library temporarily can be
21494 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21495 @cindex @option{--RTS} option
21497 @node Choosing the Scheduling Policy
21498 @section Choosing the Scheduling Policy
21501 When using a POSIX threads implementation, you have a choice of several
21502 scheduling policies: @code{SCHED_FIFO},
21503 @cindex @code{SCHED_FIFO} scheduling policy
21505 @cindex @code{SCHED_RR} scheduling policy
21506 and @code{SCHED_OTHER}.
21507 @cindex @code{SCHED_OTHER} scheduling policy
21508 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21509 or @code{SCHED_RR} requires special (e.g., root) privileges.
21511 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21513 @cindex @code{SCHED_FIFO} scheduling policy
21514 you can use one of the following:
21518 @code{pragma Time_Slice (0.0)}
21519 @cindex pragma Time_Slice
21521 the corresponding binder option @option{-T0}
21522 @cindex @option{-T0} option
21524 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21525 @cindex pragma Task_Dispatching_Policy
21529 To specify @code{SCHED_RR},
21530 @cindex @code{SCHED_RR} scheduling policy
21531 you should use @code{pragma Time_Slice} with a
21532 value greater than @code{0.0}, or else use the corresponding @option{-T}
21535 @node Solaris-Specific Considerations
21536 @section Solaris-Specific Considerations
21537 @cindex Solaris Sparc threads libraries
21540 This section addresses some topics related to the various threads libraries
21544 * Solaris Threads Issues::
21547 @node Solaris Threads Issues
21548 @subsection Solaris Threads Issues
21551 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21552 library based on POSIX threads --- @emph{rts-pthread}.
21553 @cindex rts-pthread threads library
21554 This run-time library has the advantage of being mostly shared across all
21555 POSIX-compliant thread implementations, and it also provides under
21556 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21557 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21558 and @code{PTHREAD_PRIO_PROTECT}
21559 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21560 semantics that can be selected using the predefined pragma
21561 @code{Locking_Policy}
21562 @cindex pragma Locking_Policy (under rts-pthread)
21564 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21565 @cindex @code{Inheritance_Locking} (under rts-pthread)
21566 @cindex @code{Ceiling_Locking} (under rts-pthread)
21568 As explained above, the native run-time library is based on the Solaris thread
21569 library (@code{libthread}) and is the default library.
21571 When the Solaris threads library is used (this is the default), programs
21572 compiled with GNAT can automatically take advantage of
21573 and can thus execute on multiple processors.
21574 The user can alternatively specify a processor on which the program should run
21575 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21577 setting the environment variable @env{GNAT_PROCESSOR}
21578 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21579 to one of the following:
21583 Use the default configuration (run the program on all
21584 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21588 Let the run-time implementation choose one processor and run the program on
21591 @item 0 .. Last_Proc
21592 Run the program on the specified processor.
21593 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21594 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21597 @node Linux-Specific Considerations
21598 @section Linux-Specific Considerations
21599 @cindex Linux threads libraries
21602 On GNU/Linux without NPTL support (usually system with GNU C Library
21603 older than 2.3), the signal model is not POSIX compliant, which means
21604 that to send a signal to the process, you need to send the signal to all
21605 threads, e.g.@: by using @code{killpg()}.
21607 @node AIX-Specific Considerations
21608 @section AIX-Specific Considerations
21609 @cindex AIX resolver library
21612 On AIX, the resolver library initializes some internal structure on
21613 the first call to @code{get*by*} functions, which are used to implement
21614 @code{GNAT.Sockets.Get_Host_By_Name} and
21615 @code{GNAT.Sockets.Get_Host_By_Address}.
21616 If such initialization occurs within an Ada task, and the stack size for
21617 the task is the default size, a stack overflow may occur.
21619 To avoid this overflow, the user should either ensure that the first call
21620 to @code{GNAT.Sockets.Get_Host_By_Name} or
21621 @code{GNAT.Sockets.Get_Host_By_Addrss}
21622 occurs in the environment task, or use @code{pragma Storage_Size} to
21623 specify a sufficiently large size for the stack of the task that contains
21626 @node Irix-Specific Considerations
21627 @section Irix-Specific Considerations
21628 @cindex Irix libraries
21631 The GCC support libraries coming with the Irix compiler have moved to
21632 their canonical place with respect to the general Irix ABI related
21633 conventions. Running applications built with the default shared GNAT
21634 run-time now requires the LD_LIBRARY_PATH environment variable to
21635 include this location. A possible way to achieve this is to issue the
21636 following command line on a bash prompt:
21640 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
21644 @node RTX-Specific Considerations
21645 @section RTX-Specific Considerations
21646 @cindex RTX libraries
21649 The Real-time Extension (RTX) to Windows is based on the Windows Win32
21650 API. Applications can be built to work in two different modes:
21654 Windows executables that run in Ring 3 to utilize memory protection
21655 (@emph{rts-rtx-w32}).
21658 Real-time subsystem (RTSS) executables that run in Ring 0, where
21659 performance can be optimized with RTSS applications taking precedent
21660 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
21661 the Microsoft linker to handle RTSS libraries.
21665 @node HP-UX-Specific Considerations
21666 @section HP-UX-Specific Considerations
21667 @cindex HP-UX Scheduling
21670 On HP-UX, appropriate privileges are required to change the scheduling
21671 parameters of a task. The calling process must have appropriate
21672 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
21673 successfully change the scheduling parameters.
21675 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
21676 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
21677 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
21679 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
21680 one of the following:
21684 @code{pragma Time_Slice (0.0)}
21685 @cindex pragma Time_Slice
21687 the corresponding binder option @option{-T0}
21688 @cindex @option{-T0} option
21690 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21691 @cindex pragma Task_Dispatching_Policy
21695 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
21696 you should use @code{pragma Time_Slice} with a
21697 value greater than @code{0.0}, or use the corresponding @option{-T}
21698 binder option, or set the @code{pragma Task_Dispatching_Policy
21699 (Round_Robin_Within_Priorities)}.
21701 @c *******************************
21702 @node Example of Binder Output File
21703 @appendix Example of Binder Output File
21706 This Appendix displays the source code for @command{gnatbind}'s output
21707 file generated for a simple ``Hello World'' program.
21708 Comments have been added for clarification purposes.
21710 @smallexample @c adanocomment
21714 -- The package is called Ada_Main unless this name is actually used
21715 -- as a unit name in the partition, in which case some other unique
21719 package ada_main is
21721 Elab_Final_Code : Integer;
21722 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21724 -- The main program saves the parameters (argument count,
21725 -- argument values, environment pointer) in global variables
21726 -- for later access by other units including
21727 -- Ada.Command_Line.
21729 gnat_argc : Integer;
21730 gnat_argv : System.Address;
21731 gnat_envp : System.Address;
21733 -- The actual variables are stored in a library routine. This
21734 -- is useful for some shared library situations, where there
21735 -- are problems if variables are not in the library.
21737 pragma Import (C, gnat_argc);
21738 pragma Import (C, gnat_argv);
21739 pragma Import (C, gnat_envp);
21741 -- The exit status is similarly an external location
21743 gnat_exit_status : Integer;
21744 pragma Import (C, gnat_exit_status);
21746 GNAT_Version : constant String :=
21747 "GNAT Version: 6.0.0w (20061115)";
21748 pragma Export (C, GNAT_Version, "__gnat_version");
21750 -- This is the generated adafinal routine that performs
21751 -- finalization at the end of execution. In the case where
21752 -- Ada is the main program, this main program makes a call
21753 -- to adafinal at program termination.
21755 procedure adafinal;
21756 pragma Export (C, adafinal, "adafinal");
21758 -- This is the generated adainit routine that performs
21759 -- initialization at the start of execution. In the case
21760 -- where Ada is the main program, this main program makes
21761 -- a call to adainit at program startup.
21764 pragma Export (C, adainit, "adainit");
21766 -- This routine is called at the start of execution. It is
21767 -- a dummy routine that is used by the debugger to breakpoint
21768 -- at the start of execution.
21770 procedure Break_Start;
21771 pragma Import (C, Break_Start, "__gnat_break_start");
21773 -- This is the actual generated main program (it would be
21774 -- suppressed if the no main program switch were used). As
21775 -- required by standard system conventions, this program has
21776 -- the external name main.
21780 argv : System.Address;
21781 envp : System.Address)
21783 pragma Export (C, main, "main");
21785 -- The following set of constants give the version
21786 -- identification values for every unit in the bound
21787 -- partition. This identification is computed from all
21788 -- dependent semantic units, and corresponds to the
21789 -- string that would be returned by use of the
21790 -- Body_Version or Version attributes.
21792 type Version_32 is mod 2 ** 32;
21793 u00001 : constant Version_32 := 16#7880BEB3#;
21794 u00002 : constant Version_32 := 16#0D24CBD0#;
21795 u00003 : constant Version_32 := 16#3283DBEB#;
21796 u00004 : constant Version_32 := 16#2359F9ED#;
21797 u00005 : constant Version_32 := 16#664FB847#;
21798 u00006 : constant Version_32 := 16#68E803DF#;
21799 u00007 : constant Version_32 := 16#5572E604#;
21800 u00008 : constant Version_32 := 16#46B173D8#;
21801 u00009 : constant Version_32 := 16#156A40CF#;
21802 u00010 : constant Version_32 := 16#033DABE0#;
21803 u00011 : constant Version_32 := 16#6AB38FEA#;
21804 u00012 : constant Version_32 := 16#22B6217D#;
21805 u00013 : constant Version_32 := 16#68A22947#;
21806 u00014 : constant Version_32 := 16#18CC4A56#;
21807 u00015 : constant Version_32 := 16#08258E1B#;
21808 u00016 : constant Version_32 := 16#367D5222#;
21809 u00017 : constant Version_32 := 16#20C9ECA4#;
21810 u00018 : constant Version_32 := 16#50D32CB6#;
21811 u00019 : constant Version_32 := 16#39A8BB77#;
21812 u00020 : constant Version_32 := 16#5CF8FA2B#;
21813 u00021 : constant Version_32 := 16#2F1EB794#;
21814 u00022 : constant Version_32 := 16#31AB6444#;
21815 u00023 : constant Version_32 := 16#1574B6E9#;
21816 u00024 : constant Version_32 := 16#5109C189#;
21817 u00025 : constant Version_32 := 16#56D770CD#;
21818 u00026 : constant Version_32 := 16#02F9DE3D#;
21819 u00027 : constant Version_32 := 16#08AB6B2C#;
21820 u00028 : constant Version_32 := 16#3FA37670#;
21821 u00029 : constant Version_32 := 16#476457A0#;
21822 u00030 : constant Version_32 := 16#731E1B6E#;
21823 u00031 : constant Version_32 := 16#23C2E789#;
21824 u00032 : constant Version_32 := 16#0F1BD6A1#;
21825 u00033 : constant Version_32 := 16#7C25DE96#;
21826 u00034 : constant Version_32 := 16#39ADFFA2#;
21827 u00035 : constant Version_32 := 16#571DE3E7#;
21828 u00036 : constant Version_32 := 16#5EB646AB#;
21829 u00037 : constant Version_32 := 16#4249379B#;
21830 u00038 : constant Version_32 := 16#0357E00A#;
21831 u00039 : constant Version_32 := 16#3784FB72#;
21832 u00040 : constant Version_32 := 16#2E723019#;
21833 u00041 : constant Version_32 := 16#623358EA#;
21834 u00042 : constant Version_32 := 16#107F9465#;
21835 u00043 : constant Version_32 := 16#6843F68A#;
21836 u00044 : constant Version_32 := 16#63305874#;
21837 u00045 : constant Version_32 := 16#31E56CE1#;
21838 u00046 : constant Version_32 := 16#02917970#;
21839 u00047 : constant Version_32 := 16#6CCBA70E#;
21840 u00048 : constant Version_32 := 16#41CD4204#;
21841 u00049 : constant Version_32 := 16#572E3F58#;
21842 u00050 : constant Version_32 := 16#20729FF5#;
21843 u00051 : constant Version_32 := 16#1D4F93E8#;
21844 u00052 : constant Version_32 := 16#30B2EC3D#;
21845 u00053 : constant Version_32 := 16#34054F96#;
21846 u00054 : constant Version_32 := 16#5A199860#;
21847 u00055 : constant Version_32 := 16#0E7F912B#;
21848 u00056 : constant Version_32 := 16#5760634A#;
21849 u00057 : constant Version_32 := 16#5D851835#;
21851 -- The following Export pragmas export the version numbers
21852 -- with symbolic names ending in B (for body) or S
21853 -- (for spec) so that they can be located in a link. The
21854 -- information provided here is sufficient to track down
21855 -- the exact versions of units used in a given build.
21857 pragma Export (C, u00001, "helloB");
21858 pragma Export (C, u00002, "system__standard_libraryB");
21859 pragma Export (C, u00003, "system__standard_libraryS");
21860 pragma Export (C, u00004, "adaS");
21861 pragma Export (C, u00005, "ada__text_ioB");
21862 pragma Export (C, u00006, "ada__text_ioS");
21863 pragma Export (C, u00007, "ada__exceptionsB");
21864 pragma Export (C, u00008, "ada__exceptionsS");
21865 pragma Export (C, u00009, "gnatS");
21866 pragma Export (C, u00010, "gnat__heap_sort_aB");
21867 pragma Export (C, u00011, "gnat__heap_sort_aS");
21868 pragma Export (C, u00012, "systemS");
21869 pragma Export (C, u00013, "system__exception_tableB");
21870 pragma Export (C, u00014, "system__exception_tableS");
21871 pragma Export (C, u00015, "gnat__htableB");
21872 pragma Export (C, u00016, "gnat__htableS");
21873 pragma Export (C, u00017, "system__exceptionsS");
21874 pragma Export (C, u00018, "system__machine_state_operationsB");
21875 pragma Export (C, u00019, "system__machine_state_operationsS");
21876 pragma Export (C, u00020, "system__machine_codeS");
21877 pragma Export (C, u00021, "system__storage_elementsB");
21878 pragma Export (C, u00022, "system__storage_elementsS");
21879 pragma Export (C, u00023, "system__secondary_stackB");
21880 pragma Export (C, u00024, "system__secondary_stackS");
21881 pragma Export (C, u00025, "system__parametersB");
21882 pragma Export (C, u00026, "system__parametersS");
21883 pragma Export (C, u00027, "system__soft_linksB");
21884 pragma Export (C, u00028, "system__soft_linksS");
21885 pragma Export (C, u00029, "system__stack_checkingB");
21886 pragma Export (C, u00030, "system__stack_checkingS");
21887 pragma Export (C, u00031, "system__tracebackB");
21888 pragma Export (C, u00032, "system__tracebackS");
21889 pragma Export (C, u00033, "ada__streamsS");
21890 pragma Export (C, u00034, "ada__tagsB");
21891 pragma Export (C, u00035, "ada__tagsS");
21892 pragma Export (C, u00036, "system__string_opsB");
21893 pragma Export (C, u00037, "system__string_opsS");
21894 pragma Export (C, u00038, "interfacesS");
21895 pragma Export (C, u00039, "interfaces__c_streamsB");
21896 pragma Export (C, u00040, "interfaces__c_streamsS");
21897 pragma Export (C, u00041, "system__file_ioB");
21898 pragma Export (C, u00042, "system__file_ioS");
21899 pragma Export (C, u00043, "ada__finalizationB");
21900 pragma Export (C, u00044, "ada__finalizationS");
21901 pragma Export (C, u00045, "system__finalization_rootB");
21902 pragma Export (C, u00046, "system__finalization_rootS");
21903 pragma Export (C, u00047, "system__finalization_implementationB");
21904 pragma Export (C, u00048, "system__finalization_implementationS");
21905 pragma Export (C, u00049, "system__string_ops_concat_3B");
21906 pragma Export (C, u00050, "system__string_ops_concat_3S");
21907 pragma Export (C, u00051, "system__stream_attributesB");
21908 pragma Export (C, u00052, "system__stream_attributesS");
21909 pragma Export (C, u00053, "ada__io_exceptionsS");
21910 pragma Export (C, u00054, "system__unsigned_typesS");
21911 pragma Export (C, u00055, "system__file_control_blockS");
21912 pragma Export (C, u00056, "ada__finalization__list_controllerB");
21913 pragma Export (C, u00057, "ada__finalization__list_controllerS");
21915 -- BEGIN ELABORATION ORDER
21918 -- gnat.heap_sort_a (spec)
21919 -- gnat.heap_sort_a (body)
21920 -- gnat.htable (spec)
21921 -- gnat.htable (body)
21922 -- interfaces (spec)
21924 -- system.machine_code (spec)
21925 -- system.parameters (spec)
21926 -- system.parameters (body)
21927 -- interfaces.c_streams (spec)
21928 -- interfaces.c_streams (body)
21929 -- system.standard_library (spec)
21930 -- ada.exceptions (spec)
21931 -- system.exception_table (spec)
21932 -- system.exception_table (body)
21933 -- ada.io_exceptions (spec)
21934 -- system.exceptions (spec)
21935 -- system.storage_elements (spec)
21936 -- system.storage_elements (body)
21937 -- system.machine_state_operations (spec)
21938 -- system.machine_state_operations (body)
21939 -- system.secondary_stack (spec)
21940 -- system.stack_checking (spec)
21941 -- system.soft_links (spec)
21942 -- system.soft_links (body)
21943 -- system.stack_checking (body)
21944 -- system.secondary_stack (body)
21945 -- system.standard_library (body)
21946 -- system.string_ops (spec)
21947 -- system.string_ops (body)
21950 -- ada.streams (spec)
21951 -- system.finalization_root (spec)
21952 -- system.finalization_root (body)
21953 -- system.string_ops_concat_3 (spec)
21954 -- system.string_ops_concat_3 (body)
21955 -- system.traceback (spec)
21956 -- system.traceback (body)
21957 -- ada.exceptions (body)
21958 -- system.unsigned_types (spec)
21959 -- system.stream_attributes (spec)
21960 -- system.stream_attributes (body)
21961 -- system.finalization_implementation (spec)
21962 -- system.finalization_implementation (body)
21963 -- ada.finalization (spec)
21964 -- ada.finalization (body)
21965 -- ada.finalization.list_controller (spec)
21966 -- ada.finalization.list_controller (body)
21967 -- system.file_control_block (spec)
21968 -- system.file_io (spec)
21969 -- system.file_io (body)
21970 -- ada.text_io (spec)
21971 -- ada.text_io (body)
21973 -- END ELABORATION ORDER
21977 -- The following source file name pragmas allow the generated file
21978 -- names to be unique for different main programs. They are needed
21979 -- since the package name will always be Ada_Main.
21981 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21982 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21984 -- Generated package body for Ada_Main starts here
21986 package body ada_main is
21988 -- The actual finalization is performed by calling the
21989 -- library routine in System.Standard_Library.Adafinal
21991 procedure Do_Finalize;
21992 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21999 procedure adainit is
22001 -- These booleans are set to True once the associated unit has
22002 -- been elaborated. It is also used to avoid elaborating the
22003 -- same unit twice.
22006 pragma Import (Ada, E040, "interfaces__c_streams_E");
22009 pragma Import (Ada, E008, "ada__exceptions_E");
22012 pragma Import (Ada, E014, "system__exception_table_E");
22015 pragma Import (Ada, E053, "ada__io_exceptions_E");
22018 pragma Import (Ada, E017, "system__exceptions_E");
22021 pragma Import (Ada, E024, "system__secondary_stack_E");
22024 pragma Import (Ada, E030, "system__stack_checking_E");
22027 pragma Import (Ada, E028, "system__soft_links_E");
22030 pragma Import (Ada, E035, "ada__tags_E");
22033 pragma Import (Ada, E033, "ada__streams_E");
22036 pragma Import (Ada, E046, "system__finalization_root_E");
22039 pragma Import (Ada, E048, "system__finalization_implementation_E");
22042 pragma Import (Ada, E044, "ada__finalization_E");
22045 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22048 pragma Import (Ada, E055, "system__file_control_block_E");
22051 pragma Import (Ada, E042, "system__file_io_E");
22054 pragma Import (Ada, E006, "ada__text_io_E");
22056 -- Set_Globals is a library routine that stores away the
22057 -- value of the indicated set of global values in global
22058 -- variables within the library.
22060 procedure Set_Globals
22061 (Main_Priority : Integer;
22062 Time_Slice_Value : Integer;
22063 WC_Encoding : Character;
22064 Locking_Policy : Character;
22065 Queuing_Policy : Character;
22066 Task_Dispatching_Policy : Character;
22067 Adafinal : System.Address;
22068 Unreserve_All_Interrupts : Integer;
22069 Exception_Tracebacks : Integer);
22070 @findex __gnat_set_globals
22071 pragma Import (C, Set_Globals, "__gnat_set_globals");
22073 -- SDP_Table_Build is a library routine used to build the
22074 -- exception tables. See unit Ada.Exceptions in files
22075 -- a-except.ads/adb for full details of how zero cost
22076 -- exception handling works. This procedure, the call to
22077 -- it, and the two following tables are all omitted if the
22078 -- build is in longjmp/setjmp exception mode.
22080 @findex SDP_Table_Build
22081 @findex Zero Cost Exceptions
22082 procedure SDP_Table_Build
22083 (SDP_Addresses : System.Address;
22084 SDP_Count : Natural;
22085 Elab_Addresses : System.Address;
22086 Elab_Addr_Count : Natural);
22087 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22089 -- Table of Unit_Exception_Table addresses. Used for zero
22090 -- cost exception handling to build the top level table.
22092 ST : aliased constant array (1 .. 23) of System.Address := (
22094 Ada.Text_Io'UET_Address,
22095 Ada.Exceptions'UET_Address,
22096 Gnat.Heap_Sort_A'UET_Address,
22097 System.Exception_Table'UET_Address,
22098 System.Machine_State_Operations'UET_Address,
22099 System.Secondary_Stack'UET_Address,
22100 System.Parameters'UET_Address,
22101 System.Soft_Links'UET_Address,
22102 System.Stack_Checking'UET_Address,
22103 System.Traceback'UET_Address,
22104 Ada.Streams'UET_Address,
22105 Ada.Tags'UET_Address,
22106 System.String_Ops'UET_Address,
22107 Interfaces.C_Streams'UET_Address,
22108 System.File_Io'UET_Address,
22109 Ada.Finalization'UET_Address,
22110 System.Finalization_Root'UET_Address,
22111 System.Finalization_Implementation'UET_Address,
22112 System.String_Ops_Concat_3'UET_Address,
22113 System.Stream_Attributes'UET_Address,
22114 System.File_Control_Block'UET_Address,
22115 Ada.Finalization.List_Controller'UET_Address);
22117 -- Table of addresses of elaboration routines. Used for
22118 -- zero cost exception handling to make sure these
22119 -- addresses are included in the top level procedure
22122 EA : aliased constant array (1 .. 23) of System.Address := (
22123 adainit'Code_Address,
22124 Do_Finalize'Code_Address,
22125 Ada.Exceptions'Elab_Spec'Address,
22126 System.Exceptions'Elab_Spec'Address,
22127 Interfaces.C_Streams'Elab_Spec'Address,
22128 System.Exception_Table'Elab_Body'Address,
22129 Ada.Io_Exceptions'Elab_Spec'Address,
22130 System.Stack_Checking'Elab_Spec'Address,
22131 System.Soft_Links'Elab_Body'Address,
22132 System.Secondary_Stack'Elab_Body'Address,
22133 Ada.Tags'Elab_Spec'Address,
22134 Ada.Tags'Elab_Body'Address,
22135 Ada.Streams'Elab_Spec'Address,
22136 System.Finalization_Root'Elab_Spec'Address,
22137 Ada.Exceptions'Elab_Body'Address,
22138 System.Finalization_Implementation'Elab_Spec'Address,
22139 System.Finalization_Implementation'Elab_Body'Address,
22140 Ada.Finalization'Elab_Spec'Address,
22141 Ada.Finalization.List_Controller'Elab_Spec'Address,
22142 System.File_Control_Block'Elab_Spec'Address,
22143 System.File_Io'Elab_Body'Address,
22144 Ada.Text_Io'Elab_Spec'Address,
22145 Ada.Text_Io'Elab_Body'Address);
22147 -- Start of processing for adainit
22151 -- Call SDP_Table_Build to build the top level procedure
22152 -- table for zero cost exception handling (omitted in
22153 -- longjmp/setjmp mode).
22155 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22157 -- Call Set_Globals to record various information for
22158 -- this partition. The values are derived by the binder
22159 -- from information stored in the ali files by the compiler.
22161 @findex __gnat_set_globals
22163 (Main_Priority => -1,
22164 -- Priority of main program, -1 if no pragma Priority used
22166 Time_Slice_Value => -1,
22167 -- Time slice from Time_Slice pragma, -1 if none used
22169 WC_Encoding => 'b',
22170 -- Wide_Character encoding used, default is brackets
22172 Locking_Policy => ' ',
22173 -- Locking_Policy used, default of space means not
22174 -- specified, otherwise it is the first character of
22175 -- the policy name.
22177 Queuing_Policy => ' ',
22178 -- Queuing_Policy used, default of space means not
22179 -- specified, otherwise it is the first character of
22180 -- the policy name.
22182 Task_Dispatching_Policy => ' ',
22183 -- Task_Dispatching_Policy used, default of space means
22184 -- not specified, otherwise first character of the
22187 Adafinal => System.Null_Address,
22188 -- Address of Adafinal routine, not used anymore
22190 Unreserve_All_Interrupts => 0,
22191 -- Set true if pragma Unreserve_All_Interrupts was used
22193 Exception_Tracebacks => 0);
22194 -- Indicates if exception tracebacks are enabled
22196 Elab_Final_Code := 1;
22198 -- Now we have the elaboration calls for all units in the partition.
22199 -- The Elab_Spec and Elab_Body attributes generate references to the
22200 -- implicit elaboration procedures generated by the compiler for
22201 -- each unit that requires elaboration.
22204 Interfaces.C_Streams'Elab_Spec;
22208 Ada.Exceptions'Elab_Spec;
22211 System.Exception_Table'Elab_Body;
22215 Ada.Io_Exceptions'Elab_Spec;
22219 System.Exceptions'Elab_Spec;
22223 System.Stack_Checking'Elab_Spec;
22226 System.Soft_Links'Elab_Body;
22231 System.Secondary_Stack'Elab_Body;
22235 Ada.Tags'Elab_Spec;
22238 Ada.Tags'Elab_Body;
22242 Ada.Streams'Elab_Spec;
22246 System.Finalization_Root'Elab_Spec;
22250 Ada.Exceptions'Elab_Body;
22254 System.Finalization_Implementation'Elab_Spec;
22257 System.Finalization_Implementation'Elab_Body;
22261 Ada.Finalization'Elab_Spec;
22265 Ada.Finalization.List_Controller'Elab_Spec;
22269 System.File_Control_Block'Elab_Spec;
22273 System.File_Io'Elab_Body;
22277 Ada.Text_Io'Elab_Spec;
22280 Ada.Text_Io'Elab_Body;
22284 Elab_Final_Code := 0;
22292 procedure adafinal is
22301 -- main is actually a function, as in the ANSI C standard,
22302 -- defined to return the exit status. The three parameters
22303 -- are the argument count, argument values and environment
22306 @findex Main Program
22309 argv : System.Address;
22310 envp : System.Address)
22313 -- The initialize routine performs low level system
22314 -- initialization using a standard library routine which
22315 -- sets up signal handling and performs any other
22316 -- required setup. The routine can be found in file
22319 @findex __gnat_initialize
22320 procedure initialize;
22321 pragma Import (C, initialize, "__gnat_initialize");
22323 -- The finalize routine performs low level system
22324 -- finalization using a standard library routine. The
22325 -- routine is found in file a-final.c and in the standard
22326 -- distribution is a dummy routine that does nothing, so
22327 -- really this is a hook for special user finalization.
22329 @findex __gnat_finalize
22330 procedure finalize;
22331 pragma Import (C, finalize, "__gnat_finalize");
22333 -- We get to the main program of the partition by using
22334 -- pragma Import because if we try to with the unit and
22335 -- call it Ada style, then not only do we waste time
22336 -- recompiling it, but also, we don't really know the right
22337 -- switches (e.g.@: identifier character set) to be used
22340 procedure Ada_Main_Program;
22341 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22343 -- Start of processing for main
22346 -- Save global variables
22352 -- Call low level system initialization
22356 -- Call our generated Ada initialization routine
22360 -- This is the point at which we want the debugger to get
22365 -- Now we call the main program of the partition
22369 -- Perform Ada finalization
22373 -- Perform low level system finalization
22377 -- Return the proper exit status
22378 return (gnat_exit_status);
22381 -- This section is entirely comments, so it has no effect on the
22382 -- compilation of the Ada_Main package. It provides the list of
22383 -- object files and linker options, as well as some standard
22384 -- libraries needed for the link. The gnatlink utility parses
22385 -- this b~hello.adb file to read these comment lines to generate
22386 -- the appropriate command line arguments for the call to the
22387 -- system linker. The BEGIN/END lines are used for sentinels for
22388 -- this parsing operation.
22390 -- The exact file names will of course depend on the environment,
22391 -- host/target and location of files on the host system.
22393 @findex Object file list
22394 -- BEGIN Object file/option list
22397 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22398 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22399 -- END Object file/option list
22405 The Ada code in the above example is exactly what is generated by the
22406 binder. We have added comments to more clearly indicate the function
22407 of each part of the generated @code{Ada_Main} package.
22409 The code is standard Ada in all respects, and can be processed by any
22410 tools that handle Ada. In particular, it is possible to use the debugger
22411 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22412 suppose that for reasons that you do not understand, your program is crashing
22413 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22414 you can place a breakpoint on the call:
22416 @smallexample @c ada
22417 Ada.Text_Io'Elab_Body;
22421 and trace the elaboration routine for this package to find out where
22422 the problem might be (more usually of course you would be debugging
22423 elaboration code in your own application).
22425 @node Elaboration Order Handling in GNAT
22426 @appendix Elaboration Order Handling in GNAT
22427 @cindex Order of elaboration
22428 @cindex Elaboration control
22431 * Elaboration Code::
22432 * Checking the Elaboration Order::
22433 * Controlling the Elaboration Order::
22434 * Controlling Elaboration in GNAT - Internal Calls::
22435 * Controlling Elaboration in GNAT - External Calls::
22436 * Default Behavior in GNAT - Ensuring Safety::
22437 * Treatment of Pragma Elaborate::
22438 * Elaboration Issues for Library Tasks::
22439 * Mixing Elaboration Models::
22440 * What to Do If the Default Elaboration Behavior Fails::
22441 * Elaboration for Access-to-Subprogram Values::
22442 * Summary of Procedures for Elaboration Control::
22443 * Other Elaboration Order Considerations::
22447 This chapter describes the handling of elaboration code in Ada and
22448 in GNAT, and discusses how the order of elaboration of program units can
22449 be controlled in GNAT, either automatically or with explicit programming
22452 @node Elaboration Code
22453 @section Elaboration Code
22456 Ada provides rather general mechanisms for executing code at elaboration
22457 time, that is to say before the main program starts executing. Such code arises
22461 @item Initializers for variables.
22462 Variables declared at the library level, in package specs or bodies, can
22463 require initialization that is performed at elaboration time, as in:
22464 @smallexample @c ada
22466 Sqrt_Half : Float := Sqrt (0.5);
22470 @item Package initialization code
22471 Code in a @code{BEGIN-END} section at the outer level of a package body is
22472 executed as part of the package body elaboration code.
22474 @item Library level task allocators
22475 Tasks that are declared using task allocators at the library level
22476 start executing immediately and hence can execute at elaboration time.
22480 Subprogram calls are possible in any of these contexts, which means that
22481 any arbitrary part of the program may be executed as part of the elaboration
22482 code. It is even possible to write a program which does all its work at
22483 elaboration time, with a null main program, although stylistically this
22484 would usually be considered an inappropriate way to structure
22487 An important concern arises in the context of elaboration code:
22488 we have to be sure that it is executed in an appropriate order. What we
22489 have is a series of elaboration code sections, potentially one section
22490 for each unit in the program. It is important that these execute
22491 in the correct order. Correctness here means that, taking the above
22492 example of the declaration of @code{Sqrt_Half},
22493 if some other piece of
22494 elaboration code references @code{Sqrt_Half},
22495 then it must run after the
22496 section of elaboration code that contains the declaration of
22499 There would never be any order of elaboration problem if we made a rule
22500 that whenever you @code{with} a unit, you must elaborate both the spec and body
22501 of that unit before elaborating the unit doing the @code{with}'ing:
22503 @smallexample @c ada
22507 package Unit_2 is @dots{}
22513 would require that both the body and spec of @code{Unit_1} be elaborated
22514 before the spec of @code{Unit_2}. However, a rule like that would be far too
22515 restrictive. In particular, it would make it impossible to have routines
22516 in separate packages that were mutually recursive.
22518 You might think that a clever enough compiler could look at the actual
22519 elaboration code and determine an appropriate correct order of elaboration,
22520 but in the general case, this is not possible. Consider the following
22523 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22525 the variable @code{Sqrt_1}, which is declared in the elaboration code
22526 of the body of @code{Unit_1}:
22528 @smallexample @c ada
22530 Sqrt_1 : Float := Sqrt (0.1);
22535 The elaboration code of the body of @code{Unit_1} also contains:
22537 @smallexample @c ada
22540 if expression_1 = 1 then
22541 Q := Unit_2.Func_2;
22548 @code{Unit_2} is exactly parallel,
22549 it has a procedure @code{Func_2} that references
22550 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22551 the body @code{Unit_2}:
22553 @smallexample @c ada
22555 Sqrt_2 : Float := Sqrt (0.1);
22560 The elaboration code of the body of @code{Unit_2} also contains:
22562 @smallexample @c ada
22565 if expression_2 = 2 then
22566 Q := Unit_1.Func_1;
22573 Now the question is, which of the following orders of elaboration is
22598 If you carefully analyze the flow here, you will see that you cannot tell
22599 at compile time the answer to this question.
22600 If @code{expression_1} is not equal to 1,
22601 and @code{expression_2} is not equal to 2,
22602 then either order is acceptable, because neither of the function calls is
22603 executed. If both tests evaluate to true, then neither order is acceptable
22604 and in fact there is no correct order.
22606 If one of the two expressions is true, and the other is false, then one
22607 of the above orders is correct, and the other is incorrect. For example,
22608 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22609 then the call to @code{Func_1}
22610 will occur, but not the call to @code{Func_2.}
22611 This means that it is essential
22612 to elaborate the body of @code{Unit_1} before
22613 the body of @code{Unit_2}, so the first
22614 order of elaboration is correct and the second is wrong.
22616 By making @code{expression_1} and @code{expression_2}
22617 depend on input data, or perhaps
22618 the time of day, we can make it impossible for the compiler or binder
22619 to figure out which of these expressions will be true, and hence it
22620 is impossible to guarantee a safe order of elaboration at run time.
22622 @node Checking the Elaboration Order
22623 @section Checking the Elaboration Order
22626 In some languages that involve the same kind of elaboration problems,
22627 e.g.@: Java and C++, the programmer is expected to worry about these
22628 ordering problems himself, and it is common to
22629 write a program in which an incorrect elaboration order gives
22630 surprising results, because it references variables before they
22632 Ada is designed to be a safe language, and a programmer-beware approach is
22633 clearly not sufficient. Consequently, the language provides three lines
22637 @item Standard rules
22638 Some standard rules restrict the possible choice of elaboration
22639 order. In particular, if you @code{with} a unit, then its spec is always
22640 elaborated before the unit doing the @code{with}. Similarly, a parent
22641 spec is always elaborated before the child spec, and finally
22642 a spec is always elaborated before its corresponding body.
22644 @item Dynamic elaboration checks
22645 @cindex Elaboration checks
22646 @cindex Checks, elaboration
22647 Dynamic checks are made at run time, so that if some entity is accessed
22648 before it is elaborated (typically by means of a subprogram call)
22649 then the exception (@code{Program_Error}) is raised.
22651 @item Elaboration control
22652 Facilities are provided for the programmer to specify the desired order
22656 Let's look at these facilities in more detail. First, the rules for
22657 dynamic checking. One possible rule would be simply to say that the
22658 exception is raised if you access a variable which has not yet been
22659 elaborated. The trouble with this approach is that it could require
22660 expensive checks on every variable reference. Instead Ada has two
22661 rules which are a little more restrictive, but easier to check, and
22665 @item Restrictions on calls
22666 A subprogram can only be called at elaboration time if its body
22667 has been elaborated. The rules for elaboration given above guarantee
22668 that the spec of the subprogram has been elaborated before the
22669 call, but not the body. If this rule is violated, then the
22670 exception @code{Program_Error} is raised.
22672 @item Restrictions on instantiations
22673 A generic unit can only be instantiated if the body of the generic
22674 unit has been elaborated. Again, the rules for elaboration given above
22675 guarantee that the spec of the generic unit has been elaborated
22676 before the instantiation, but not the body. If this rule is
22677 violated, then the exception @code{Program_Error} is raised.
22681 The idea is that if the body has been elaborated, then any variables
22682 it references must have been elaborated; by checking for the body being
22683 elaborated we guarantee that none of its references causes any
22684 trouble. As we noted above, this is a little too restrictive, because a
22685 subprogram that has no non-local references in its body may in fact be safe
22686 to call. However, it really would be unsafe to rely on this, because
22687 it would mean that the caller was aware of details of the implementation
22688 in the body. This goes against the basic tenets of Ada.
22690 A plausible implementation can be described as follows.
22691 A Boolean variable is associated with each subprogram
22692 and each generic unit. This variable is initialized to False, and is set to
22693 True at the point body is elaborated. Every call or instantiation checks the
22694 variable, and raises @code{Program_Error} if the variable is False.
22696 Note that one might think that it would be good enough to have one Boolean
22697 variable for each package, but that would not deal with cases of trying
22698 to call a body in the same package as the call
22699 that has not been elaborated yet.
22700 Of course a compiler may be able to do enough analysis to optimize away
22701 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22702 does such optimizations, but still the easiest conceptual model is to
22703 think of there being one variable per subprogram.
22705 @node Controlling the Elaboration Order
22706 @section Controlling the Elaboration Order
22709 In the previous section we discussed the rules in Ada which ensure
22710 that @code{Program_Error} is raised if an incorrect elaboration order is
22711 chosen. This prevents erroneous executions, but we need mechanisms to
22712 specify a correct execution and avoid the exception altogether.
22713 To achieve this, Ada provides a number of features for controlling
22714 the order of elaboration. We discuss these features in this section.
22716 First, there are several ways of indicating to the compiler that a given
22717 unit has no elaboration problems:
22720 @item packages that do not require a body
22721 A library package that does not require a body does not permit
22722 a body (this rule was introduced in Ada 95).
22723 Thus if we have a such a package, as in:
22725 @smallexample @c ada
22728 package Definitions is
22730 type m is new integer;
22732 type a is array (1 .. 10) of m;
22733 type b is array (1 .. 20) of m;
22741 A package that @code{with}'s @code{Definitions} may safely instantiate
22742 @code{Definitions.Subp} because the compiler can determine that there
22743 definitely is no package body to worry about in this case
22746 @cindex pragma Pure
22748 Places sufficient restrictions on a unit to guarantee that
22749 no call to any subprogram in the unit can result in an
22750 elaboration problem. This means that the compiler does not need
22751 to worry about the point of elaboration of such units, and in
22752 particular, does not need to check any calls to any subprograms
22755 @item pragma Preelaborate
22756 @findex Preelaborate
22757 @cindex pragma Preelaborate
22758 This pragma places slightly less stringent restrictions on a unit than
22760 but these restrictions are still sufficient to ensure that there
22761 are no elaboration problems with any calls to the unit.
22763 @item pragma Elaborate_Body
22764 @findex Elaborate_Body
22765 @cindex pragma Elaborate_Body
22766 This pragma requires that the body of a unit be elaborated immediately
22767 after its spec. Suppose a unit @code{A} has such a pragma,
22768 and unit @code{B} does
22769 a @code{with} of unit @code{A}. Recall that the standard rules require
22770 the spec of unit @code{A}
22771 to be elaborated before the @code{with}'ing unit; given the pragma in
22772 @code{A}, we also know that the body of @code{A}
22773 will be elaborated before @code{B}, so
22774 that calls to @code{A} are safe and do not need a check.
22779 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22781 @code{Elaborate_Body} does not guarantee that the program is
22782 free of elaboration problems, because it may not be possible
22783 to satisfy the requested elaboration order.
22784 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22786 marks @code{Unit_1} as @code{Elaborate_Body},
22787 and not @code{Unit_2,} then the order of
22788 elaboration will be:
22800 Now that means that the call to @code{Func_1} in @code{Unit_2}
22801 need not be checked,
22802 it must be safe. But the call to @code{Func_2} in
22803 @code{Unit_1} may still fail if
22804 @code{Expression_1} is equal to 1,
22805 and the programmer must still take
22806 responsibility for this not being the case.
22808 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22809 eliminated, except for calls entirely within a body, which are
22810 in any case fully under programmer control. However, using the pragma
22811 everywhere is not always possible.
22812 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22813 we marked both of them as having pragma @code{Elaborate_Body}, then
22814 clearly there would be no possible elaboration order.
22816 The above pragmas allow a server to guarantee safe use by clients, and
22817 clearly this is the preferable approach. Consequently a good rule
22818 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22819 and if this is not possible,
22820 mark them as @code{Elaborate_Body} if possible.
22821 As we have seen, there are situations where neither of these
22822 three pragmas can be used.
22823 So we also provide methods for clients to control the
22824 order of elaboration of the servers on which they depend:
22827 @item pragma Elaborate (unit)
22829 @cindex pragma Elaborate
22830 This pragma is placed in the context clause, after a @code{with} clause,
22831 and it requires that the body of the named unit be elaborated before
22832 the unit in which the pragma occurs. The idea is to use this pragma
22833 if the current unit calls at elaboration time, directly or indirectly,
22834 some subprogram in the named unit.
22836 @item pragma Elaborate_All (unit)
22837 @findex Elaborate_All
22838 @cindex pragma Elaborate_All
22839 This is a stronger version of the Elaborate pragma. Consider the
22843 Unit A @code{with}'s unit B and calls B.Func in elab code
22844 Unit B @code{with}'s unit C, and B.Func calls C.Func
22848 Now if we put a pragma @code{Elaborate (B)}
22849 in unit @code{A}, this ensures that the
22850 body of @code{B} is elaborated before the call, but not the
22851 body of @code{C}, so
22852 the call to @code{C.Func} could still cause @code{Program_Error} to
22855 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22856 not only that the body of the named unit be elaborated before the
22857 unit doing the @code{with}, but also the bodies of all units that the
22858 named unit uses, following @code{with} links transitively. For example,
22859 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22861 not only that the body of @code{B} be elaborated before @code{A},
22863 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22867 We are now in a position to give a usage rule in Ada for avoiding
22868 elaboration problems, at least if dynamic dispatching and access to
22869 subprogram values are not used. We will handle these cases separately
22872 The rule is simple. If a unit has elaboration code that can directly or
22873 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22874 a generic package in a @code{with}'ed unit,
22875 then if the @code{with}'ed unit does not have
22876 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22877 a pragma @code{Elaborate_All}
22878 for the @code{with}'ed unit. By following this rule a client is
22879 assured that calls can be made without risk of an exception.
22881 For generic subprogram instantiations, the rule can be relaxed to
22882 require only a pragma @code{Elaborate} since elaborating the body
22883 of a subprogram cannot cause any transitive elaboration (we are
22884 not calling the subprogram in this case, just elaborating its
22887 If this rule is not followed, then a program may be in one of four
22891 @item No order exists
22892 No order of elaboration exists which follows the rules, taking into
22893 account any @code{Elaborate}, @code{Elaborate_All},
22894 or @code{Elaborate_Body} pragmas. In
22895 this case, an Ada compiler must diagnose the situation at bind
22896 time, and refuse to build an executable program.
22898 @item One or more orders exist, all incorrect
22899 One or more acceptable elaboration orders exist, and all of them
22900 generate an elaboration order problem. In this case, the binder
22901 can build an executable program, but @code{Program_Error} will be raised
22902 when the program is run.
22904 @item Several orders exist, some right, some incorrect
22905 One or more acceptable elaboration orders exists, and some of them
22906 work, and some do not. The programmer has not controlled
22907 the order of elaboration, so the binder may or may not pick one of
22908 the correct orders, and the program may or may not raise an
22909 exception when it is run. This is the worst case, because it means
22910 that the program may fail when moved to another compiler, or even
22911 another version of the same compiler.
22913 @item One or more orders exists, all correct
22914 One ore more acceptable elaboration orders exist, and all of them
22915 work. In this case the program runs successfully. This state of
22916 affairs can be guaranteed by following the rule we gave above, but
22917 may be true even if the rule is not followed.
22921 Note that one additional advantage of following our rules on the use
22922 of @code{Elaborate} and @code{Elaborate_All}
22923 is that the program continues to stay in the ideal (all orders OK) state
22924 even if maintenance
22925 changes some bodies of some units. Conversely, if a program that does
22926 not follow this rule happens to be safe at some point, this state of affairs
22927 may deteriorate silently as a result of maintenance changes.
22929 You may have noticed that the above discussion did not mention
22930 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22931 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22932 code in the body makes calls to some other unit, so it is still necessary
22933 to use @code{Elaborate_All} on such units.
22935 @node Controlling Elaboration in GNAT - Internal Calls
22936 @section Controlling Elaboration in GNAT - Internal Calls
22939 In the case of internal calls, i.e., calls within a single package, the
22940 programmer has full control over the order of elaboration, and it is up
22941 to the programmer to elaborate declarations in an appropriate order. For
22944 @smallexample @c ada
22947 function One return Float;
22951 function One return Float is
22960 will obviously raise @code{Program_Error} at run time, because function
22961 One will be called before its body is elaborated. In this case GNAT will
22962 generate a warning that the call will raise @code{Program_Error}:
22968 2. function One return Float;
22970 4. Q : Float := One;
22972 >>> warning: cannot call "One" before body is elaborated
22973 >>> warning: Program_Error will be raised at run time
22976 6. function One return Float is
22989 Note that in this particular case, it is likely that the call is safe, because
22990 the function @code{One} does not access any global variables.
22991 Nevertheless in Ada, we do not want the validity of the check to depend on
22992 the contents of the body (think about the separate compilation case), so this
22993 is still wrong, as we discussed in the previous sections.
22995 The error is easily corrected by rearranging the declarations so that the
22996 body of @code{One} appears before the declaration containing the call
22997 (note that in Ada 95 and Ada 2005,
22998 declarations can appear in any order, so there is no restriction that
22999 would prevent this reordering, and if we write:
23001 @smallexample @c ada
23004 function One return Float;
23006 function One return Float is
23017 then all is well, no warning is generated, and no
23018 @code{Program_Error} exception
23020 Things are more complicated when a chain of subprograms is executed:
23022 @smallexample @c ada
23025 function A return Integer;
23026 function B return Integer;
23027 function C return Integer;
23029 function B return Integer is begin return A; end;
23030 function C return Integer is begin return B; end;
23034 function A return Integer is begin return 1; end;
23040 Now the call to @code{C}
23041 at elaboration time in the declaration of @code{X} is correct, because
23042 the body of @code{C} is already elaborated,
23043 and the call to @code{B} within the body of
23044 @code{C} is correct, but the call
23045 to @code{A} within the body of @code{B} is incorrect, because the body
23046 of @code{A} has not been elaborated, so @code{Program_Error}
23047 will be raised on the call to @code{A}.
23048 In this case GNAT will generate a
23049 warning that @code{Program_Error} may be
23050 raised at the point of the call. Let's look at the warning:
23056 2. function A return Integer;
23057 3. function B return Integer;
23058 4. function C return Integer;
23060 6. function B return Integer is begin return A; end;
23062 >>> warning: call to "A" before body is elaborated may
23063 raise Program_Error
23064 >>> warning: "B" called at line 7
23065 >>> warning: "C" called at line 9
23067 7. function C return Integer is begin return B; end;
23069 9. X : Integer := C;
23071 11. function A return Integer is begin return 1; end;
23081 Note that the message here says ``may raise'', instead of the direct case,
23082 where the message says ``will be raised''. That's because whether
23084 actually called depends in general on run-time flow of control.
23085 For example, if the body of @code{B} said
23087 @smallexample @c ada
23090 function B return Integer is
23092 if some-condition-depending-on-input-data then
23103 then we could not know until run time whether the incorrect call to A would
23104 actually occur, so @code{Program_Error} might
23105 or might not be raised. It is possible for a compiler to
23106 do a better job of analyzing bodies, to
23107 determine whether or not @code{Program_Error}
23108 might be raised, but it certainly
23109 couldn't do a perfect job (that would require solving the halting problem
23110 and is provably impossible), and because this is a warning anyway, it does
23111 not seem worth the effort to do the analysis. Cases in which it
23112 would be relevant are rare.
23114 In practice, warnings of either of the forms given
23115 above will usually correspond to
23116 real errors, and should be examined carefully and eliminated.
23117 In the rare case where a warning is bogus, it can be suppressed by any of
23118 the following methods:
23122 Compile with the @option{-gnatws} switch set
23125 Suppress @code{Elaboration_Check} for the called subprogram
23128 Use pragma @code{Warnings_Off} to turn warnings off for the call
23132 For the internal elaboration check case,
23133 GNAT by default generates the
23134 necessary run-time checks to ensure
23135 that @code{Program_Error} is raised if any
23136 call fails an elaboration check. Of course this can only happen if a
23137 warning has been issued as described above. The use of pragma
23138 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23139 some of these checks, meaning that it may be possible (but is not
23140 guaranteed) for a program to be able to call a subprogram whose body
23141 is not yet elaborated, without raising a @code{Program_Error} exception.
23143 @node Controlling Elaboration in GNAT - External Calls
23144 @section Controlling Elaboration in GNAT - External Calls
23147 The previous section discussed the case in which the execution of a
23148 particular thread of elaboration code occurred entirely within a
23149 single unit. This is the easy case to handle, because a programmer
23150 has direct and total control over the order of elaboration, and
23151 furthermore, checks need only be generated in cases which are rare
23152 and which the compiler can easily detect.
23153 The situation is more complex when separate compilation is taken into account.
23154 Consider the following:
23156 @smallexample @c ada
23160 function Sqrt (Arg : Float) return Float;
23163 package body Math is
23164 function Sqrt (Arg : Float) return Float is
23173 X : Float := Math.Sqrt (0.5);
23186 where @code{Main} is the main program. When this program is executed, the
23187 elaboration code must first be executed, and one of the jobs of the
23188 binder is to determine the order in which the units of a program are
23189 to be elaborated. In this case we have four units: the spec and body
23191 the spec of @code{Stuff} and the body of @code{Main}).
23192 In what order should the four separate sections of elaboration code
23195 There are some restrictions in the order of elaboration that the binder
23196 can choose. In particular, if unit U has a @code{with}
23197 for a package @code{X}, then you
23198 are assured that the spec of @code{X}
23199 is elaborated before U , but you are
23200 not assured that the body of @code{X}
23201 is elaborated before U.
23202 This means that in the above case, the binder is allowed to choose the
23213 but that's not good, because now the call to @code{Math.Sqrt}
23214 that happens during
23215 the elaboration of the @code{Stuff}
23216 spec happens before the body of @code{Math.Sqrt} is
23217 elaborated, and hence causes @code{Program_Error} exception to be raised.
23218 At first glance, one might say that the binder is misbehaving, because
23219 obviously you want to elaborate the body of something you @code{with}
23221 that is not a general rule that can be followed in all cases. Consider
23223 @smallexample @c ada
23226 package X is @dots{}
23228 package Y is @dots{}
23231 package body Y is @dots{}
23234 package body X is @dots{}
23240 This is a common arrangement, and, apart from the order of elaboration
23241 problems that might arise in connection with elaboration code, this works fine.
23242 A rule that says that you must first elaborate the body of anything you
23243 @code{with} cannot work in this case:
23244 the body of @code{X} @code{with}'s @code{Y},
23245 which means you would have to
23246 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23248 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23249 loop that cannot be broken.
23251 It is true that the binder can in many cases guess an order of elaboration
23252 that is unlikely to cause a @code{Program_Error}
23253 exception to be raised, and it tries to do so (in the
23254 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23256 elaborate the body of @code{Math} right after its spec, so all will be well).
23258 However, a program that blindly relies on the binder to be helpful can
23259 get into trouble, as we discussed in the previous sections, so
23261 provides a number of facilities for assisting the programmer in
23262 developing programs that are robust with respect to elaboration order.
23264 @node Default Behavior in GNAT - Ensuring Safety
23265 @section Default Behavior in GNAT - Ensuring Safety
23268 The default behavior in GNAT ensures elaboration safety. In its
23269 default mode GNAT implements the
23270 rule we previously described as the right approach. Let's restate it:
23274 @emph{If a unit has elaboration code that can directly or indirectly make a
23275 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23276 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23277 does not have pragma @code{Pure} or
23278 @code{Preelaborate}, then the client should have an
23279 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23281 @emph{In the case of instantiating a generic subprogram, it is always
23282 sufficient to have only an @code{Elaborate} pragma for the
23283 @code{with}'ed unit.}
23287 By following this rule a client is assured that calls and instantiations
23288 can be made without risk of an exception.
23290 In this mode GNAT traces all calls that are potentially made from
23291 elaboration code, and puts in any missing implicit @code{Elaborate}
23292 and @code{Elaborate_All} pragmas.
23293 The advantage of this approach is that no elaboration problems
23294 are possible if the binder can find an elaboration order that is
23295 consistent with these implicit @code{Elaborate} and
23296 @code{Elaborate_All} pragmas. The
23297 disadvantage of this approach is that no such order may exist.
23299 If the binder does not generate any diagnostics, then it means that it has
23300 found an elaboration order that is guaranteed to be safe. However, the binder
23301 may still be relying on implicitly generated @code{Elaborate} and
23302 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23305 If it is important to guarantee portability, then the compilations should
23308 (warn on elaboration problems) switch. This will cause warning messages
23309 to be generated indicating the missing @code{Elaborate} and
23310 @code{Elaborate_All} pragmas.
23311 Consider the following source program:
23313 @smallexample @c ada
23318 m : integer := k.r;
23325 where it is clear that there
23326 should be a pragma @code{Elaborate_All}
23327 for unit @code{k}. An implicit pragma will be generated, and it is
23328 likely that the binder will be able to honor it. However, if you want
23329 to port this program to some other Ada compiler than GNAT.
23330 it is safer to include the pragma explicitly in the source. If this
23331 unit is compiled with the
23333 switch, then the compiler outputs a warning:
23340 3. m : integer := k.r;
23342 >>> warning: call to "r" may raise Program_Error
23343 >>> warning: missing pragma Elaborate_All for "k"
23351 and these warnings can be used as a guide for supplying manually
23352 the missing pragmas. It is usually a bad idea to use this warning
23353 option during development. That's because it will warn you when
23354 you need to put in a pragma, but cannot warn you when it is time
23355 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23356 unnecessary dependencies and even false circularities.
23358 This default mode is more restrictive than the Ada Reference
23359 Manual, and it is possible to construct programs which will compile
23360 using the dynamic model described there, but will run into a
23361 circularity using the safer static model we have described.
23363 Of course any Ada compiler must be able to operate in a mode
23364 consistent with the requirements of the Ada Reference Manual,
23365 and in particular must have the capability of implementing the
23366 standard dynamic model of elaboration with run-time checks.
23368 In GNAT, this standard mode can be achieved either by the use of
23369 the @option{-gnatE} switch on the compiler (@command{gcc} or
23370 @command{gnatmake}) command, or by the use of the configuration pragma:
23372 @smallexample @c ada
23373 pragma Elaboration_Checks (DYNAMIC);
23377 Either approach will cause the unit affected to be compiled using the
23378 standard dynamic run-time elaboration checks described in the Ada
23379 Reference Manual. The static model is generally preferable, since it
23380 is clearly safer to rely on compile and link time checks rather than
23381 run-time checks. However, in the case of legacy code, it may be
23382 difficult to meet the requirements of the static model. This
23383 issue is further discussed in
23384 @ref{What to Do If the Default Elaboration Behavior Fails}.
23386 Note that the static model provides a strict subset of the allowed
23387 behavior and programs of the Ada Reference Manual, so if you do
23388 adhere to the static model and no circularities exist,
23389 then you are assured that your program will
23390 work using the dynamic model, providing that you remove any
23391 pragma Elaborate statements from the source.
23393 @node Treatment of Pragma Elaborate
23394 @section Treatment of Pragma Elaborate
23395 @cindex Pragma Elaborate
23398 The use of @code{pragma Elaborate}
23399 should generally be avoided in Ada 95 and Ada 2005 programs,
23400 since there is no guarantee that transitive calls
23401 will be properly handled. Indeed at one point, this pragma was placed
23402 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23404 Now that's a bit restrictive. In practice, the case in which
23405 @code{pragma Elaborate} is useful is when the caller knows that there
23406 are no transitive calls, or that the called unit contains all necessary
23407 transitive @code{pragma Elaborate} statements, and legacy code often
23408 contains such uses.
23410 Strictly speaking the static mode in GNAT should ignore such pragmas,
23411 since there is no assurance at compile time that the necessary safety
23412 conditions are met. In practice, this would cause GNAT to be incompatible
23413 with correctly written Ada 83 code that had all necessary
23414 @code{pragma Elaborate} statements in place. Consequently, we made the
23415 decision that GNAT in its default mode will believe that if it encounters
23416 a @code{pragma Elaborate} then the programmer knows what they are doing,
23417 and it will trust that no elaboration errors can occur.
23419 The result of this decision is two-fold. First to be safe using the
23420 static mode, you should remove all @code{pragma Elaborate} statements.
23421 Second, when fixing circularities in existing code, you can selectively
23422 use @code{pragma Elaborate} statements to convince the static mode of
23423 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23426 When using the static mode with @option{-gnatwl}, any use of
23427 @code{pragma Elaborate} will generate a warning about possible
23430 @node Elaboration Issues for Library Tasks
23431 @section Elaboration Issues for Library Tasks
23432 @cindex Library tasks, elaboration issues
23433 @cindex Elaboration of library tasks
23436 In this section we examine special elaboration issues that arise for
23437 programs that declare library level tasks.
23439 Generally the model of execution of an Ada program is that all units are
23440 elaborated, and then execution of the program starts. However, the
23441 declaration of library tasks definitely does not fit this model. The
23442 reason for this is that library tasks start as soon as they are declared
23443 (more precisely, as soon as the statement part of the enclosing package
23444 body is reached), that is to say before elaboration
23445 of the program is complete. This means that if such a task calls a
23446 subprogram, or an entry in another task, the callee may or may not be
23447 elaborated yet, and in the standard
23448 Reference Manual model of dynamic elaboration checks, you can even
23449 get timing dependent Program_Error exceptions, since there can be
23450 a race between the elaboration code and the task code.
23452 The static model of elaboration in GNAT seeks to avoid all such
23453 dynamic behavior, by being conservative, and the conservative
23454 approach in this particular case is to assume that all the code
23455 in a task body is potentially executed at elaboration time if
23456 a task is declared at the library level.
23458 This can definitely result in unexpected circularities. Consider
23459 the following example
23461 @smallexample @c ada
23467 type My_Int is new Integer;
23469 function Ident (M : My_Int) return My_Int;
23473 package body Decls is
23474 task body Lib_Task is
23480 function Ident (M : My_Int) return My_Int is
23488 procedure Put_Val (Arg : Decls.My_Int);
23492 package body Utils is
23493 procedure Put_Val (Arg : Decls.My_Int) is
23495 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23502 Decls.Lib_Task.Start;
23507 If the above example is compiled in the default static elaboration
23508 mode, then a circularity occurs. The circularity comes from the call
23509 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23510 this call occurs in elaboration code, we need an implicit pragma
23511 @code{Elaborate_All} for @code{Utils}. This means that not only must
23512 the spec and body of @code{Utils} be elaborated before the body
23513 of @code{Decls}, but also the spec and body of any unit that is
23514 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23515 the body of @code{Decls}. This is the transitive implication of
23516 pragma @code{Elaborate_All} and it makes sense, because in general
23517 the body of @code{Put_Val} might have a call to something in a
23518 @code{with'ed} unit.
23520 In this case, the body of Utils (actually its spec) @code{with's}
23521 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23522 must be elaborated before itself, in case there is a call from the
23523 body of @code{Utils}.
23525 Here is the exact chain of events we are worrying about:
23529 In the body of @code{Decls} a call is made from within the body of a library
23530 task to a subprogram in the package @code{Utils}. Since this call may
23531 occur at elaboration time (given that the task is activated at elaboration
23532 time), we have to assume the worst, i.e., that the
23533 call does happen at elaboration time.
23536 This means that the body and spec of @code{Util} must be elaborated before
23537 the body of @code{Decls} so that this call does not cause an access before
23541 Within the body of @code{Util}, specifically within the body of
23542 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23546 One such @code{with}'ed package is package @code{Decls}, so there
23547 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23548 In fact there is such a call in this example, but we would have to
23549 assume that there was such a call even if it were not there, since
23550 we are not supposed to write the body of @code{Decls} knowing what
23551 is in the body of @code{Utils}; certainly in the case of the
23552 static elaboration model, the compiler does not know what is in
23553 other bodies and must assume the worst.
23556 This means that the spec and body of @code{Decls} must also be
23557 elaborated before we elaborate the unit containing the call, but
23558 that unit is @code{Decls}! This means that the body of @code{Decls}
23559 must be elaborated before itself, and that's a circularity.
23563 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23564 the body of @code{Decls} you will get a true Ada Reference Manual
23565 circularity that makes the program illegal.
23567 In practice, we have found that problems with the static model of
23568 elaboration in existing code often arise from library tasks, so
23569 we must address this particular situation.
23571 Note that if we compile and run the program above, using the dynamic model of
23572 elaboration (that is to say use the @option{-gnatE} switch),
23573 then it compiles, binds,
23574 links, and runs, printing the expected result of 2. Therefore in some sense
23575 the circularity here is only apparent, and we need to capture
23576 the properties of this program that distinguish it from other library-level
23577 tasks that have real elaboration problems.
23579 We have four possible answers to this question:
23584 Use the dynamic model of elaboration.
23586 If we use the @option{-gnatE} switch, then as noted above, the program works.
23587 Why is this? If we examine the task body, it is apparent that the task cannot
23589 @code{accept} statement until after elaboration has been completed, because
23590 the corresponding entry call comes from the main program, not earlier.
23591 This is why the dynamic model works here. But that's really giving
23592 up on a precise analysis, and we prefer to take this approach only if we cannot
23594 problem in any other manner. So let us examine two ways to reorganize
23595 the program to avoid the potential elaboration problem.
23598 Split library tasks into separate packages.
23600 Write separate packages, so that library tasks are isolated from
23601 other declarations as much as possible. Let us look at a variation on
23604 @smallexample @c ada
23612 package body Decls1 is
23613 task body Lib_Task is
23621 type My_Int is new Integer;
23622 function Ident (M : My_Int) return My_Int;
23626 package body Decls2 is
23627 function Ident (M : My_Int) return My_Int is
23635 procedure Put_Val (Arg : Decls2.My_Int);
23639 package body Utils is
23640 procedure Put_Val (Arg : Decls2.My_Int) is
23642 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23649 Decls1.Lib_Task.Start;
23654 All we have done is to split @code{Decls} into two packages, one
23655 containing the library task, and one containing everything else. Now
23656 there is no cycle, and the program compiles, binds, links and executes
23657 using the default static model of elaboration.
23660 Declare separate task types.
23662 A significant part of the problem arises because of the use of the
23663 single task declaration form. This means that the elaboration of
23664 the task type, and the elaboration of the task itself (i.e.@: the
23665 creation of the task) happen at the same time. A good rule
23666 of style in Ada is to always create explicit task types. By
23667 following the additional step of placing task objects in separate
23668 packages from the task type declaration, many elaboration problems
23669 are avoided. Here is another modified example of the example program:
23671 @smallexample @c ada
23673 task type Lib_Task_Type is
23677 type My_Int is new Integer;
23679 function Ident (M : My_Int) return My_Int;
23683 package body Decls is
23684 task body Lib_Task_Type is
23690 function Ident (M : My_Int) return My_Int is
23698 procedure Put_Val (Arg : Decls.My_Int);
23702 package body Utils is
23703 procedure Put_Val (Arg : Decls.My_Int) is
23705 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23711 Lib_Task : Decls.Lib_Task_Type;
23717 Declst.Lib_Task.Start;
23722 What we have done here is to replace the @code{task} declaration in
23723 package @code{Decls} with a @code{task type} declaration. Then we
23724 introduce a separate package @code{Declst} to contain the actual
23725 task object. This separates the elaboration issues for
23726 the @code{task type}
23727 declaration, which causes no trouble, from the elaboration issues
23728 of the task object, which is also unproblematic, since it is now independent
23729 of the elaboration of @code{Utils}.
23730 This separation of concerns also corresponds to
23731 a generally sound engineering principle of separating declarations
23732 from instances. This version of the program also compiles, binds, links,
23733 and executes, generating the expected output.
23736 Use No_Entry_Calls_In_Elaboration_Code restriction.
23737 @cindex No_Entry_Calls_In_Elaboration_Code
23739 The previous two approaches described how a program can be restructured
23740 to avoid the special problems caused by library task bodies. in practice,
23741 however, such restructuring may be difficult to apply to existing legacy code,
23742 so we must consider solutions that do not require massive rewriting.
23744 Let us consider more carefully why our original sample program works
23745 under the dynamic model of elaboration. The reason is that the code
23746 in the task body blocks immediately on the @code{accept}
23747 statement. Now of course there is nothing to prohibit elaboration
23748 code from making entry calls (for example from another library level task),
23749 so we cannot tell in isolation that
23750 the task will not execute the accept statement during elaboration.
23752 However, in practice it is very unusual to see elaboration code
23753 make any entry calls, and the pattern of tasks starting
23754 at elaboration time and then immediately blocking on @code{accept} or
23755 @code{select} statements is very common. What this means is that
23756 the compiler is being too pessimistic when it analyzes the
23757 whole package body as though it might be executed at elaboration
23760 If we know that the elaboration code contains no entry calls, (a very safe
23761 assumption most of the time, that could almost be made the default
23762 behavior), then we can compile all units of the program under control
23763 of the following configuration pragma:
23766 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23770 This pragma can be placed in the @file{gnat.adc} file in the usual
23771 manner. If we take our original unmodified program and compile it
23772 in the presence of a @file{gnat.adc} containing the above pragma,
23773 then once again, we can compile, bind, link, and execute, obtaining
23774 the expected result. In the presence of this pragma, the compiler does
23775 not trace calls in a task body, that appear after the first @code{accept}
23776 or @code{select} statement, and therefore does not report a potential
23777 circularity in the original program.
23779 The compiler will check to the extent it can that the above
23780 restriction is not violated, but it is not always possible to do a
23781 complete check at compile time, so it is important to use this
23782 pragma only if the stated restriction is in fact met, that is to say
23783 no task receives an entry call before elaboration of all units is completed.
23787 @node Mixing Elaboration Models
23788 @section Mixing Elaboration Models
23790 So far, we have assumed that the entire program is either compiled
23791 using the dynamic model or static model, ensuring consistency. It
23792 is possible to mix the two models, but rules have to be followed
23793 if this mixing is done to ensure that elaboration checks are not
23796 The basic rule is that @emph{a unit compiled with the static model cannot
23797 be @code{with'ed} by a unit compiled with the dynamic model}. The
23798 reason for this is that in the static model, a unit assumes that
23799 its clients guarantee to use (the equivalent of) pragma
23800 @code{Elaborate_All} so that no elaboration checks are required
23801 in inner subprograms, and this assumption is violated if the
23802 client is compiled with dynamic checks.
23804 The precise rule is as follows. A unit that is compiled with dynamic
23805 checks can only @code{with} a unit that meets at least one of the
23806 following criteria:
23811 The @code{with'ed} unit is itself compiled with dynamic elaboration
23812 checks (that is with the @option{-gnatE} switch.
23815 The @code{with'ed} unit is an internal GNAT implementation unit from
23816 the System, Interfaces, Ada, or GNAT hierarchies.
23819 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23822 The @code{with'ing} unit (that is the client) has an explicit pragma
23823 @code{Elaborate_All} for the @code{with'ed} unit.
23828 If this rule is violated, that is if a unit with dynamic elaboration
23829 checks @code{with's} a unit that does not meet one of the above four
23830 criteria, then the binder (@code{gnatbind}) will issue a warning
23831 similar to that in the following example:
23834 warning: "x.ads" has dynamic elaboration checks and with's
23835 warning: "y.ads" which has static elaboration checks
23839 These warnings indicate that the rule has been violated, and that as a result
23840 elaboration checks may be missed in the resulting executable file.
23841 This warning may be suppressed using the @option{-ws} binder switch
23842 in the usual manner.
23844 One useful application of this mixing rule is in the case of a subsystem
23845 which does not itself @code{with} units from the remainder of the
23846 application. In this case, the entire subsystem can be compiled with
23847 dynamic checks to resolve a circularity in the subsystem, while
23848 allowing the main application that uses this subsystem to be compiled
23849 using the more reliable default static model.
23851 @node What to Do If the Default Elaboration Behavior Fails
23852 @section What to Do If the Default Elaboration Behavior Fails
23855 If the binder cannot find an acceptable order, it outputs detailed
23856 diagnostics. For example:
23862 error: elaboration circularity detected
23863 info: "proc (body)" must be elaborated before "pack (body)"
23864 info: reason: Elaborate_All probably needed in unit "pack (body)"
23865 info: recompile "pack (body)" with -gnatwl
23866 info: for full details
23867 info: "proc (body)"
23868 info: is needed by its spec:
23869 info: "proc (spec)"
23870 info: which is withed by:
23871 info: "pack (body)"
23872 info: "pack (body)" must be elaborated before "proc (body)"
23873 info: reason: pragma Elaborate in unit "proc (body)"
23879 In this case we have a cycle that the binder cannot break. On the one
23880 hand, there is an explicit pragma Elaborate in @code{proc} for
23881 @code{pack}. This means that the body of @code{pack} must be elaborated
23882 before the body of @code{proc}. On the other hand, there is elaboration
23883 code in @code{pack} that calls a subprogram in @code{proc}. This means
23884 that for maximum safety, there should really be a pragma
23885 Elaborate_All in @code{pack} for @code{proc} which would require that
23886 the body of @code{proc} be elaborated before the body of
23887 @code{pack}. Clearly both requirements cannot be satisfied.
23888 Faced with a circularity of this kind, you have three different options.
23891 @item Fix the program
23892 The most desirable option from the point of view of long-term maintenance
23893 is to rearrange the program so that the elaboration problems are avoided.
23894 One useful technique is to place the elaboration code into separate
23895 child packages. Another is to move some of the initialization code to
23896 explicitly called subprograms, where the program controls the order
23897 of initialization explicitly. Although this is the most desirable option,
23898 it may be impractical and involve too much modification, especially in
23899 the case of complex legacy code.
23901 @item Perform dynamic checks
23902 If the compilations are done using the
23904 (dynamic elaboration check) switch, then GNAT behaves in a quite different
23905 manner. Dynamic checks are generated for all calls that could possibly result
23906 in raising an exception. With this switch, the compiler does not generate
23907 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
23908 exactly as specified in the @cite{Ada Reference Manual}.
23909 The binder will generate
23910 an executable program that may or may not raise @code{Program_Error}, and then
23911 it is the programmer's job to ensure that it does not raise an exception. Note
23912 that it is important to compile all units with the switch, it cannot be used
23915 @item Suppress checks
23916 The drawback of dynamic checks is that they generate a
23917 significant overhead at run time, both in space and time. If you
23918 are absolutely sure that your program cannot raise any elaboration
23919 exceptions, and you still want to use the dynamic elaboration model,
23920 then you can use the configuration pragma
23921 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23922 example this pragma could be placed in the @file{gnat.adc} file.
23924 @item Suppress checks selectively
23925 When you know that certain calls or instantiations in elaboration code cannot
23926 possibly lead to an elaboration error, and the binder nevertheless complains
23927 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
23928 elaboration circularities, it is possible to remove those warnings locally and
23929 obtain a program that will bind. Clearly this can be unsafe, and it is the
23930 responsibility of the programmer to make sure that the resulting program has no
23931 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
23932 used with different granularity to suppress warnings and break elaboration
23937 Place the pragma that names the called subprogram in the declarative part
23938 that contains the call.
23941 Place the pragma in the declarative part, without naming an entity. This
23942 disables warnings on all calls in the corresponding declarative region.
23945 Place the pragma in the package spec that declares the called subprogram,
23946 and name the subprogram. This disables warnings on all elaboration calls to
23950 Place the pragma in the package spec that declares the called subprogram,
23951 without naming any entity. This disables warnings on all elaboration calls to
23952 all subprograms declared in this spec.
23954 @item Use Pragma Elaborate
23955 As previously described in section @xref{Treatment of Pragma Elaborate},
23956 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23957 that no elaboration checks are required on calls to the designated unit.
23958 There may be cases in which the caller knows that no transitive calls
23959 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23960 case where @code{pragma Elaborate_All} would cause a circularity.
23964 These five cases are listed in order of decreasing safety, and therefore
23965 require increasing programmer care in their application. Consider the
23968 @smallexample @c adanocomment
23970 function F1 return Integer;
23975 function F2 return Integer;
23976 function Pure (x : integer) return integer;
23977 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
23978 -- pragma Suppress (Elaboration_Check); -- (4)
23982 package body Pack1 is
23983 function F1 return Integer is
23987 Val : integer := Pack2.Pure (11); -- Elab. call (1)
23990 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
23991 -- pragma Suppress(Elaboration_Check); -- (2)
23993 X1 := Pack2.F2 + 1; -- Elab. call (2)
23998 package body Pack2 is
23999 function F2 return Integer is
24003 function Pure (x : integer) return integer is
24005 return x ** 3 - 3 * x;
24009 with Pack1, Ada.Text_IO;
24012 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24015 In the absence of any pragmas, an attempt to bind this program produces
24016 the following diagnostics:
24022 error: elaboration circularity detected
24023 info: "pack1 (body)" must be elaborated before "pack1 (body)"
24024 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
24025 info: recompile "pack1 (body)" with -gnatwl for full details
24026 info: "pack1 (body)"
24027 info: must be elaborated along with its spec:
24028 info: "pack1 (spec)"
24029 info: which is withed by:
24030 info: "pack2 (body)"
24031 info: which must be elaborated along with its spec:
24032 info: "pack2 (spec)"
24033 info: which is withed by:
24034 info: "pack1 (body)"
24037 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24038 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24039 F2 is safe, even though F2 calls F1, because the call appears after the
24040 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24041 remove the warning on the call. It is also possible to use pragma (2)
24042 because there are no other potentially unsafe calls in the block.
24045 The call to @code{Pure} is safe because this function does not depend on the
24046 state of @code{Pack2}. Therefore any call to this function is safe, and it
24047 is correct to place pragma (3) in the corresponding package spec.
24050 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24051 warnings on all calls to functions declared therein. Note that this is not
24052 necessarily safe, and requires more detailed examination of the subprogram
24053 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24054 be already elaborated.
24058 It is hard to generalize on which of these four approaches should be
24059 taken. Obviously if it is possible to fix the program so that the default
24060 treatment works, this is preferable, but this may not always be practical.
24061 It is certainly simple enough to use
24063 but the danger in this case is that, even if the GNAT binder
24064 finds a correct elaboration order, it may not always do so,
24065 and certainly a binder from another Ada compiler might not. A
24066 combination of testing and analysis (for which the warnings generated
24069 switch can be useful) must be used to ensure that the program is free
24070 of errors. One switch that is useful in this testing is the
24071 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24074 Normally the binder tries to find an order that has the best chance
24075 of avoiding elaboration problems. However, if this switch is used, the binder
24076 plays a devil's advocate role, and tries to choose the order that
24077 has the best chance of failing. If your program works even with this
24078 switch, then it has a better chance of being error free, but this is still
24081 For an example of this approach in action, consider the C-tests (executable
24082 tests) from the ACVC suite. If these are compiled and run with the default
24083 treatment, then all but one of them succeed without generating any error
24084 diagnostics from the binder. However, there is one test that fails, and
24085 this is not surprising, because the whole point of this test is to ensure
24086 that the compiler can handle cases where it is impossible to determine
24087 a correct order statically, and it checks that an exception is indeed
24088 raised at run time.
24090 This one test must be compiled and run using the
24092 switch, and then it passes. Alternatively, the entire suite can
24093 be run using this switch. It is never wrong to run with the dynamic
24094 elaboration switch if your code is correct, and we assume that the
24095 C-tests are indeed correct (it is less efficient, but efficiency is
24096 not a factor in running the ACVC tests.)
24098 @node Elaboration for Access-to-Subprogram Values
24099 @section Elaboration for Access-to-Subprogram Values
24100 @cindex Access-to-subprogram
24103 Access-to-subprogram types (introduced in Ada 95) complicate
24104 the handling of elaboration. The trouble is that it becomes
24105 impossible to tell at compile time which procedure
24106 is being called. This means that it is not possible for the binder
24107 to analyze the elaboration requirements in this case.
24109 If at the point at which the access value is created
24110 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24111 the body of the subprogram is
24112 known to have been elaborated, then the access value is safe, and its use
24113 does not require a check. This may be achieved by appropriate arrangement
24114 of the order of declarations if the subprogram is in the current unit,
24115 or, if the subprogram is in another unit, by using pragma
24116 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24117 on the referenced unit.
24119 If the referenced body is not known to have been elaborated at the point
24120 the access value is created, then any use of the access value must do a
24121 dynamic check, and this dynamic check will fail and raise a
24122 @code{Program_Error} exception if the body has not been elaborated yet.
24123 GNAT will generate the necessary checks, and in addition, if the
24125 switch is set, will generate warnings that such checks are required.
24127 The use of dynamic dispatching for tagged types similarly generates
24128 a requirement for dynamic checks, and premature calls to any primitive
24129 operation of a tagged type before the body of the operation has been
24130 elaborated, will result in the raising of @code{Program_Error}.
24132 @node Summary of Procedures for Elaboration Control
24133 @section Summary of Procedures for Elaboration Control
24134 @cindex Elaboration control
24137 First, compile your program with the default options, using none of
24138 the special elaboration control switches. If the binder successfully
24139 binds your program, then you can be confident that, apart from issues
24140 raised by the use of access-to-subprogram types and dynamic dispatching,
24141 the program is free of elaboration errors. If it is important that the
24142 program be portable, then use the
24144 switch to generate warnings about missing @code{Elaborate} or
24145 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24147 If the program fails to bind using the default static elaboration
24148 handling, then you can fix the program to eliminate the binder
24149 message, or recompile the entire program with the
24150 @option{-gnatE} switch to generate dynamic elaboration checks,
24151 and, if you are sure there really are no elaboration problems,
24152 use a global pragma @code{Suppress (Elaboration_Check)}.
24154 @node Other Elaboration Order Considerations
24155 @section Other Elaboration Order Considerations
24157 This section has been entirely concerned with the issue of finding a valid
24158 elaboration order, as defined by the Ada Reference Manual. In a case
24159 where several elaboration orders are valid, the task is to find one
24160 of the possible valid elaboration orders (and the static model in GNAT
24161 will ensure that this is achieved).
24163 The purpose of the elaboration rules in the Ada Reference Manual is to
24164 make sure that no entity is accessed before it has been elaborated. For
24165 a subprogram, this means that the spec and body must have been elaborated
24166 before the subprogram is called. For an object, this means that the object
24167 must have been elaborated before its value is read or written. A violation
24168 of either of these two requirements is an access before elaboration order,
24169 and this section has been all about avoiding such errors.
24171 In the case where more than one order of elaboration is possible, in the
24172 sense that access before elaboration errors are avoided, then any one of
24173 the orders is ``correct'' in the sense that it meets the requirements of
24174 the Ada Reference Manual, and no such error occurs.
24176 However, it may be the case for a given program, that there are
24177 constraints on the order of elaboration that come not from consideration
24178 of avoiding elaboration errors, but rather from extra-lingual logic
24179 requirements. Consider this example:
24181 @smallexample @c ada
24182 with Init_Constants;
24183 package Constants is
24188 package Init_Constants is
24189 procedure P; -- require a body
24190 end Init_Constants;
24193 package body Init_Constants is
24194 procedure P is begin null; end;
24198 end Init_Constants;
24202 Z : Integer := Constants.X + Constants.Y;
24206 with Text_IO; use Text_IO;
24209 Put_Line (Calc.Z'Img);
24214 In this example, there is more than one valid order of elaboration. For
24215 example both the following are correct orders:
24218 Init_Constants spec
24221 Init_Constants body
24226 Init_Constants spec
24227 Init_Constants body
24234 There is no language rule to prefer one or the other, both are correct
24235 from an order of elaboration point of view. But the programmatic effects
24236 of the two orders are very different. In the first, the elaboration routine
24237 of @code{Calc} initializes @code{Z} to zero, and then the main program
24238 runs with this value of zero. But in the second order, the elaboration
24239 routine of @code{Calc} runs after the body of Init_Constants has set
24240 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24243 One could perhaps by applying pretty clever non-artificial intelligence
24244 to the situation guess that it is more likely that the second order of
24245 elaboration is the one desired, but there is no formal linguistic reason
24246 to prefer one over the other. In fact in this particular case, GNAT will
24247 prefer the second order, because of the rule that bodies are elaborated
24248 as soon as possible, but it's just luck that this is what was wanted
24249 (if indeed the second order was preferred).
24251 If the program cares about the order of elaboration routines in a case like
24252 this, it is important to specify the order required. In this particular
24253 case, that could have been achieved by adding to the spec of Calc:
24255 @smallexample @c ada
24256 pragma Elaborate_All (Constants);
24260 which requires that the body (if any) and spec of @code{Constants},
24261 as well as the body and spec of any unit @code{with}'ed by
24262 @code{Constants} be elaborated before @code{Calc} is elaborated.
24264 Clearly no automatic method can always guess which alternative you require,
24265 and if you are working with legacy code that had constraints of this kind
24266 which were not properly specified by adding @code{Elaborate} or
24267 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24268 compilers can choose different orders.
24270 However, GNAT does attempt to diagnose the common situation where there
24271 are uninitialized variables in the visible part of a package spec, and the
24272 corresponding package body has an elaboration block that directly or
24273 indirectly initialized one or more of these variables. This is the situation
24274 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24275 a warning that suggests this addition if it detects this situation.
24277 The @code{gnatbind}
24278 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24279 out problems. This switch causes bodies to be elaborated as late as possible
24280 instead of as early as possible. In the example above, it would have forced
24281 the choice of the first elaboration order. If you get different results
24282 when using this switch, and particularly if one set of results is right,
24283 and one is wrong as far as you are concerned, it shows that you have some
24284 missing @code{Elaborate} pragmas. For the example above, we have the
24288 gnatmake -f -q main
24291 gnatmake -f -q main -bargs -p
24297 It is of course quite unlikely that both these results are correct, so
24298 it is up to you in a case like this to investigate the source of the
24299 difference, by looking at the two elaboration orders that are chosen,
24300 and figuring out which is correct, and then adding the necessary
24301 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24305 @c *******************************
24306 @node Conditional Compilation
24307 @appendix Conditional Compilation
24308 @c *******************************
24309 @cindex Conditional compilation
24312 It is often necessary to arrange for a single source program
24313 to serve multiple purposes, where it is compiled in different
24314 ways to achieve these different goals. Some examples of the
24315 need for this feature are
24318 @item Adapting a program to a different hardware environment
24319 @item Adapting a program to a different target architecture
24320 @item Turning debugging features on and off
24321 @item Arranging for a program to compile with different compilers
24325 In C, or C++, the typical approach would be to use the preprocessor
24326 that is defined as part of the language. The Ada language does not
24327 contain such a feature. This is not an oversight, but rather a very
24328 deliberate design decision, based on the experience that overuse of
24329 the preprocessing features in C and C++ can result in programs that
24330 are extremely difficult to maintain. For example, if we have ten
24331 switches that can be on or off, this means that there are a thousand
24332 separate programs, any one of which might not even be syntactically
24333 correct, and even if syntactically correct, the resulting program
24334 might not work correctly. Testing all combinations can quickly become
24337 Nevertheless, the need to tailor programs certainly exists, and in
24338 this Appendix we will discuss how this can
24339 be achieved using Ada in general, and GNAT in particular.
24342 * Use of Boolean Constants::
24343 * Debugging - A Special Case::
24344 * Conditionalizing Declarations::
24345 * Use of Alternative Implementations::
24349 @node Use of Boolean Constants
24350 @section Use of Boolean Constants
24353 In the case where the difference is simply which code
24354 sequence is executed, the cleanest solution is to use Boolean
24355 constants to control which code is executed.
24357 @smallexample @c ada
24359 FP_Initialize_Required : constant Boolean := True;
24361 if FP_Initialize_Required then
24368 Not only will the code inside the @code{if} statement not be executed if
24369 the constant Boolean is @code{False}, but it will also be completely
24370 deleted from the program.
24371 However, the code is only deleted after the @code{if} statement
24372 has been checked for syntactic and semantic correctness.
24373 (In contrast, with preprocessors the code is deleted before the
24374 compiler ever gets to see it, so it is not checked until the switch
24376 @cindex Preprocessors (contrasted with conditional compilation)
24378 Typically the Boolean constants will be in a separate package,
24381 @smallexample @c ada
24384 FP_Initialize_Required : constant Boolean := True;
24385 Reset_Available : constant Boolean := False;
24392 The @code{Config} package exists in multiple forms for the various targets,
24393 with an appropriate script selecting the version of @code{Config} needed.
24394 Then any other unit requiring conditional compilation can do a @code{with}
24395 of @code{Config} to make the constants visible.
24398 @node Debugging - A Special Case
24399 @section Debugging - A Special Case
24402 A common use of conditional code is to execute statements (for example
24403 dynamic checks, or output of intermediate results) under control of a
24404 debug switch, so that the debugging behavior can be turned on and off.
24405 This can be done using a Boolean constant to control whether the code
24408 @smallexample @c ada
24411 Put_Line ("got to the first stage!");
24419 @smallexample @c ada
24421 if Debugging and then Temperature > 999.0 then
24422 raise Temperature_Crazy;
24428 Since this is a common case, there are special features to deal with
24429 this in a convenient manner. For the case of tests, Ada 2005 has added
24430 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24431 @cindex pragma @code{Assert}
24432 on the @code{Assert} pragma that has always been available in GNAT, so this
24433 feature may be used with GNAT even if you are not using Ada 2005 features.
24434 The use of pragma @code{Assert} is described in
24435 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24436 example, the last test could be written:
24438 @smallexample @c ada
24439 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24445 @smallexample @c ada
24446 pragma Assert (Temperature <= 999.0);
24450 In both cases, if assertions are active and the temperature is excessive,
24451 the exception @code{Assert_Failure} will be raised, with the given string in
24452 the first case or a string indicating the location of the pragma in the second
24453 case used as the exception message.
24455 You can turn assertions on and off by using the @code{Assertion_Policy}
24457 @cindex pragma @code{Assertion_Policy}
24458 This is an Ada 2005 pragma which is implemented in all modes by
24459 GNAT, but only in the latest versions of GNAT which include Ada 2005
24460 capability. Alternatively, you can use the @option{-gnata} switch
24461 @cindex @option{-gnata} switch
24462 to enable assertions from the command line (this is recognized by all versions
24465 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24466 @code{Debug} can be used:
24467 @cindex pragma @code{Debug}
24469 @smallexample @c ada
24470 pragma Debug (Put_Line ("got to the first stage!"));
24474 If debug pragmas are enabled, the argument, which must be of the form of
24475 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24476 Only one call can be present, but of course a special debugging procedure
24477 containing any code you like can be included in the program and then
24478 called in a pragma @code{Debug} argument as needed.
24480 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24481 construct is that pragma @code{Debug} can appear in declarative contexts,
24482 such as at the very beginning of a procedure, before local declarations have
24485 Debug pragmas are enabled using either the @option{-gnata} switch that also
24486 controls assertions, or with a separate Debug_Policy pragma.
24487 @cindex pragma @code{Debug_Policy}
24488 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24489 in Ada 95 and Ada 83 programs as well), and is analogous to
24490 pragma @code{Assertion_Policy} to control assertions.
24492 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24493 and thus they can appear in @file{gnat.adc} if you are not using a
24494 project file, or in the file designated to contain configuration pragmas
24496 They then apply to all subsequent compilations. In practice the use of
24497 the @option{-gnata} switch is often the most convenient method of controlling
24498 the status of these pragmas.
24500 Note that a pragma is not a statement, so in contexts where a statement
24501 sequence is required, you can't just write a pragma on its own. You have
24502 to add a @code{null} statement.
24504 @smallexample @c ada
24507 @dots{} -- some statements
24509 pragma Assert (Num_Cases < 10);
24516 @node Conditionalizing Declarations
24517 @section Conditionalizing Declarations
24520 In some cases, it may be necessary to conditionalize declarations to meet
24521 different requirements. For example we might want a bit string whose length
24522 is set to meet some hardware message requirement.
24524 In some cases, it may be possible to do this using declare blocks controlled
24525 by conditional constants:
24527 @smallexample @c ada
24529 if Small_Machine then
24531 X : Bit_String (1 .. 10);
24537 X : Large_Bit_String (1 .. 1000);
24546 Note that in this approach, both declarations are analyzed by the
24547 compiler so this can only be used where both declarations are legal,
24548 even though one of them will not be used.
24550 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
24551 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24552 that are parameterized by these constants. For example
24554 @smallexample @c ada
24557 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24563 If @code{Bits_Per_Word} is set to 32, this generates either
24565 @smallexample @c ada
24568 Field1 at 0 range 0 .. 32;
24574 for the big endian case, or
24576 @smallexample @c ada
24579 Field1 at 0 range 10 .. 32;
24585 for the little endian case. Since a powerful subset of Ada expression
24586 notation is usable for creating static constants, clever use of this
24587 feature can often solve quite difficult problems in conditionalizing
24588 compilation (note incidentally that in Ada 95, the little endian
24589 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24590 need to define this one yourself).
24593 @node Use of Alternative Implementations
24594 @section Use of Alternative Implementations
24597 In some cases, none of the approaches described above are adequate. This
24598 can occur for example if the set of declarations required is radically
24599 different for two different configurations.
24601 In this situation, the official Ada way of dealing with conditionalizing
24602 such code is to write separate units for the different cases. As long as
24603 this does not result in excessive duplication of code, this can be done
24604 without creating maintenance problems. The approach is to share common
24605 code as far as possible, and then isolate the code and declarations
24606 that are different. Subunits are often a convenient method for breaking
24607 out a piece of a unit that is to be conditionalized, with separate files
24608 for different versions of the subunit for different targets, where the
24609 build script selects the right one to give to the compiler.
24610 @cindex Subunits (and conditional compilation)
24612 As an example, consider a situation where a new feature in Ada 2005
24613 allows something to be done in a really nice way. But your code must be able
24614 to compile with an Ada 95 compiler. Conceptually you want to say:
24616 @smallexample @c ada
24619 @dots{} neat Ada 2005 code
24621 @dots{} not quite as neat Ada 95 code
24627 where @code{Ada_2005} is a Boolean constant.
24629 But this won't work when @code{Ada_2005} is set to @code{False},
24630 since the @code{then} clause will be illegal for an Ada 95 compiler.
24631 (Recall that although such unreachable code would eventually be deleted
24632 by the compiler, it still needs to be legal. If it uses features
24633 introduced in Ada 2005, it will be illegal in Ada 95.)
24635 So instead we write
24637 @smallexample @c ada
24638 procedure Insert is separate;
24642 Then we have two files for the subunit @code{Insert}, with the two sets of
24644 If the package containing this is called @code{File_Queries}, then we might
24648 @item @file{file_queries-insert-2005.adb}
24649 @item @file{file_queries-insert-95.adb}
24653 and the build script renames the appropriate file to
24656 file_queries-insert.adb
24660 and then carries out the compilation.
24662 This can also be done with project files' naming schemes. For example:
24664 @smallexample @c project
24665 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
24669 Note also that with project files it is desirable to use a different extension
24670 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
24671 conflict may arise through another commonly used feature: to declare as part
24672 of the project a set of directories containing all the sources obeying the
24673 default naming scheme.
24675 The use of alternative units is certainly feasible in all situations,
24676 and for example the Ada part of the GNAT run-time is conditionalized
24677 based on the target architecture using this approach. As a specific example,
24678 consider the implementation of the AST feature in VMS. There is one
24686 which is the same for all architectures, and three bodies:
24690 used for all non-VMS operating systems
24691 @item s-asthan-vms-alpha.adb
24692 used for VMS on the Alpha
24693 @item s-asthan-vms-ia64.adb
24694 used for VMS on the ia64
24698 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
24699 this operating system feature is not available, and the two remaining
24700 versions interface with the corresponding versions of VMS to provide
24701 VMS-compatible AST handling. The GNAT build script knows the architecture
24702 and operating system, and automatically selects the right version,
24703 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
24705 Another style for arranging alternative implementations is through Ada's
24706 access-to-subprogram facility.
24707 In case some functionality is to be conditionally included,
24708 you can declare an access-to-procedure variable @code{Ref} that is initialized
24709 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
24711 In some library package, set @code{Ref} to @code{Proc'Access} for some
24712 procedure @code{Proc} that performs the relevant processing.
24713 The initialization only occurs if the library package is included in the
24715 The same idea can also be implemented using tagged types and dispatching
24719 @node Preprocessing
24720 @section Preprocessing
24721 @cindex Preprocessing
24724 Although it is quite possible to conditionalize code without the use of
24725 C-style preprocessing, as described earlier in this section, it is
24726 nevertheless convenient in some cases to use the C approach. Moreover,
24727 older Ada compilers have often provided some preprocessing capability,
24728 so legacy code may depend on this approach, even though it is not
24731 To accommodate such use, GNAT provides a preprocessor (modeled to a large
24732 extent on the various preprocessors that have been used
24733 with legacy code on other compilers, to enable easier transition).
24735 The preprocessor may be used in two separate modes. It can be used quite
24736 separately from the compiler, to generate a separate output source file
24737 that is then fed to the compiler as a separate step. This is the
24738 @code{gnatprep} utility, whose use is fully described in
24739 @ref{Preprocessing Using gnatprep}.
24740 @cindex @code{gnatprep}
24742 The preprocessing language allows such constructs as
24746 #if DEBUG or PRIORITY > 4 then
24747 bunch of declarations
24749 completely different bunch of declarations
24755 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
24756 defined either on the command line or in a separate file.
24758 The other way of running the preprocessor is even closer to the C style and
24759 often more convenient. In this approach the preprocessing is integrated into
24760 the compilation process. The compiler is fed the preprocessor input which
24761 includes @code{#if} lines etc, and then the compiler carries out the
24762 preprocessing internally and processes the resulting output.
24763 For more details on this approach, see @ref{Integrated Preprocessing}.
24766 @c *******************************
24767 @node Inline Assembler
24768 @appendix Inline Assembler
24769 @c *******************************
24772 If you need to write low-level software that interacts directly
24773 with the hardware, Ada provides two ways to incorporate assembly
24774 language code into your program. First, you can import and invoke
24775 external routines written in assembly language, an Ada feature fully
24776 supported by GNAT@. However, for small sections of code it may be simpler
24777 or more efficient to include assembly language statements directly
24778 in your Ada source program, using the facilities of the implementation-defined
24779 package @code{System.Machine_Code}, which incorporates the gcc
24780 Inline Assembler. The Inline Assembler approach offers a number of advantages,
24781 including the following:
24784 @item No need to use non-Ada tools
24785 @item Consistent interface over different targets
24786 @item Automatic usage of the proper calling conventions
24787 @item Access to Ada constants and variables
24788 @item Definition of intrinsic routines
24789 @item Possibility of inlining a subprogram comprising assembler code
24790 @item Code optimizer can take Inline Assembler code into account
24793 This chapter presents a series of examples to show you how to use
24794 the Inline Assembler. Although it focuses on the Intel x86,
24795 the general approach applies also to other processors.
24796 It is assumed that you are familiar with Ada
24797 and with assembly language programming.
24800 * Basic Assembler Syntax::
24801 * A Simple Example of Inline Assembler::
24802 * Output Variables in Inline Assembler::
24803 * Input Variables in Inline Assembler::
24804 * Inlining Inline Assembler Code::
24805 * Other Asm Functionality::
24808 @c ---------------------------------------------------------------------------
24809 @node Basic Assembler Syntax
24810 @section Basic Assembler Syntax
24813 The assembler used by GNAT and gcc is based not on the Intel assembly
24814 language, but rather on a language that descends from the AT&T Unix
24815 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24816 The following table summarizes the main features of @emph{as} syntax
24817 and points out the differences from the Intel conventions.
24818 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24819 pre-processor) documentation for further information.
24822 @item Register names
24823 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24825 Intel: No extra punctuation; for example @code{eax}
24827 @item Immediate operand
24828 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24830 Intel: No extra punctuation; for example @code{4}
24833 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24835 Intel: No extra punctuation; for example @code{loc}
24837 @item Memory contents
24838 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24840 Intel: Square brackets; for example @code{[loc]}
24842 @item Register contents
24843 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24845 Intel: Square brackets; for example @code{[eax]}
24847 @item Hexadecimal numbers
24848 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24850 Intel: Trailing ``h''; for example @code{A0h}
24853 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24856 Intel: Implicit, deduced by assembler; for example @code{mov}
24858 @item Instruction repetition
24859 gcc / @emph{as}: Split into two lines; for example
24865 Intel: Keep on one line; for example @code{rep stosl}
24867 @item Order of operands
24868 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24870 Intel: Destination first; for example @code{mov eax, 4}
24873 @c ---------------------------------------------------------------------------
24874 @node A Simple Example of Inline Assembler
24875 @section A Simple Example of Inline Assembler
24878 The following example will generate a single assembly language statement,
24879 @code{nop}, which does nothing. Despite its lack of run-time effect,
24880 the example will be useful in illustrating the basics of
24881 the Inline Assembler facility.
24883 @smallexample @c ada
24885 with System.Machine_Code; use System.Machine_Code;
24886 procedure Nothing is
24893 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24894 here it takes one parameter, a @emph{template string} that must be a static
24895 expression and that will form the generated instruction.
24896 @code{Asm} may be regarded as a compile-time procedure that parses
24897 the template string and additional parameters (none here),
24898 from which it generates a sequence of assembly language instructions.
24900 The examples in this chapter will illustrate several of the forms
24901 for invoking @code{Asm}; a complete specification of the syntax
24902 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
24905 Under the standard GNAT conventions, the @code{Nothing} procedure
24906 should be in a file named @file{nothing.adb}.
24907 You can build the executable in the usual way:
24911 However, the interesting aspect of this example is not its run-time behavior
24912 but rather the generated assembly code.
24913 To see this output, invoke the compiler as follows:
24915 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24917 where the options are:
24921 compile only (no bind or link)
24923 generate assembler listing
24924 @item -fomit-frame-pointer
24925 do not set up separate stack frames
24927 do not add runtime checks
24930 This gives a human-readable assembler version of the code. The resulting
24931 file will have the same name as the Ada source file, but with a @code{.s}
24932 extension. In our example, the file @file{nothing.s} has the following
24937 .file "nothing.adb"
24939 ___gnu_compiled_ada:
24942 .globl __ada_nothing
24954 The assembly code you included is clearly indicated by
24955 the compiler, between the @code{#APP} and @code{#NO_APP}
24956 delimiters. The character before the 'APP' and 'NOAPP'
24957 can differ on different targets. For example, GNU/Linux uses '#APP' while
24958 on NT you will see '/APP'.
24960 If you make a mistake in your assembler code (such as using the
24961 wrong size modifier, or using a wrong operand for the instruction) GNAT
24962 will report this error in a temporary file, which will be deleted when
24963 the compilation is finished. Generating an assembler file will help
24964 in such cases, since you can assemble this file separately using the
24965 @emph{as} assembler that comes with gcc.
24967 Assembling the file using the command
24970 as @file{nothing.s}
24973 will give you error messages whose lines correspond to the assembler
24974 input file, so you can easily find and correct any mistakes you made.
24975 If there are no errors, @emph{as} will generate an object file
24976 @file{nothing.out}.
24978 @c ---------------------------------------------------------------------------
24979 @node Output Variables in Inline Assembler
24980 @section Output Variables in Inline Assembler
24983 The examples in this section, showing how to access the processor flags,
24984 illustrate how to specify the destination operands for assembly language
24987 @smallexample @c ada
24989 with Interfaces; use Interfaces;
24990 with Ada.Text_IO; use Ada.Text_IO;
24991 with System.Machine_Code; use System.Machine_Code;
24992 procedure Get_Flags is
24993 Flags : Unsigned_32;
24996 Asm ("pushfl" & LF & HT & -- push flags on stack
24997 "popl %%eax" & LF & HT & -- load eax with flags
24998 "movl %%eax, %0", -- store flags in variable
24999 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25000 Put_Line ("Flags register:" & Flags'Img);
25005 In order to have a nicely aligned assembly listing, we have separated
25006 multiple assembler statements in the Asm template string with linefeed
25007 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25008 The resulting section of the assembly output file is:
25015 movl %eax, -40(%ebp)
25020 It would have been legal to write the Asm invocation as:
25023 Asm ("pushfl popl %%eax movl %%eax, %0")
25026 but in the generated assembler file, this would come out as:
25030 pushfl popl %eax movl %eax, -40(%ebp)
25034 which is not so convenient for the human reader.
25036 We use Ada comments
25037 at the end of each line to explain what the assembler instructions
25038 actually do. This is a useful convention.
25040 When writing Inline Assembler instructions, you need to precede each register
25041 and variable name with a percent sign. Since the assembler already requires
25042 a percent sign at the beginning of a register name, you need two consecutive
25043 percent signs for such names in the Asm template string, thus @code{%%eax}.
25044 In the generated assembly code, one of the percent signs will be stripped off.
25046 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25047 variables: operands you later define using @code{Input} or @code{Output}
25048 parameters to @code{Asm}.
25049 An output variable is illustrated in
25050 the third statement in the Asm template string:
25054 The intent is to store the contents of the eax register in a variable that can
25055 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
25056 necessarily work, since the compiler might optimize by using a register
25057 to hold Flags, and the expansion of the @code{movl} instruction would not be
25058 aware of this optimization. The solution is not to store the result directly
25059 but rather to advise the compiler to choose the correct operand form;
25060 that is the purpose of the @code{%0} output variable.
25062 Information about the output variable is supplied in the @code{Outputs}
25063 parameter to @code{Asm}:
25065 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25068 The output is defined by the @code{Asm_Output} attribute of the target type;
25069 the general format is
25071 Type'Asm_Output (constraint_string, variable_name)
25074 The constraint string directs the compiler how
25075 to store/access the associated variable. In the example
25077 Unsigned_32'Asm_Output ("=m", Flags);
25079 the @code{"m"} (memory) constraint tells the compiler that the variable
25080 @code{Flags} should be stored in a memory variable, thus preventing
25081 the optimizer from keeping it in a register. In contrast,
25083 Unsigned_32'Asm_Output ("=r", Flags);
25085 uses the @code{"r"} (register) constraint, telling the compiler to
25086 store the variable in a register.
25088 If the constraint is preceded by the equal character (@strong{=}), it tells
25089 the compiler that the variable will be used to store data into it.
25091 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25092 allowing the optimizer to choose whatever it deems best.
25094 There are a fairly large number of constraints, but the ones that are
25095 most useful (for the Intel x86 processor) are the following:
25101 global (i.e.@: can be stored anywhere)
25119 use one of eax, ebx, ecx or edx
25121 use one of eax, ebx, ecx, edx, esi or edi
25124 The full set of constraints is described in the gcc and @emph{as}
25125 documentation; note that it is possible to combine certain constraints
25126 in one constraint string.
25128 You specify the association of an output variable with an assembler operand
25129 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25131 @smallexample @c ada
25133 Asm ("pushfl" & LF & HT & -- push flags on stack
25134 "popl %%eax" & LF & HT & -- load eax with flags
25135 "movl %%eax, %0", -- store flags in variable
25136 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25140 @code{%0} will be replaced in the expanded code by the appropriate operand,
25142 the compiler decided for the @code{Flags} variable.
25144 In general, you may have any number of output variables:
25147 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25149 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25150 of @code{Asm_Output} attributes
25154 @smallexample @c ada
25156 Asm ("movl %%eax, %0" & LF & HT &
25157 "movl %%ebx, %1" & LF & HT &
25159 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
25160 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
25161 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
25165 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25166 in the Ada program.
25168 As a variation on the @code{Get_Flags} example, we can use the constraints
25169 string to direct the compiler to store the eax register into the @code{Flags}
25170 variable, instead of including the store instruction explicitly in the
25171 @code{Asm} template string:
25173 @smallexample @c ada
25175 with Interfaces; use Interfaces;
25176 with Ada.Text_IO; use Ada.Text_IO;
25177 with System.Machine_Code; use System.Machine_Code;
25178 procedure Get_Flags_2 is
25179 Flags : Unsigned_32;
25182 Asm ("pushfl" & LF & HT & -- push flags on stack
25183 "popl %%eax", -- save flags in eax
25184 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25185 Put_Line ("Flags register:" & Flags'Img);
25191 The @code{"a"} constraint tells the compiler that the @code{Flags}
25192 variable will come from the eax register. Here is the resulting code:
25200 movl %eax,-40(%ebp)
25205 The compiler generated the store of eax into Flags after
25206 expanding the assembler code.
25208 Actually, there was no need to pop the flags into the eax register;
25209 more simply, we could just pop the flags directly into the program variable:
25211 @smallexample @c ada
25213 with Interfaces; use Interfaces;
25214 with Ada.Text_IO; use Ada.Text_IO;
25215 with System.Machine_Code; use System.Machine_Code;
25216 procedure Get_Flags_3 is
25217 Flags : Unsigned_32;
25220 Asm ("pushfl" & LF & HT & -- push flags on stack
25221 "pop %0", -- save flags in Flags
25222 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25223 Put_Line ("Flags register:" & Flags'Img);
25228 @c ---------------------------------------------------------------------------
25229 @node Input Variables in Inline Assembler
25230 @section Input Variables in Inline Assembler
25233 The example in this section illustrates how to specify the source operands
25234 for assembly language statements.
25235 The program simply increments its input value by 1:
25237 @smallexample @c ada
25239 with Interfaces; use Interfaces;
25240 with Ada.Text_IO; use Ada.Text_IO;
25241 with System.Machine_Code; use System.Machine_Code;
25242 procedure Increment is
25244 function Incr (Value : Unsigned_32) return Unsigned_32 is
25245 Result : Unsigned_32;
25248 Inputs => Unsigned_32'Asm_Input ("a", Value),
25249 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25253 Value : Unsigned_32;
25257 Put_Line ("Value before is" & Value'Img);
25258 Value := Incr (Value);
25259 Put_Line ("Value after is" & Value'Img);
25264 The @code{Outputs} parameter to @code{Asm} specifies
25265 that the result will be in the eax register and that it is to be stored
25266 in the @code{Result} variable.
25268 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25269 but with an @code{Asm_Input} attribute.
25270 The @code{"="} constraint, indicating an output value, is not present.
25272 You can have multiple input variables, in the same way that you can have more
25273 than one output variable.
25275 The parameter count (%0, %1) etc, now starts at the first input
25276 statement, and continues with the output statements.
25277 When both parameters use the same variable, the
25278 compiler will treat them as the same %n operand, which is the case here.
25280 Just as the @code{Outputs} parameter causes the register to be stored into the
25281 target variable after execution of the assembler statements, so does the
25282 @code{Inputs} parameter cause its variable to be loaded into the register
25283 before execution of the assembler statements.
25285 Thus the effect of the @code{Asm} invocation is:
25287 @item load the 32-bit value of @code{Value} into eax
25288 @item execute the @code{incl %eax} instruction
25289 @item store the contents of eax into the @code{Result} variable
25292 The resulting assembler file (with @option{-O2} optimization) contains:
25295 _increment__incr.1:
25308 @c ---------------------------------------------------------------------------
25309 @node Inlining Inline Assembler Code
25310 @section Inlining Inline Assembler Code
25313 For a short subprogram such as the @code{Incr} function in the previous
25314 section, the overhead of the call and return (creating / deleting the stack
25315 frame) can be significant, compared to the amount of code in the subprogram
25316 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25317 which directs the compiler to expand invocations of the subprogram at the
25318 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25319 Here is the resulting program:
25321 @smallexample @c ada
25323 with Interfaces; use Interfaces;
25324 with Ada.Text_IO; use Ada.Text_IO;
25325 with System.Machine_Code; use System.Machine_Code;
25326 procedure Increment_2 is
25328 function Incr (Value : Unsigned_32) return Unsigned_32 is
25329 Result : Unsigned_32;
25332 Inputs => Unsigned_32'Asm_Input ("a", Value),
25333 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25336 pragma Inline (Increment);
25338 Value : Unsigned_32;
25342 Put_Line ("Value before is" & Value'Img);
25343 Value := Increment (Value);
25344 Put_Line ("Value after is" & Value'Img);
25349 Compile the program with both optimization (@option{-O2}) and inlining
25350 (@option{-gnatn}) enabled.
25352 The @code{Incr} function is still compiled as usual, but at the
25353 point in @code{Increment} where our function used to be called:
25358 call _increment__incr.1
25363 the code for the function body directly appears:
25376 thus saving the overhead of stack frame setup and an out-of-line call.
25378 @c ---------------------------------------------------------------------------
25379 @node Other Asm Functionality
25380 @section Other @code{Asm} Functionality
25383 This section describes two important parameters to the @code{Asm}
25384 procedure: @code{Clobber}, which identifies register usage;
25385 and @code{Volatile}, which inhibits unwanted optimizations.
25388 * The Clobber Parameter::
25389 * The Volatile Parameter::
25392 @c ---------------------------------------------------------------------------
25393 @node The Clobber Parameter
25394 @subsection The @code{Clobber} Parameter
25397 One of the dangers of intermixing assembly language and a compiled language
25398 such as Ada is that the compiler needs to be aware of which registers are
25399 being used by the assembly code. In some cases, such as the earlier examples,
25400 the constraint string is sufficient to indicate register usage (e.g.,
25402 the eax register). But more generally, the compiler needs an explicit
25403 identification of the registers that are used by the Inline Assembly
25406 Using a register that the compiler doesn't know about
25407 could be a side effect of an instruction (like @code{mull}
25408 storing its result in both eax and edx).
25409 It can also arise from explicit register usage in your
25410 assembly code; for example:
25413 Asm ("movl %0, %%ebx" & LF & HT &
25415 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25416 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25420 where the compiler (since it does not analyze the @code{Asm} template string)
25421 does not know you are using the ebx register.
25423 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25424 to identify the registers that will be used by your assembly code:
25428 Asm ("movl %0, %%ebx" & LF & HT &
25430 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25431 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25436 The Clobber parameter is a static string expression specifying the
25437 register(s) you are using. Note that register names are @emph{not} prefixed
25438 by a percent sign. Also, if more than one register is used then their names
25439 are separated by commas; e.g., @code{"eax, ebx"}
25441 The @code{Clobber} parameter has several additional uses:
25443 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25444 @item Use ``register'' name @code{memory} if you changed a memory location
25447 @c ---------------------------------------------------------------------------
25448 @node The Volatile Parameter
25449 @subsection The @code{Volatile} Parameter
25450 @cindex Volatile parameter
25453 Compiler optimizations in the presence of Inline Assembler may sometimes have
25454 unwanted effects. For example, when an @code{Asm} invocation with an input
25455 variable is inside a loop, the compiler might move the loading of the input
25456 variable outside the loop, regarding it as a one-time initialization.
25458 If this effect is not desired, you can disable such optimizations by setting
25459 the @code{Volatile} parameter to @code{True}; for example:
25461 @smallexample @c ada
25463 Asm ("movl %0, %%ebx" & LF & HT &
25465 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25466 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25472 By default, @code{Volatile} is set to @code{False} unless there is no
25473 @code{Outputs} parameter.
25475 Although setting @code{Volatile} to @code{True} prevents unwanted
25476 optimizations, it will also disable other optimizations that might be
25477 important for efficiency. In general, you should set @code{Volatile}
25478 to @code{True} only if the compiler's optimizations have created
25480 @c END OF INLINE ASSEMBLER CHAPTER
25481 @c ===============================
25483 @c ***********************************
25484 @c * Compatibility and Porting Guide *
25485 @c ***********************************
25486 @node Compatibility and Porting Guide
25487 @appendix Compatibility and Porting Guide
25490 This chapter describes the compatibility issues that may arise between
25491 GNAT and other Ada compilation systems (including those for Ada 83),
25492 and shows how GNAT can expedite porting
25493 applications developed in other Ada environments.
25496 * Compatibility with Ada 83::
25497 * Compatibility between Ada 95 and Ada 2005::
25498 * Implementation-dependent characteristics::
25499 * Compatibility with Other Ada Systems::
25500 * Representation Clauses::
25502 @c Brief section is only in non-VMS version
25503 @c Full chapter is in VMS version
25504 * Compatibility with HP Ada 83::
25507 * Transitioning to 64-Bit GNAT for OpenVMS::
25511 @node Compatibility with Ada 83
25512 @section Compatibility with Ada 83
25513 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25516 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
25517 particular, the design intention was that the difficulties associated
25518 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25519 that occur when moving from one Ada 83 system to another.
25521 However, there are a number of points at which there are minor
25522 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
25523 full details of these issues,
25524 and should be consulted for a complete treatment.
25526 following subsections treat the most likely issues to be encountered.
25529 * Legal Ada 83 programs that are illegal in Ada 95::
25530 * More deterministic semantics::
25531 * Changed semantics::
25532 * Other language compatibility issues::
25535 @node Legal Ada 83 programs that are illegal in Ada 95
25536 @subsection Legal Ada 83 programs that are illegal in Ada 95
25538 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25539 Ada 95 and thus also in Ada 2005:
25542 @item Character literals
25543 Some uses of character literals are ambiguous. Since Ada 95 has introduced
25544 @code{Wide_Character} as a new predefined character type, some uses of
25545 character literals that were legal in Ada 83 are illegal in Ada 95.
25547 @smallexample @c ada
25548 for Char in 'A' .. 'Z' loop @dots{} end loop;
25552 The problem is that @code{'A'} and @code{'Z'} could be from either
25553 @code{Character} or @code{Wide_Character}. The simplest correction
25554 is to make the type explicit; e.g.:
25555 @smallexample @c ada
25556 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25559 @item New reserved words
25560 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25561 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25562 Existing Ada 83 code using any of these identifiers must be edited to
25563 use some alternative name.
25565 @item Freezing rules
25566 The rules in Ada 95 are slightly different with regard to the point at
25567 which entities are frozen, and representation pragmas and clauses are
25568 not permitted past the freeze point. This shows up most typically in
25569 the form of an error message complaining that a representation item
25570 appears too late, and the appropriate corrective action is to move
25571 the item nearer to the declaration of the entity to which it refers.
25573 A particular case is that representation pragmas
25576 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25578 cannot be applied to a subprogram body. If necessary, a separate subprogram
25579 declaration must be introduced to which the pragma can be applied.
25581 @item Optional bodies for library packages
25582 In Ada 83, a package that did not require a package body was nevertheless
25583 allowed to have one. This lead to certain surprises in compiling large
25584 systems (situations in which the body could be unexpectedly ignored by the
25585 binder). In Ada 95, if a package does not require a body then it is not
25586 permitted to have a body. To fix this problem, simply remove a redundant
25587 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25588 into the spec that makes the body required. One approach is to add a private
25589 part to the package declaration (if necessary), and define a parameterless
25590 procedure called @code{Requires_Body}, which must then be given a dummy
25591 procedure body in the package body, which then becomes required.
25592 Another approach (assuming that this does not introduce elaboration
25593 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25594 since one effect of this pragma is to require the presence of a package body.
25596 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25597 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25598 @code{Constraint_Error}.
25599 This means that it is illegal to have separate exception handlers for
25600 the two exceptions. The fix is simply to remove the handler for the
25601 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25602 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25604 @item Indefinite subtypes in generics
25605 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25606 as the actual for a generic formal private type, but then the instantiation
25607 would be illegal if there were any instances of declarations of variables
25608 of this type in the generic body. In Ada 95, to avoid this clear violation
25609 of the methodological principle known as the ``contract model'',
25610 the generic declaration explicitly indicates whether
25611 or not such instantiations are permitted. If a generic formal parameter
25612 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25613 type name, then it can be instantiated with indefinite types, but no
25614 stand-alone variables can be declared of this type. Any attempt to declare
25615 such a variable will result in an illegality at the time the generic is
25616 declared. If the @code{(<>)} notation is not used, then it is illegal
25617 to instantiate the generic with an indefinite type.
25618 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25619 It will show up as a compile time error, and
25620 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25623 @node More deterministic semantics
25624 @subsection More deterministic semantics
25628 Conversions from real types to integer types round away from 0. In Ada 83
25629 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
25630 implementation freedom was intended to support unbiased rounding in
25631 statistical applications, but in practice it interfered with portability.
25632 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25633 is required. Numeric code may be affected by this change in semantics.
25634 Note, though, that this issue is no worse than already existed in Ada 83
25635 when porting code from one vendor to another.
25638 The Real-Time Annex introduces a set of policies that define the behavior of
25639 features that were implementation dependent in Ada 83, such as the order in
25640 which open select branches are executed.
25643 @node Changed semantics
25644 @subsection Changed semantics
25647 The worst kind of incompatibility is one where a program that is legal in
25648 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25649 possible in Ada 83. Fortunately this is extremely rare, but the one
25650 situation that you should be alert to is the change in the predefined type
25651 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25654 @item Range of type @code{Character}
25655 The range of @code{Standard.Character} is now the full 256 characters
25656 of Latin-1, whereas in most Ada 83 implementations it was restricted
25657 to 128 characters. Although some of the effects of
25658 this change will be manifest in compile-time rejection of legal
25659 Ada 83 programs it is possible for a working Ada 83 program to have
25660 a different effect in Ada 95, one that was not permitted in Ada 83.
25661 As an example, the expression
25662 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25663 delivers @code{255} as its value.
25664 In general, you should look at the logic of any
25665 character-processing Ada 83 program and see whether it needs to be adapted
25666 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
25667 character handling package that may be relevant if code needs to be adapted
25668 to account for the additional Latin-1 elements.
25669 The desirable fix is to
25670 modify the program to accommodate the full character set, but in some cases
25671 it may be convenient to define a subtype or derived type of Character that
25672 covers only the restricted range.
25676 @node Other language compatibility issues
25677 @subsection Other language compatibility issues
25680 @item @option{-gnat83} switch
25681 All implementations of GNAT provide a switch that causes GNAT to operate
25682 in Ada 83 mode. In this mode, some but not all compatibility problems
25683 of the type described above are handled automatically. For example, the
25684 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
25685 as identifiers as in Ada 83.
25687 in practice, it is usually advisable to make the necessary modifications
25688 to the program to remove the need for using this switch.
25689 See @ref{Compiling Different Versions of Ada}.
25691 @item Support for removed Ada 83 pragmas and attributes
25692 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
25693 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
25694 compilers are allowed, but not required, to implement these missing
25695 elements. In contrast with some other compilers, GNAT implements all
25696 such pragmas and attributes, eliminating this compatibility concern. These
25697 include @code{pragma Interface} and the floating point type attributes
25698 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25702 @node Compatibility between Ada 95 and Ada 2005
25703 @section Compatibility between Ada 95 and Ada 2005
25704 @cindex Compatibility between Ada 95 and Ada 2005
25707 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
25708 a number of incompatibilities. Several are enumerated below;
25709 for a complete description please see the
25710 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
25711 @cite{Rationale for Ada 2005}.
25714 @item New reserved words.
25715 The words @code{interface}, @code{overriding} and @code{synchronized} are
25716 reserved in Ada 2005.
25717 A pre-Ada 2005 program that uses any of these as an identifier will be
25720 @item New declarations in predefined packages.
25721 A number of packages in the predefined environment contain new declarations:
25722 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
25723 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
25724 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
25725 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
25726 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
25727 If an Ada 95 program does a @code{with} and @code{use} of any of these
25728 packages, the new declarations may cause name clashes.
25730 @item Access parameters.
25731 A nondispatching subprogram with an access parameter cannot be renamed
25732 as a dispatching operation. This was permitted in Ada 95.
25734 @item Access types, discriminants, and constraints.
25735 Rule changes in this area have led to some incompatibilities; for example,
25736 constrained subtypes of some access types are not permitted in Ada 2005.
25738 @item Aggregates for limited types.
25739 The allowance of aggregates for limited types in Ada 2005 raises the
25740 possibility of ambiguities in legal Ada 95 programs, since additional types
25741 now need to be considered in expression resolution.
25743 @item Fixed-point multiplication and division.
25744 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
25745 were legal in Ada 95 and invoked the predefined versions of these operations,
25747 The ambiguity may be resolved either by applying a type conversion to the
25748 expression, or by explicitly invoking the operation from package
25751 @item Return-by-reference types.
25752 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
25753 can declare a function returning a value from an anonymous access type.
25757 @node Implementation-dependent characteristics
25758 @section Implementation-dependent characteristics
25760 Although the Ada language defines the semantics of each construct as
25761 precisely as practical, in some situations (for example for reasons of
25762 efficiency, or where the effect is heavily dependent on the host or target
25763 platform) the implementation is allowed some freedom. In porting Ada 83
25764 code to GNAT, you need to be aware of whether / how the existing code
25765 exercised such implementation dependencies. Such characteristics fall into
25766 several categories, and GNAT offers specific support in assisting the
25767 transition from certain Ada 83 compilers.
25770 * Implementation-defined pragmas::
25771 * Implementation-defined attributes::
25773 * Elaboration order::
25774 * Target-specific aspects::
25777 @node Implementation-defined pragmas
25778 @subsection Implementation-defined pragmas
25781 Ada compilers are allowed to supplement the language-defined pragmas, and
25782 these are a potential source of non-portability. All GNAT-defined pragmas
25783 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
25784 Reference Manual}, and these include several that are specifically
25785 intended to correspond to other vendors' Ada 83 pragmas.
25786 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25787 For compatibility with HP Ada 83, GNAT supplies the pragmas
25788 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25789 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25790 and @code{Volatile}.
25791 Other relevant pragmas include @code{External} and @code{Link_With}.
25792 Some vendor-specific
25793 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25795 avoiding compiler rejection of units that contain such pragmas; they are not
25796 relevant in a GNAT context and hence are not otherwise implemented.
25798 @node Implementation-defined attributes
25799 @subsection Implementation-defined attributes
25801 Analogous to pragmas, the set of attributes may be extended by an
25802 implementation. All GNAT-defined attributes are described in
25803 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
25804 Manual}, and these include several that are specifically intended
25805 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
25806 the attribute @code{VADS_Size} may be useful. For compatibility with HP
25807 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25811 @subsection Libraries
25813 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
25814 code uses vendor-specific libraries then there are several ways to manage
25815 this in Ada 95 or Ada 2005:
25818 If the source code for the libraries (specs and bodies) are
25819 available, then the libraries can be migrated in the same way as the
25822 If the source code for the specs but not the bodies are
25823 available, then you can reimplement the bodies.
25825 Some features introduced by Ada 95 obviate the need for library support. For
25826 example most Ada 83 vendors supplied a package for unsigned integers. The
25827 Ada 95 modular type feature is the preferred way to handle this need, so
25828 instead of migrating or reimplementing the unsigned integer package it may
25829 be preferable to retrofit the application using modular types.
25832 @node Elaboration order
25833 @subsection Elaboration order
25835 The implementation can choose any elaboration order consistent with the unit
25836 dependency relationship. This freedom means that some orders can result in
25837 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25838 to invoke a subprogram its body has been elaborated, or to instantiate a
25839 generic before the generic body has been elaborated. By default GNAT
25840 attempts to choose a safe order (one that will not encounter access before
25841 elaboration problems) by implicitly inserting @code{Elaborate} or
25842 @code{Elaborate_All} pragmas where
25843 needed. However, this can lead to the creation of elaboration circularities
25844 and a resulting rejection of the program by gnatbind. This issue is
25845 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25846 In brief, there are several
25847 ways to deal with this situation:
25851 Modify the program to eliminate the circularities, e.g.@: by moving
25852 elaboration-time code into explicitly-invoked procedures
25854 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25855 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25856 @code{Elaborate_All}
25857 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25858 (by selectively suppressing elaboration checks via pragma
25859 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25862 @node Target-specific aspects
25863 @subsection Target-specific aspects
25865 Low-level applications need to deal with machine addresses, data
25866 representations, interfacing with assembler code, and similar issues. If
25867 such an Ada 83 application is being ported to different target hardware (for
25868 example where the byte endianness has changed) then you will need to
25869 carefully examine the program logic; the porting effort will heavily depend
25870 on the robustness of the original design. Moreover, Ada 95 (and thus
25871 Ada 2005) are sometimes
25872 incompatible with typical Ada 83 compiler practices regarding implicit
25873 packing, the meaning of the Size attribute, and the size of access values.
25874 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25876 @node Compatibility with Other Ada Systems
25877 @section Compatibility with Other Ada Systems
25880 If programs avoid the use of implementation dependent and
25881 implementation defined features, as documented in the @cite{Ada
25882 Reference Manual}, there should be a high degree of portability between
25883 GNAT and other Ada systems. The following are specific items which
25884 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
25885 compilers, but do not affect porting code to GNAT@.
25886 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
25887 the following issues may or may not arise for Ada 2005 programs
25888 when other compilers appear.)
25891 @item Ada 83 Pragmas and Attributes
25892 Ada 95 compilers are allowed, but not required, to implement the missing
25893 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25894 GNAT implements all such pragmas and attributes, eliminating this as
25895 a compatibility concern, but some other Ada 95 compilers reject these
25896 pragmas and attributes.
25898 @item Specialized Needs Annexes
25899 GNAT implements the full set of special needs annexes. At the
25900 current time, it is the only Ada 95 compiler to do so. This means that
25901 programs making use of these features may not be portable to other Ada
25902 95 compilation systems.
25904 @item Representation Clauses
25905 Some other Ada 95 compilers implement only the minimal set of
25906 representation clauses required by the Ada 95 reference manual. GNAT goes
25907 far beyond this minimal set, as described in the next section.
25910 @node Representation Clauses
25911 @section Representation Clauses
25914 The Ada 83 reference manual was quite vague in describing both the minimal
25915 required implementation of representation clauses, and also their precise
25916 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
25917 minimal set of capabilities required is still quite limited.
25919 GNAT implements the full required set of capabilities in
25920 Ada 95 and Ada 2005, but also goes much further, and in particular
25921 an effort has been made to be compatible with existing Ada 83 usage to the
25922 greatest extent possible.
25924 A few cases exist in which Ada 83 compiler behavior is incompatible with
25925 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
25926 intentional or accidental dependence on specific implementation dependent
25927 characteristics of these Ada 83 compilers. The following is a list of
25928 the cases most likely to arise in existing Ada 83 code.
25931 @item Implicit Packing
25932 Some Ada 83 compilers allowed a Size specification to cause implicit
25933 packing of an array or record. This could cause expensive implicit
25934 conversions for change of representation in the presence of derived
25935 types, and the Ada design intends to avoid this possibility.
25936 Subsequent AI's were issued to make it clear that such implicit
25937 change of representation in response to a Size clause is inadvisable,
25938 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
25939 Reference Manuals as implementation advice that is followed by GNAT@.
25940 The problem will show up as an error
25941 message rejecting the size clause. The fix is simply to provide
25942 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25943 a Component_Size clause.
25945 @item Meaning of Size Attribute
25946 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
25947 the minimal number of bits required to hold values of the type. For example,
25948 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
25949 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
25950 some 32 in this situation. This problem will usually show up as a compile
25951 time error, but not always. It is a good idea to check all uses of the
25952 'Size attribute when porting Ada 83 code. The GNAT specific attribute
25953 Object_Size can provide a useful way of duplicating the behavior of
25954 some Ada 83 compiler systems.
25956 @item Size of Access Types
25957 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25958 and that therefore it will be the same size as a System.Address value. This
25959 assumption is true for GNAT in most cases with one exception. For the case of
25960 a pointer to an unconstrained array type (where the bounds may vary from one
25961 value of the access type to another), the default is to use a ``fat pointer'',
25962 which is represented as two separate pointers, one to the bounds, and one to
25963 the array. This representation has a number of advantages, including improved
25964 efficiency. However, it may cause some difficulties in porting existing Ada 83
25965 code which makes the assumption that, for example, pointers fit in 32 bits on
25966 a machine with 32-bit addressing.
25968 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25969 access types in this case (where the designated type is an unconstrained array
25970 type). These thin pointers are indeed the same size as a System.Address value.
25971 To specify a thin pointer, use a size clause for the type, for example:
25973 @smallexample @c ada
25974 type X is access all String;
25975 for X'Size use Standard'Address_Size;
25979 which will cause the type X to be represented using a single pointer.
25980 When using this representation, the bounds are right behind the array.
25981 This representation is slightly less efficient, and does not allow quite
25982 such flexibility in the use of foreign pointers or in using the
25983 Unrestricted_Access attribute to create pointers to non-aliased objects.
25984 But for any standard portable use of the access type it will work in
25985 a functionally correct manner and allow porting of existing code.
25986 Note that another way of forcing a thin pointer representation
25987 is to use a component size clause for the element size in an array,
25988 or a record representation clause for an access field in a record.
25992 @c This brief section is only in the non-VMS version
25993 @c The complete chapter on HP Ada is in the VMS version
25994 @node Compatibility with HP Ada 83
25995 @section Compatibility with HP Ada 83
25998 The VMS version of GNAT fully implements all the pragmas and attributes
25999 provided by HP Ada 83, as well as providing the standard HP Ada 83
26000 libraries, including Starlet. In addition, data layouts and parameter
26001 passing conventions are highly compatible. This means that porting
26002 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26003 most other porting efforts. The following are some of the most
26004 significant differences between GNAT and HP Ada 83.
26007 @item Default floating-point representation
26008 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26009 it is VMS format. GNAT does implement the necessary pragmas
26010 (Long_Float, Float_Representation) for changing this default.
26013 The package System in GNAT exactly corresponds to the definition in the
26014 Ada 95 reference manual, which means that it excludes many of the
26015 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
26016 that contains the additional definitions, and a special pragma,
26017 Extend_System allows this package to be treated transparently as an
26018 extension of package System.
26021 The definitions provided by Aux_DEC are exactly compatible with those
26022 in the HP Ada 83 version of System, with one exception.
26023 HP Ada provides the following declarations:
26025 @smallexample @c ada
26026 TO_ADDRESS (INTEGER)
26027 TO_ADDRESS (UNSIGNED_LONGWORD)
26028 TO_ADDRESS (@i{universal_integer})
26032 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26033 an extension to Ada 83 not strictly compatible with the reference manual.
26034 In GNAT, we are constrained to be exactly compatible with the standard,
26035 and this means we cannot provide this capability. In HP Ada 83, the
26036 point of this definition is to deal with a call like:
26038 @smallexample @c ada
26039 TO_ADDRESS (16#12777#);
26043 Normally, according to the Ada 83 standard, one would expect this to be
26044 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26045 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
26046 definition using @i{universal_integer} takes precedence.
26048 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26049 is not possible to be 100% compatible. Since there are many programs using
26050 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26051 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26052 declarations provided in the GNAT version of AUX_Dec are:
26054 @smallexample @c ada
26055 function To_Address (X : Integer) return Address;
26056 pragma Pure_Function (To_Address);
26058 function To_Address_Long (X : Unsigned_Longword)
26060 pragma Pure_Function (To_Address_Long);
26064 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26065 change the name to TO_ADDRESS_LONG@.
26067 @item Task_Id values
26068 The Task_Id values assigned will be different in the two systems, and GNAT
26069 does not provide a specified value for the Task_Id of the environment task,
26070 which in GNAT is treated like any other declared task.
26074 For full details on these and other less significant compatibility issues,
26075 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26076 Overview and Comparison on HP Platforms}.
26078 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26079 attributes are recognized, although only a subset of them can sensibly
26080 be implemented. The description of pragmas in @ref{Implementation
26081 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26082 indicates whether or not they are applicable to non-VMS systems.
26086 @node Transitioning to 64-Bit GNAT for OpenVMS
26087 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26090 This section is meant to assist users of pre-2006 @value{EDITION}
26091 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26092 the version of the GNAT technology supplied in 2006 and later for
26093 OpenVMS on both Alpha and I64.
26096 * Introduction to transitioning::
26097 * Migration of 32 bit code::
26098 * Taking advantage of 64 bit addressing::
26099 * Technical details::
26102 @node Introduction to transitioning
26103 @subsection Introduction
26106 64-bit @value{EDITION} for Open VMS has been designed to meet
26111 Providing a full conforming implementation of Ada 95 and Ada 2005
26114 Allowing maximum backward compatibility, thus easing migration of existing
26118 Supplying a path for exploiting the full 64-bit address range
26122 Ada's strong typing semantics has made it
26123 impractical to have different 32-bit and 64-bit modes. As soon as
26124 one object could possibly be outside the 32-bit address space, this
26125 would make it necessary for the @code{System.Address} type to be 64 bits.
26126 In particular, this would cause inconsistencies if 32-bit code is
26127 called from 64-bit code that raises an exception.
26129 This issue has been resolved by always using 64-bit addressing
26130 at the system level, but allowing for automatic conversions between
26131 32-bit and 64-bit addresses where required. Thus users who
26132 do not currently require 64-bit addressing capabilities, can
26133 recompile their code with only minimal changes (and indeed
26134 if the code is written in portable Ada, with no assumptions about
26135 the size of the @code{Address} type, then no changes at all are necessary).
26137 this approach provides a simple, gradual upgrade path to future
26138 use of larger memories than available for 32-bit systems.
26139 Also, newly written applications or libraries will by default
26140 be fully compatible with future systems exploiting 64-bit
26141 addressing capabilities.
26143 @ref{Migration of 32 bit code}, will focus on porting applications
26144 that do not require more than 2 GB of
26145 addressable memory. This code will be referred to as
26146 @emph{32-bit code}.
26147 For applications intending to exploit the full 64-bit address space,
26148 @ref{Taking advantage of 64 bit addressing},
26149 will consider further changes that may be required.
26150 Such code will be referred to below as @emph{64-bit code}.
26152 @node Migration of 32 bit code
26153 @subsection Migration of 32-bit code
26157 * Access types and 32/64-bit allocation::
26158 * Unchecked conversions::
26159 * Predefined constants::
26160 * Interfacing with C::
26161 * 32/64-bit descriptors::
26162 * Experience with source compatibility::
26165 @node Address types
26166 @subsubsection Address types
26169 To solve the problem of mixing 64-bit and 32-bit addressing,
26170 while maintaining maximum backward compatibility, the following
26171 approach has been taken:
26175 @code{System.Address} always has a size of 64 bits
26176 @cindex @code{System.Address} size
26177 @cindex @code{Address} size
26180 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26181 @cindex @code{System.Short_Address} size
26182 @cindex @code{Short_Address} size
26186 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26187 a @code{Short_Address}
26188 may be used where an @code{Address} is required, and vice versa, without
26189 needing explicit type conversions.
26190 By virtue of the Open VMS parameter passing conventions,
26192 and exported subprograms that have 32-bit address parameters are
26193 compatible with those that have 64-bit address parameters.
26194 (See @ref{Making code 64 bit clean} for details.)
26196 The areas that may need attention are those where record types have
26197 been defined that contain components of the type @code{System.Address}, and
26198 where objects of this type are passed to code expecting a record layout with
26201 Different compilers on different platforms cannot be
26202 expected to represent the same type in the same way,
26203 since alignment constraints
26204 and other system-dependent properties affect the compiler's decision.
26205 For that reason, Ada code
26206 generally uses representation clauses to specify the expected
26207 layout where required.
26209 If such a representation clause uses 32 bits for a component having
26210 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26211 will detect that error and produce a specific diagnostic message.
26212 The developer should then determine whether the representation
26213 should be 64 bits or not and make either of two changes:
26214 change the size to 64 bits and leave the type as @code{System.Address}, or
26215 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26216 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26217 required in any code setting or accessing the field; the compiler will
26218 automatically perform any needed conversions between address
26221 @node Access types and 32/64-bit allocation
26222 @subsubsection Access types and 32/64-bit allocation
26223 @cindex 32-bit allocation
26224 @cindex 64-bit allocation
26227 By default, objects designated by access values are always allocated in
26228 the 64-bit address space, and access values themselves are represented
26229 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
26230 is required (for example if the address of an allocated object is assigned
26231 to a @code{Short_Address} variable), then several alternatives are available:
26235 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26236 definition is @code{access T} versus @code{access all T} or
26237 @code{access constant T}), may be declared with a @code{'Size} representation
26238 clause that establishes the size as 32 bits.
26239 In such circumstances allocations for that type will
26240 be from the 32-bit heap. Such a clause is not permitted
26241 for a general access type (declared with @code{access all} or
26242 @code{access constant}) as values of such types must be able to refer
26243 to any object of the designated type, including objects residing outside
26244 the 32-bit address range. Existing @w{Ada 83} code will not contain such
26245 type definitions, however, since general access types were introduced
26249 Switches for @command{GNAT BIND} control whether the internal GNAT
26250 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26251 @cindex @code{__gnat_malloc}
26252 The switches are respectively @option{-H64} (the default) and
26254 @cindex @option{-H32} (@command{gnatbind})
26255 @cindex @option{-H64} (@command{gnatbind})
26258 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26259 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26260 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26261 If this variable is left
26262 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26263 then the default (64-bit) allocation is used.
26264 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26265 then 32-bit allocation is used. The gnatbind qualifiers described above
26266 override this logical name.
26269 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26270 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26271 at a low level to convert explicit calls to @code{malloc} and related
26272 functions from the C run-time library so that they perform allocations
26273 in the 32-bit heap.
26274 Since all internal allocations from GNAT use @code{__gnat_malloc},
26275 this switch is not required unless the program makes explicit calls on
26276 @code{malloc} (or related functions) from interfaced C code.
26280 @node Unchecked conversions
26281 @subsubsection Unchecked conversions
26284 In the case of an @code{Unchecked_Conversion} where the source type is a
26285 64-bit access type or the type @code{System.Address}, and the target
26286 type is a 32-bit type, the compiler will generate a warning.
26287 Even though the generated code will still perform the required
26288 conversions, it is highly recommended in these cases to use
26289 respectively a 32-bit access type or @code{System.Short_Address}
26290 as the source type.
26292 @node Predefined constants
26293 @subsubsection Predefined constants
26296 The following table shows the correspondence between pre-2006 versions of
26297 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26300 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26301 @item @b{Constant} @tab @b{Old} @tab @b{New}
26302 @item @code{System.Word_Size} @tab 32 @tab 64
26303 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
26304 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
26305 @item @code{System.Address_Size} @tab 32 @tab 64
26309 If you need to refer to the specific
26310 memory size of a 32-bit implementation, instead of the
26311 actual memory size, use @code{System.Short_Memory_Size}
26312 rather than @code{System.Memory_Size}.
26313 Similarly, references to @code{System.Address_Size} may need
26314 to be replaced by @code{System.Short_Address'Size}.
26315 The program @command{gnatfind} may be useful for locating
26316 references to the above constants, so that you can verify that they
26319 @node Interfacing with C
26320 @subsubsection Interfacing with C
26323 In order to minimize the impact of the transition to 64-bit addresses on
26324 legacy programs, some fundamental types in the @code{Interfaces.C}
26325 package hierarchy continue to be represented in 32 bits.
26326 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26327 This eases integration with the default HP C layout choices, for example
26328 as found in the system routines in @code{DECC$SHR.EXE}.
26329 Because of this implementation choice, the type fully compatible with
26330 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26331 Depending on the context the compiler will issue a
26332 warning or an error when type @code{Address} is used, alerting the user to a
26333 potential problem. Otherwise 32-bit programs that use
26334 @code{Interfaces.C} should normally not require code modifications
26336 The other issue arising with C interfacing concerns pragma @code{Convention}.
26337 For VMS 64-bit systems, there is an issue of the appropriate default size
26338 of C convention pointers in the absence of an explicit size clause. The HP
26339 C compiler can choose either 32 or 64 bits depending on compiler options.
26340 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26341 clause is given. This proves a better choice for porting 32-bit legacy
26342 applications. In order to have a 64-bit representation, it is necessary to
26343 specify a size representation clause. For example:
26345 @smallexample @c ada
26346 type int_star is access Interfaces.C.int;
26347 pragma Convention(C, int_star);
26348 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
26351 @node 32/64-bit descriptors
26352 @subsubsection 32/64-bit descriptors
26355 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
26356 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26357 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26358 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26359 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26361 If the configuration pragma @code{Short_Descriptors} is supplied, then
26362 all descriptors will be 32 bits.
26363 @cindex pragma @code{Short_Descriptors}
26365 @node Experience with source compatibility
26366 @subsubsection Experience with source compatibility
26369 The Security Server and STARLET on I64 provide an interesting ``test case''
26370 for source compatibility issues, since it is in such system code
26371 where assumptions about @code{Address} size might be expected to occur.
26372 Indeed, there were a small number of occasions in the Security Server
26373 file @file{jibdef.ads}
26374 where a representation clause for a record type specified
26375 32 bits for a component of type @code{Address}.
26376 All of these errors were detected by the compiler.
26377 The repair was obvious and immediate; to simply replace @code{Address} by
26378 @code{Short_Address}.
26380 In the case of STARLET, there were several record types that should
26381 have had representation clauses but did not. In these record types
26382 there was an implicit assumption that an @code{Address} value occupied
26384 These compiled without error, but their usage resulted in run-time error
26385 returns from STARLET system calls.
26386 Future GNAT technology enhancements may include a tool that detects and flags
26387 these sorts of potential source code porting problems.
26389 @c ****************************************
26390 @node Taking advantage of 64 bit addressing
26391 @subsection Taking advantage of 64-bit addressing
26394 * Making code 64 bit clean::
26395 * Allocating memory from the 64 bit storage pool::
26396 * Restrictions on use of 64 bit objects::
26397 * STARLET and other predefined libraries::
26400 @node Making code 64 bit clean
26401 @subsubsection Making code 64-bit clean
26404 In order to prevent problems that may occur when (parts of) a
26405 system start using memory outside the 32-bit address range,
26406 we recommend some additional guidelines:
26410 For imported subprograms that take parameters of the
26411 type @code{System.Address}, ensure that these subprograms can
26412 indeed handle 64-bit addresses. If not, or when in doubt,
26413 change the subprogram declaration to specify
26414 @code{System.Short_Address} instead.
26417 Resolve all warnings related to size mismatches in
26418 unchecked conversions. Failing to do so causes
26419 erroneous execution if the source object is outside
26420 the 32-bit address space.
26423 (optional) Explicitly use the 32-bit storage pool
26424 for access types used in a 32-bit context, or use
26425 generic access types where possible
26426 (@pxref{Restrictions on use of 64 bit objects}).
26430 If these rules are followed, the compiler will automatically insert
26431 any necessary checks to ensure that no addresses or access values
26432 passed to 32-bit code ever refer to objects outside the 32-bit
26434 Any attempt to do this will raise @code{Constraint_Error}.
26436 @node Allocating memory from the 64 bit storage pool
26437 @subsubsection Allocating memory from the 64-bit storage pool
26440 By default, all allocations -- for both pool-specific and general
26441 access types -- use the 64-bit storage pool. To override
26442 this default, for an individual access type or globally, see
26443 @ref{Access types and 32/64-bit allocation}.
26445 @node Restrictions on use of 64 bit objects
26446 @subsubsection Restrictions on use of 64-bit objects
26449 Taking the address of an object allocated from a 64-bit storage pool,
26450 and then passing this address to a subprogram expecting
26451 @code{System.Short_Address},
26452 or assigning it to a variable of type @code{Short_Address}, will cause
26453 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26454 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26455 no exception is raised and execution
26456 will become erroneous.
26458 @node STARLET and other predefined libraries
26459 @subsubsection STARLET and other predefined libraries
26462 All code that comes as part of GNAT is 64-bit clean, but the
26463 restrictions given in @ref{Restrictions on use of 64 bit objects},
26464 still apply. Look at the package
26465 specs to see in which contexts objects allocated
26466 in 64-bit address space are acceptable.
26468 @node Technical details
26469 @subsection Technical details
26472 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26473 Ada standard with respect to the type of @code{System.Address}. Previous
26474 versions of @value{EDITION} have defined this type as private and implemented it as a
26477 In order to allow defining @code{System.Short_Address} as a proper subtype,
26478 and to match the implicit sign extension in parameter passing,
26479 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26480 visible (i.e., non-private) integer type.
26481 Standard operations on the type, such as the binary operators ``+'', ``-'',
26482 etc., that take @code{Address} operands and return an @code{Address} result,
26483 have been hidden by declaring these
26484 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26485 ambiguities that would otherwise result from overloading.
26486 (Note that, although @code{Address} is a visible integer type,
26487 good programming practice dictates against exploiting the type's
26488 integer properties such as literals, since this will compromise
26491 Defining @code{Address} as a visible integer type helps achieve
26492 maximum compatibility for existing Ada code,
26493 without sacrificing the capabilities of the 64-bit architecture.
26496 @c ************************************************
26498 @node Microsoft Windows Topics
26499 @appendix Microsoft Windows Topics
26505 This chapter describes topics that are specific to the Microsoft Windows
26506 platforms (NT, 2000, and XP Professional).
26509 * Using GNAT on Windows::
26510 * Using a network installation of GNAT::
26511 * CONSOLE and WINDOWS subsystems::
26512 * Temporary Files::
26513 * Mixed-Language Programming on Windows::
26514 * Windows Calling Conventions::
26515 * Introduction to Dynamic Link Libraries (DLLs)::
26516 * Using DLLs with GNAT::
26517 * Building DLLs with GNAT Project files::
26518 * Building DLLs with GNAT::
26519 * Building DLLs with gnatdll::
26520 * GNAT and Windows Resources::
26521 * Debugging a DLL::
26522 * Setting Stack Size from gnatlink::
26523 * Setting Heap Size from gnatlink::
26526 @node Using GNAT on Windows
26527 @section Using GNAT on Windows
26530 One of the strengths of the GNAT technology is that its tool set
26531 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26532 @code{gdb} debugger, etc.) is used in the same way regardless of the
26535 On Windows this tool set is complemented by a number of Microsoft-specific
26536 tools that have been provided to facilitate interoperability with Windows
26537 when this is required. With these tools:
26542 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26546 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26547 relocatable and non-relocatable DLLs are supported).
26550 You can build Ada DLLs for use in other applications. These applications
26551 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26552 relocatable and non-relocatable Ada DLLs are supported.
26555 You can include Windows resources in your Ada application.
26558 You can use or create COM/DCOM objects.
26562 Immediately below are listed all known general GNAT-for-Windows restrictions.
26563 Other restrictions about specific features like Windows Resources and DLLs
26564 are listed in separate sections below.
26569 It is not possible to use @code{GetLastError} and @code{SetLastError}
26570 when tasking, protected records, or exceptions are used. In these
26571 cases, in order to implement Ada semantics, the GNAT run-time system
26572 calls certain Win32 routines that set the last error variable to 0 upon
26573 success. It should be possible to use @code{GetLastError} and
26574 @code{SetLastError} when tasking, protected record, and exception
26575 features are not used, but it is not guaranteed to work.
26578 It is not possible to link against Microsoft libraries except for
26579 import libraries. Interfacing must be done by the mean of DLLs.
26582 When the compilation environment is located on FAT32 drives, users may
26583 experience recompilations of the source files that have not changed if
26584 Daylight Saving Time (DST) state has changed since the last time files
26585 were compiled. NTFS drives do not have this problem.
26588 No components of the GNAT toolset use any entries in the Windows
26589 registry. The only entries that can be created are file associations and
26590 PATH settings, provided the user has chosen to create them at installation
26591 time, as well as some minimal book-keeping information needed to correctly
26592 uninstall or integrate different GNAT products.
26595 @node Using a network installation of GNAT
26596 @section Using a network installation of GNAT
26599 Make sure the system on which GNAT is installed is accessible from the
26600 current machine, i.e., the install location is shared over the network.
26601 Shared resources are accessed on Windows by means of UNC paths, which
26602 have the format @code{\\server\sharename\path}
26604 In order to use such a network installation, simply add the UNC path of the
26605 @file{bin} directory of your GNAT installation in front of your PATH. For
26606 example, if GNAT is installed in @file{\GNAT} directory of a share location
26607 called @file{c-drive} on a machine @file{LOKI}, the following command will
26610 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26612 Be aware that every compilation using the network installation results in the
26613 transfer of large amounts of data across the network and will likely cause
26614 serious performance penalty.
26616 @node CONSOLE and WINDOWS subsystems
26617 @section CONSOLE and WINDOWS subsystems
26618 @cindex CONSOLE Subsystem
26619 @cindex WINDOWS Subsystem
26623 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26624 (which is the default subsystem) will always create a console when
26625 launching the application. This is not something desirable when the
26626 application has a Windows GUI. To get rid of this console the
26627 application must be using the @code{WINDOWS} subsystem. To do so
26628 the @option{-mwindows} linker option must be specified.
26631 $ gnatmake winprog -largs -mwindows
26634 @node Temporary Files
26635 @section Temporary Files
26636 @cindex Temporary files
26639 It is possible to control where temporary files gets created by setting
26640 the @env{TMP} environment variable. The file will be created:
26643 @item Under the directory pointed to by the @env{TMP} environment variable if
26644 this directory exists.
26646 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
26647 set (or not pointing to a directory) and if this directory exists.
26649 @item Under the current working directory otherwise.
26653 This allows you to determine exactly where the temporary
26654 file will be created. This is particularly useful in networked
26655 environments where you may not have write access to some
26658 @node Mixed-Language Programming on Windows
26659 @section Mixed-Language Programming on Windows
26662 Developing pure Ada applications on Windows is no different than on
26663 other GNAT-supported platforms. However, when developing or porting an
26664 application that contains a mix of Ada and C/C++, the choice of your
26665 Windows C/C++ development environment conditions your overall
26666 interoperability strategy.
26668 If you use @command{gcc} to compile the non-Ada part of your application,
26669 there are no Windows-specific restrictions that affect the overall
26670 interoperability with your Ada code. If you do want to use the
26671 Microsoft tools for your non-Ada code, you have two choices:
26675 Encapsulate your non-Ada code in a DLL to be linked with your Ada
26676 application. In this case, use the Microsoft or whatever environment to
26677 build the DLL and use GNAT to build your executable
26678 (@pxref{Using DLLs with GNAT}).
26681 Or you can encapsulate your Ada code in a DLL to be linked with the
26682 other part of your application. In this case, use GNAT to build the DLL
26683 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
26684 or whatever environment to build your executable.
26687 @node Windows Calling Conventions
26688 @section Windows Calling Conventions
26692 This section pertain only to Win32. On Win64 there is a single native
26693 calling convention. All convention specifiers are ignored on this
26697 * C Calling Convention::
26698 * Stdcall Calling Convention::
26699 * Win32 Calling Convention::
26700 * DLL Calling Convention::
26704 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26705 (callee), there are several ways to push @code{G}'s parameters on the
26706 stack and there are several possible scenarios to clean up the stack
26707 upon @code{G}'s return. A calling convention is an agreed upon software
26708 protocol whereby the responsibilities between the caller (@code{F}) and
26709 the callee (@code{G}) are clearly defined. Several calling conventions
26710 are available for Windows:
26714 @code{C} (Microsoft defined)
26717 @code{Stdcall} (Microsoft defined)
26720 @code{Win32} (GNAT specific)
26723 @code{DLL} (GNAT specific)
26726 @node C Calling Convention
26727 @subsection @code{C} Calling Convention
26730 This is the default calling convention used when interfacing to C/C++
26731 routines compiled with either @command{gcc} or Microsoft Visual C++.
26733 In the @code{C} calling convention subprogram parameters are pushed on the
26734 stack by the caller from right to left. The caller itself is in charge of
26735 cleaning up the stack after the call. In addition, the name of a routine
26736 with @code{C} calling convention is mangled by adding a leading underscore.
26738 The name to use on the Ada side when importing (or exporting) a routine
26739 with @code{C} calling convention is the name of the routine. For
26740 instance the C function:
26743 int get_val (long);
26747 should be imported from Ada as follows:
26749 @smallexample @c ada
26751 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26752 pragma Import (C, Get_Val, External_Name => "get_val");
26757 Note that in this particular case the @code{External_Name} parameter could
26758 have been omitted since, when missing, this parameter is taken to be the
26759 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26760 is missing, as in the above example, this parameter is set to be the
26761 @code{External_Name} with a leading underscore.
26763 When importing a variable defined in C, you should always use the @code{C}
26764 calling convention unless the object containing the variable is part of a
26765 DLL (in which case you should use the @code{Stdcall} calling
26766 convention, @pxref{Stdcall Calling Convention}).
26768 @node Stdcall Calling Convention
26769 @subsection @code{Stdcall} Calling Convention
26772 This convention, which was the calling convention used for Pascal
26773 programs, is used by Microsoft for all the routines in the Win32 API for
26774 efficiency reasons. It must be used to import any routine for which this
26775 convention was specified.
26777 In the @code{Stdcall} calling convention subprogram parameters are pushed
26778 on the stack by the caller from right to left. The callee (and not the
26779 caller) is in charge of cleaning the stack on routine exit. In addition,
26780 the name of a routine with @code{Stdcall} calling convention is mangled by
26781 adding a leading underscore (as for the @code{C} calling convention) and a
26782 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
26783 bytes) of the parameters passed to the routine.
26785 The name to use on the Ada side when importing a C routine with a
26786 @code{Stdcall} calling convention is the name of the C routine. The leading
26787 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
26788 the compiler. For instance the Win32 function:
26791 @b{APIENTRY} int get_val (long);
26795 should be imported from Ada as follows:
26797 @smallexample @c ada
26799 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26800 pragma Import (Stdcall, Get_Val);
26801 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26806 As for the @code{C} calling convention, when the @code{External_Name}
26807 parameter is missing, it is taken to be the name of the Ada entity in lower
26808 case. If instead of writing the above import pragma you write:
26810 @smallexample @c ada
26812 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26813 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26818 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26819 of specifying the @code{External_Name} parameter you specify the
26820 @code{Link_Name} as in the following example:
26822 @smallexample @c ada
26824 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26825 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26830 then the imported routine is @code{retrieve_val}, that is, there is no
26831 decoration at all. No leading underscore and no Stdcall suffix
26832 @code{@@}@code{@var{nn}}.
26835 This is especially important as in some special cases a DLL's entry
26836 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
26837 name generated for a call has it.
26840 It is also possible to import variables defined in a DLL by using an
26841 import pragma for a variable. As an example, if a DLL contains a
26842 variable defined as:
26849 then, to access this variable from Ada you should write:
26851 @smallexample @c ada
26853 My_Var : Interfaces.C.int;
26854 pragma Import (Stdcall, My_Var);
26859 Note that to ease building cross-platform bindings this convention
26860 will be handled as a @code{C} calling convention on non-Windows platforms.
26862 @node Win32 Calling Convention
26863 @subsection @code{Win32} Calling Convention
26866 This convention, which is GNAT-specific is fully equivalent to the
26867 @code{Stdcall} calling convention described above.
26869 @node DLL Calling Convention
26870 @subsection @code{DLL} Calling Convention
26873 This convention, which is GNAT-specific is fully equivalent to the
26874 @code{Stdcall} calling convention described above.
26876 @node Introduction to Dynamic Link Libraries (DLLs)
26877 @section Introduction to Dynamic Link Libraries (DLLs)
26881 A Dynamically Linked Library (DLL) is a library that can be shared by
26882 several applications running under Windows. A DLL can contain any number of
26883 routines and variables.
26885 One advantage of DLLs is that you can change and enhance them without
26886 forcing all the applications that depend on them to be relinked or
26887 recompiled. However, you should be aware than all calls to DLL routines are
26888 slower since, as you will understand below, such calls are indirect.
26890 To illustrate the remainder of this section, suppose that an application
26891 wants to use the services of a DLL @file{API.dll}. To use the services
26892 provided by @file{API.dll} you must statically link against the DLL or
26893 an import library which contains a jump table with an entry for each
26894 routine and variable exported by the DLL. In the Microsoft world this
26895 import library is called @file{API.lib}. When using GNAT this import
26896 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
26897 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26899 After you have linked your application with the DLL or the import library
26900 and you run your application, here is what happens:
26904 Your application is loaded into memory.
26907 The DLL @file{API.dll} is mapped into the address space of your
26908 application. This means that:
26912 The DLL will use the stack of the calling thread.
26915 The DLL will use the virtual address space of the calling process.
26918 The DLL will allocate memory from the virtual address space of the calling
26922 Handles (pointers) can be safely exchanged between routines in the DLL
26923 routines and routines in the application using the DLL.
26927 The entries in the jump table (from the import library @file{libAPI.dll.a}
26928 or @file{API.lib} or automatically created when linking against a DLL)
26929 which is part of your application are initialized with the addresses
26930 of the routines and variables in @file{API.dll}.
26933 If present in @file{API.dll}, routines @code{DllMain} or
26934 @code{DllMainCRTStartup} are invoked. These routines typically contain
26935 the initialization code needed for the well-being of the routines and
26936 variables exported by the DLL.
26940 There is an additional point which is worth mentioning. In the Windows
26941 world there are two kind of DLLs: relocatable and non-relocatable
26942 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26943 in the target application address space. If the addresses of two
26944 non-relocatable DLLs overlap and these happen to be used by the same
26945 application, a conflict will occur and the application will run
26946 incorrectly. Hence, when possible, it is always preferable to use and
26947 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26948 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26949 User's Guide) removes the debugging symbols from the DLL but the DLL can
26950 still be relocated.
26952 As a side note, an interesting difference between Microsoft DLLs and
26953 Unix shared libraries, is the fact that on most Unix systems all public
26954 routines are exported by default in a Unix shared library, while under
26955 Windows it is possible (but not required) to list exported routines in
26956 a definition file (@pxref{The Definition File}).
26958 @node Using DLLs with GNAT
26959 @section Using DLLs with GNAT
26962 * Creating an Ada Spec for the DLL Services::
26963 * Creating an Import Library::
26967 To use the services of a DLL, say @file{API.dll}, in your Ada application
26972 The Ada spec for the routines and/or variables you want to access in
26973 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26974 header files provided with the DLL.
26977 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
26978 mentioned an import library is a statically linked library containing the
26979 import table which will be filled at load time to point to the actual
26980 @file{API.dll} routines. Sometimes you don't have an import library for the
26981 DLL you want to use. The following sections will explain how to build
26982 one. Note that this is optional.
26985 The actual DLL, @file{API.dll}.
26989 Once you have all the above, to compile an Ada application that uses the
26990 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26991 you simply issue the command
26994 $ gnatmake my_ada_app -largs -lAPI
26998 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
26999 tells the GNAT linker to look for an import library. The linker will
27000 look for a library name in this specific order:
27003 @item @file{libAPI.dll.a}
27004 @item @file{API.dll.a}
27005 @item @file{libAPI.a}
27006 @item @file{API.lib}
27007 @item @file{libAPI.dll}
27008 @item @file{API.dll}
27011 The first three are the GNU style import libraries. The third is the
27012 Microsoft style import libraries. The last two are the actual DLL names.
27014 Note that if the Ada package spec for @file{API.dll} contains the
27017 @smallexample @c ada
27018 pragma Linker_Options ("-lAPI");
27022 you do not have to add @option{-largs -lAPI} at the end of the
27023 @command{gnatmake} command.
27025 If any one of the items above is missing you will have to create it
27026 yourself. The following sections explain how to do so using as an
27027 example a fictitious DLL called @file{API.dll}.
27029 @node Creating an Ada Spec for the DLL Services
27030 @subsection Creating an Ada Spec for the DLL Services
27033 A DLL typically comes with a C/C++ header file which provides the
27034 definitions of the routines and variables exported by the DLL. The Ada
27035 equivalent of this header file is a package spec that contains definitions
27036 for the imported entities. If the DLL you intend to use does not come with
27037 an Ada spec you have to generate one such spec yourself. For example if
27038 the header file of @file{API.dll} is a file @file{api.h} containing the
27039 following two definitions:
27051 then the equivalent Ada spec could be:
27053 @smallexample @c ada
27056 with Interfaces.C.Strings;
27061 function Get (Str : C.Strings.Chars_Ptr) return C.int;
27064 pragma Import (C, Get);
27065 pragma Import (DLL, Some_Var);
27072 Note that a variable is
27073 @strong{always imported with a DLL convention}. A function
27074 can have @code{C} or @code{Stdcall} convention.
27075 (@pxref{Windows Calling Conventions}).
27077 @node Creating an Import Library
27078 @subsection Creating an Import Library
27079 @cindex Import library
27082 * The Definition File::
27083 * GNAT-Style Import Library::
27084 * Microsoft-Style Import Library::
27088 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27089 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27090 with @file{API.dll} you can skip this section. You can also skip this
27091 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27092 as in this case it is possible to link directly against the
27093 DLL. Otherwise read on.
27095 @node The Definition File
27096 @subsubsection The Definition File
27097 @cindex Definition file
27101 As previously mentioned, and unlike Unix systems, the list of symbols
27102 that are exported from a DLL must be provided explicitly in Windows.
27103 The main goal of a definition file is precisely that: list the symbols
27104 exported by a DLL. A definition file (usually a file with a @code{.def}
27105 suffix) has the following structure:
27110 @r{[}LIBRARY @var{name}@r{]}
27111 @r{[}DESCRIPTION @var{string}@r{]}
27121 @item LIBRARY @var{name}
27122 This section, which is optional, gives the name of the DLL.
27124 @item DESCRIPTION @var{string}
27125 This section, which is optional, gives a description string that will be
27126 embedded in the import library.
27129 This section gives the list of exported symbols (procedures, functions or
27130 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27131 section of @file{API.def} looks like:
27145 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27146 (@pxref{Windows Calling Conventions}) for a Stdcall
27147 calling convention function in the exported symbols list.
27150 There can actually be other sections in a definition file, but these
27151 sections are not relevant to the discussion at hand.
27153 @node GNAT-Style Import Library
27154 @subsubsection GNAT-Style Import Library
27157 To create a static import library from @file{API.dll} with the GNAT tools
27158 you should proceed as follows:
27162 Create the definition file @file{API.def} (@pxref{The Definition File}).
27163 For that use the @code{dll2def} tool as follows:
27166 $ dll2def API.dll > API.def
27170 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27171 to standard output the list of entry points in the DLL. Note that if
27172 some routines in the DLL have the @code{Stdcall} convention
27173 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27174 suffix then you'll have to edit @file{api.def} to add it, and specify
27175 @option{-k} to @command{gnatdll} when creating the import library.
27178 Here are some hints to find the right @code{@@}@var{nn} suffix.
27182 If you have the Microsoft import library (.lib), it is possible to get
27183 the right symbols by using Microsoft @code{dumpbin} tool (see the
27184 corresponding Microsoft documentation for further details).
27187 $ dumpbin /exports api.lib
27191 If you have a message about a missing symbol at link time the compiler
27192 tells you what symbol is expected. You just have to go back to the
27193 definition file and add the right suffix.
27197 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27198 (@pxref{Using gnatdll}) as follows:
27201 $ gnatdll -e API.def -d API.dll
27205 @code{gnatdll} takes as input a definition file @file{API.def} and the
27206 name of the DLL containing the services listed in the definition file
27207 @file{API.dll}. The name of the static import library generated is
27208 computed from the name of the definition file as follows: if the
27209 definition file name is @var{xyz}@code{.def}, the import library name will
27210 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27211 @option{-e} could have been removed because the name of the definition
27212 file (before the ``@code{.def}'' suffix) is the same as the name of the
27213 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27216 @node Microsoft-Style Import Library
27217 @subsubsection Microsoft-Style Import Library
27220 With GNAT you can either use a GNAT-style or Microsoft-style import
27221 library. A Microsoft import library is needed only if you plan to make an
27222 Ada DLL available to applications developed with Microsoft
27223 tools (@pxref{Mixed-Language Programming on Windows}).
27225 To create a Microsoft-style import library for @file{API.dll} you
27226 should proceed as follows:
27230 Create the definition file @file{API.def} from the DLL. For this use either
27231 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27232 tool (see the corresponding Microsoft documentation for further details).
27235 Build the actual import library using Microsoft's @code{lib} utility:
27238 $ lib -machine:IX86 -def:API.def -out:API.lib
27242 If you use the above command the definition file @file{API.def} must
27243 contain a line giving the name of the DLL:
27250 See the Microsoft documentation for further details about the usage of
27254 @node Building DLLs with GNAT Project files
27255 @section Building DLLs with GNAT Project files
27256 @cindex DLLs, building
27259 There is nothing specific to Windows in the build process.
27260 @pxref{Library Projects}.
27263 Due to a system limitation, it is not possible under Windows to create threads
27264 when inside the @code{DllMain} routine which is used for auto-initialization
27265 of shared libraries, so it is not possible to have library level tasks in SALs.
27267 @node Building DLLs with GNAT
27268 @section Building DLLs with GNAT
27269 @cindex DLLs, building
27272 This section explain how to build DLLs using the GNAT built-in DLL
27273 support. With the following procedure it is straight forward to build
27274 and use DLLs with GNAT.
27278 @item building object files
27280 The first step is to build all objects files that are to be included
27281 into the DLL. This is done by using the standard @command{gnatmake} tool.
27283 @item building the DLL
27285 To build the DLL you must use @command{gcc}'s @option{-shared} and
27286 @option{-shared-libgcc} options. It is quite simple to use this method:
27289 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
27292 It is important to note that in this case all symbols found in the
27293 object files are automatically exported. It is possible to restrict
27294 the set of symbols to export by passing to @command{gcc} a definition
27295 file, @pxref{The Definition File}. For example:
27298 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
27301 If you use a definition file you must export the elaboration procedures
27302 for every package that required one. Elaboration procedures are named
27303 using the package name followed by "_E".
27305 @item preparing DLL to be used
27307 For the DLL to be used by client programs the bodies must be hidden
27308 from it and the .ali set with read-only attribute. This is very important
27309 otherwise GNAT will recompile all packages and will not actually use
27310 the code in the DLL. For example:
27314 $ copy *.ads *.ali api.dll apilib
27315 $ attrib +R apilib\*.ali
27320 At this point it is possible to use the DLL by directly linking
27321 against it. Note that you must use the GNAT shared runtime when using
27322 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27326 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27329 @node Building DLLs with gnatdll
27330 @section Building DLLs with gnatdll
27331 @cindex DLLs, building
27334 * Limitations When Using Ada DLLs from Ada::
27335 * Exporting Ada Entities::
27336 * Ada DLLs and Elaboration::
27337 * Ada DLLs and Finalization::
27338 * Creating a Spec for Ada DLLs::
27339 * Creating the Definition File::
27344 Note that it is preferred to use GNAT Project files
27345 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27346 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27348 This section explains how to build DLLs containing Ada code using
27349 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27350 remainder of this section.
27352 The steps required to build an Ada DLL that is to be used by Ada as well as
27353 non-Ada applications are as follows:
27357 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27358 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27359 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27360 skip this step if you plan to use the Ada DLL only from Ada applications.
27363 Your Ada code must export an initialization routine which calls the routine
27364 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27365 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27366 routine exported by the Ada DLL must be invoked by the clients of the DLL
27367 to initialize the DLL.
27370 When useful, the DLL should also export a finalization routine which calls
27371 routine @code{adafinal} generated by @command{gnatbind} to perform the
27372 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27373 The finalization routine exported by the Ada DLL must be invoked by the
27374 clients of the DLL when the DLL services are no further needed.
27377 You must provide a spec for the services exported by the Ada DLL in each
27378 of the programming languages to which you plan to make the DLL available.
27381 You must provide a definition file listing the exported entities
27382 (@pxref{The Definition File}).
27385 Finally you must use @code{gnatdll} to produce the DLL and the import
27386 library (@pxref{Using gnatdll}).
27390 Note that a relocatable DLL stripped using the @code{strip}
27391 binutils tool will not be relocatable anymore. To build a DLL without
27392 debug information pass @code{-largs -s} to @code{gnatdll}. This
27393 restriction does not apply to a DLL built using a Library Project.
27394 @pxref{Library Projects}.
27396 @node Limitations When Using Ada DLLs from Ada
27397 @subsection Limitations When Using Ada DLLs from Ada
27400 When using Ada DLLs from Ada applications there is a limitation users
27401 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27402 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27403 each Ada DLL includes the services of the GNAT run time that are necessary
27404 to the Ada code inside the DLL. As a result, when an Ada program uses an
27405 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27406 one in the main program.
27408 It is therefore not possible to exchange GNAT run-time objects between the
27409 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27410 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27413 It is completely safe to exchange plain elementary, array or record types,
27414 Windows object handles, etc.
27416 @node Exporting Ada Entities
27417 @subsection Exporting Ada Entities
27418 @cindex Export table
27421 Building a DLL is a way to encapsulate a set of services usable from any
27422 application. As a result, the Ada entities exported by a DLL should be
27423 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27424 any Ada name mangling. As an example here is an Ada package
27425 @code{API}, spec and body, exporting two procedures, a function, and a
27428 @smallexample @c ada
27431 with Interfaces.C; use Interfaces;
27433 Count : C.int := 0;
27434 function Factorial (Val : C.int) return C.int;
27436 procedure Initialize_API;
27437 procedure Finalize_API;
27438 -- Initialization & Finalization routines. More in the next section.
27440 pragma Export (C, Initialize_API);
27441 pragma Export (C, Finalize_API);
27442 pragma Export (C, Count);
27443 pragma Export (C, Factorial);
27449 @smallexample @c ada
27452 package body API is
27453 function Factorial (Val : C.int) return C.int is
27456 Count := Count + 1;
27457 for K in 1 .. Val loop
27463 procedure Initialize_API is
27465 pragma Import (C, Adainit);
27468 end Initialize_API;
27470 procedure Finalize_API is
27471 procedure Adafinal;
27472 pragma Import (C, Adafinal);
27482 If the Ada DLL you are building will only be used by Ada applications
27483 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27484 convention. As an example, the previous package could be written as
27487 @smallexample @c ada
27491 Count : Integer := 0;
27492 function Factorial (Val : Integer) return Integer;
27494 procedure Initialize_API;
27495 procedure Finalize_API;
27496 -- Initialization and Finalization routines.
27502 @smallexample @c ada
27505 package body API is
27506 function Factorial (Val : Integer) return Integer is
27507 Fact : Integer := 1;
27509 Count := Count + 1;
27510 for K in 1 .. Val loop
27517 -- The remainder of this package body is unchanged.
27524 Note that if you do not export the Ada entities with a @code{C} or
27525 @code{Stdcall} convention you will have to provide the mangled Ada names
27526 in the definition file of the Ada DLL
27527 (@pxref{Creating the Definition File}).
27529 @node Ada DLLs and Elaboration
27530 @subsection Ada DLLs and Elaboration
27531 @cindex DLLs and elaboration
27534 The DLL that you are building contains your Ada code as well as all the
27535 routines in the Ada library that are needed by it. The first thing a
27536 user of your DLL must do is elaborate the Ada code
27537 (@pxref{Elaboration Order Handling in GNAT}).
27539 To achieve this you must export an initialization routine
27540 (@code{Initialize_API} in the previous example), which must be invoked
27541 before using any of the DLL services. This elaboration routine must call
27542 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27543 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27544 @code{Initialize_Api} for an example. Note that the GNAT binder is
27545 automatically invoked during the DLL build process by the @code{gnatdll}
27546 tool (@pxref{Using gnatdll}).
27548 When a DLL is loaded, Windows systematically invokes a routine called
27549 @code{DllMain}. It would therefore be possible to call @code{adainit}
27550 directly from @code{DllMain} without having to provide an explicit
27551 initialization routine. Unfortunately, it is not possible to call
27552 @code{adainit} from the @code{DllMain} if your program has library level
27553 tasks because access to the @code{DllMain} entry point is serialized by
27554 the system (that is, only a single thread can execute ``through'' it at a
27555 time), which means that the GNAT run time will deadlock waiting for the
27556 newly created task to complete its initialization.
27558 @node Ada DLLs and Finalization
27559 @subsection Ada DLLs and Finalization
27560 @cindex DLLs and finalization
27563 When the services of an Ada DLL are no longer needed, the client code should
27564 invoke the DLL finalization routine, if available. The DLL finalization
27565 routine is in charge of releasing all resources acquired by the DLL. In the
27566 case of the Ada code contained in the DLL, this is achieved by calling
27567 routine @code{adafinal} generated by the GNAT binder
27568 (@pxref{Binding with Non-Ada Main Programs}).
27569 See the body of @code{Finalize_Api} for an
27570 example. As already pointed out the GNAT binder is automatically invoked
27571 during the DLL build process by the @code{gnatdll} tool
27572 (@pxref{Using gnatdll}).
27574 @node Creating a Spec for Ada DLLs
27575 @subsection Creating a Spec for Ada DLLs
27578 To use the services exported by the Ada DLL from another programming
27579 language (e.g.@: C), you have to translate the specs of the exported Ada
27580 entities in that language. For instance in the case of @code{API.dll},
27581 the corresponding C header file could look like:
27586 extern int *_imp__count;
27587 #define count (*_imp__count)
27588 int factorial (int);
27594 It is important to understand that when building an Ada DLL to be used by
27595 other Ada applications, you need two different specs for the packages
27596 contained in the DLL: one for building the DLL and the other for using
27597 the DLL. This is because the @code{DLL} calling convention is needed to
27598 use a variable defined in a DLL, but when building the DLL, the variable
27599 must have either the @code{Ada} or @code{C} calling convention. As an
27600 example consider a DLL comprising the following package @code{API}:
27602 @smallexample @c ada
27606 Count : Integer := 0;
27608 -- Remainder of the package omitted.
27615 After producing a DLL containing package @code{API}, the spec that
27616 must be used to import @code{API.Count} from Ada code outside of the
27619 @smallexample @c ada
27624 pragma Import (DLL, Count);
27630 @node Creating the Definition File
27631 @subsection Creating the Definition File
27634 The definition file is the last file needed to build the DLL. It lists
27635 the exported symbols. As an example, the definition file for a DLL
27636 containing only package @code{API} (where all the entities are exported
27637 with a @code{C} calling convention) is:
27652 If the @code{C} calling convention is missing from package @code{API},
27653 then the definition file contains the mangled Ada names of the above
27654 entities, which in this case are:
27663 api__initialize_api
27668 @node Using gnatdll
27669 @subsection Using @code{gnatdll}
27673 * gnatdll Example::
27674 * gnatdll behind the Scenes::
27679 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27680 and non-Ada sources that make up your DLL have been compiled.
27681 @code{gnatdll} is actually in charge of two distinct tasks: build the
27682 static import library for the DLL and the actual DLL. The form of the
27683 @code{gnatdll} command is
27687 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27688 @c Expanding @ovar macro inline (explanation in macro def comments)
27689 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27694 where @var{list-of-files} is a list of ALI and object files. The object
27695 file list must be the exact list of objects corresponding to the non-Ada
27696 sources whose services are to be included in the DLL. The ALI file list
27697 must be the exact list of ALI files for the corresponding Ada sources
27698 whose services are to be included in the DLL. If @var{list-of-files} is
27699 missing, only the static import library is generated.
27702 You may specify any of the following switches to @code{gnatdll}:
27705 @c @item -a@ovar{address}
27706 @c Expanding @ovar macro inline (explanation in macro def comments)
27707 @item -a@r{[}@var{address}@r{]}
27708 @cindex @option{-a} (@code{gnatdll})
27709 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27710 specified the default address @var{0x11000000} will be used. By default,
27711 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27712 advise the reader to build relocatable DLL.
27714 @item -b @var{address}
27715 @cindex @option{-b} (@code{gnatdll})
27716 Set the relocatable DLL base address. By default the address is
27719 @item -bargs @var{opts}
27720 @cindex @option{-bargs} (@code{gnatdll})
27721 Binder options. Pass @var{opts} to the binder.
27723 @item -d @var{dllfile}
27724 @cindex @option{-d} (@code{gnatdll})
27725 @var{dllfile} is the name of the DLL. This switch must be present for
27726 @code{gnatdll} to do anything. The name of the generated import library is
27727 obtained algorithmically from @var{dllfile} as shown in the following
27728 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27729 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
27730 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27731 as shown in the following example:
27732 if @var{dllfile} is @code{xyz.dll}, the definition
27733 file used is @code{xyz.def}.
27735 @item -e @var{deffile}
27736 @cindex @option{-e} (@code{gnatdll})
27737 @var{deffile} is the name of the definition file.
27740 @cindex @option{-g} (@code{gnatdll})
27741 Generate debugging information. This information is stored in the object
27742 file and copied from there to the final DLL file by the linker,
27743 where it can be read by the debugger. You must use the
27744 @option{-g} switch if you plan on using the debugger or the symbolic
27748 @cindex @option{-h} (@code{gnatdll})
27749 Help mode. Displays @code{gnatdll} switch usage information.
27752 @cindex @option{-I} (@code{gnatdll})
27753 Direct @code{gnatdll} to search the @var{dir} directory for source and
27754 object files needed to build the DLL.
27755 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27758 @cindex @option{-k} (@code{gnatdll})
27759 Removes the @code{@@}@var{nn} suffix from the import library's exported
27760 names, but keeps them for the link names. You must specify this
27761 option if you want to use a @code{Stdcall} function in a DLL for which
27762 the @code{@@}@var{nn} suffix has been removed. This is the case for most
27763 of the Windows NT DLL for example. This option has no effect when
27764 @option{-n} option is specified.
27766 @item -l @var{file}
27767 @cindex @option{-l} (@code{gnatdll})
27768 The list of ALI and object files used to build the DLL are listed in
27769 @var{file}, instead of being given in the command line. Each line in
27770 @var{file} contains the name of an ALI or object file.
27773 @cindex @option{-n} (@code{gnatdll})
27774 No Import. Do not create the import library.
27777 @cindex @option{-q} (@code{gnatdll})
27778 Quiet mode. Do not display unnecessary messages.
27781 @cindex @option{-v} (@code{gnatdll})
27782 Verbose mode. Display extra information.
27784 @item -largs @var{opts}
27785 @cindex @option{-largs} (@code{gnatdll})
27786 Linker options. Pass @var{opts} to the linker.
27789 @node gnatdll Example
27790 @subsubsection @code{gnatdll} Example
27793 As an example the command to build a relocatable DLL from @file{api.adb}
27794 once @file{api.adb} has been compiled and @file{api.def} created is
27797 $ gnatdll -d api.dll api.ali
27801 The above command creates two files: @file{libapi.dll.a} (the import
27802 library) and @file{api.dll} (the actual DLL). If you want to create
27803 only the DLL, just type:
27806 $ gnatdll -d api.dll -n api.ali
27810 Alternatively if you want to create just the import library, type:
27813 $ gnatdll -d api.dll
27816 @node gnatdll behind the Scenes
27817 @subsubsection @code{gnatdll} behind the Scenes
27820 This section details the steps involved in creating a DLL. @code{gnatdll}
27821 does these steps for you. Unless you are interested in understanding what
27822 goes on behind the scenes, you should skip this section.
27824 We use the previous example of a DLL containing the Ada package @code{API},
27825 to illustrate the steps necessary to build a DLL. The starting point is a
27826 set of objects that will make up the DLL and the corresponding ALI
27827 files. In the case of this example this means that @file{api.o} and
27828 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27833 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27834 the information necessary to generate relocation information for the
27840 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27845 In addition to the base file, the @command{gnatlink} command generates an
27846 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27847 asks @command{gnatlink} to generate the routines @code{DllMain} and
27848 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27849 is loaded into memory.
27852 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27853 export table (@file{api.exp}). The export table contains the relocation
27854 information in a form which can be used during the final link to ensure
27855 that the Windows loader is able to place the DLL anywhere in memory.
27859 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27860 --output-exp api.exp
27865 @code{gnatdll} builds the base file using the new export table. Note that
27866 @command{gnatbind} must be called once again since the binder generated file
27867 has been deleted during the previous call to @command{gnatlink}.
27872 $ gnatlink api -o api.jnk api.exp -mdll
27873 -Wl,--base-file,api.base
27878 @code{gnatdll} builds the new export table using the new base file and
27879 generates the DLL import library @file{libAPI.dll.a}.
27883 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27884 --output-exp api.exp --output-lib libAPI.a
27889 Finally @code{gnatdll} builds the relocatable DLL using the final export
27895 $ gnatlink api api.exp -o api.dll -mdll
27900 @node Using dlltool
27901 @subsubsection Using @code{dlltool}
27904 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27905 DLLs and static import libraries. This section summarizes the most
27906 common @code{dlltool} switches. The form of the @code{dlltool} command
27910 @c $ dlltool @ovar{switches}
27911 @c Expanding @ovar macro inline (explanation in macro def comments)
27912 $ dlltool @r{[}@var{switches}@r{]}
27916 @code{dlltool} switches include:
27919 @item --base-file @var{basefile}
27920 @cindex @option{--base-file} (@command{dlltool})
27921 Read the base file @var{basefile} generated by the linker. This switch
27922 is used to create a relocatable DLL.
27924 @item --def @var{deffile}
27925 @cindex @option{--def} (@command{dlltool})
27926 Read the definition file.
27928 @item --dllname @var{name}
27929 @cindex @option{--dllname} (@command{dlltool})
27930 Gives the name of the DLL. This switch is used to embed the name of the
27931 DLL in the static import library generated by @code{dlltool} with switch
27932 @option{--output-lib}.
27935 @cindex @option{-k} (@command{dlltool})
27936 Kill @code{@@}@var{nn} from exported names
27937 (@pxref{Windows Calling Conventions}
27938 for a discussion about @code{Stdcall}-style symbols.
27941 @cindex @option{--help} (@command{dlltool})
27942 Prints the @code{dlltool} switches with a concise description.
27944 @item --output-exp @var{exportfile}
27945 @cindex @option{--output-exp} (@command{dlltool})
27946 Generate an export file @var{exportfile}. The export file contains the
27947 export table (list of symbols in the DLL) and is used to create the DLL.
27949 @item --output-lib @var{libfile}
27950 @cindex @option{--output-lib} (@command{dlltool})
27951 Generate a static import library @var{libfile}.
27954 @cindex @option{-v} (@command{dlltool})
27957 @item --as @var{assembler-name}
27958 @cindex @option{--as} (@command{dlltool})
27959 Use @var{assembler-name} as the assembler. The default is @code{as}.
27962 @node GNAT and Windows Resources
27963 @section GNAT and Windows Resources
27964 @cindex Resources, windows
27967 * Building Resources::
27968 * Compiling Resources::
27969 * Using Resources::
27973 Resources are an easy way to add Windows specific objects to your
27974 application. The objects that can be added as resources include:
27983 @item string tables
27993 @item version information
27996 For example, a version information resource can be defined as follow and
27997 embedded into an executable or DLL:
27999 A version information resource can be used to embed information into an
28000 executable or a DLL. These information can be viewed using the file properties
28001 from the Windows Explorer. Here is an example of a version information
28007 FILEVERSION 1,0,0,0
28008 PRODUCTVERSION 1,0,0,0
28010 BLOCK "StringFileInfo"
28014 VALUE "CompanyName", "My Company Name"
28015 VALUE "FileDescription", "My application"
28016 VALUE "FileVersion", "1.0"
28017 VALUE "InternalName", "my_app"
28018 VALUE "LegalCopyright", "My Name"
28019 VALUE "OriginalFilename", "my_app.exe"
28020 VALUE "ProductName", "My App"
28021 VALUE "ProductVersion", "1.0"
28025 BLOCK "VarFileInfo"
28027 VALUE "Translation", 0x809, 1252
28033 The value @code{0809} (langID) is for the U.K English language and
28034 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28038 This section explains how to build, compile and use resources. Note that this
28039 section does not cover all resource objects, for a complete description see
28040 the corresponding Microsoft documentation.
28042 @node Building Resources
28043 @subsection Building Resources
28044 @cindex Resources, building
28047 A resource file is an ASCII file. By convention resource files have an
28048 @file{.rc} extension.
28049 The easiest way to build a resource file is to use Microsoft tools
28050 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28051 @code{dlgedit.exe} to build dialogs.
28052 It is always possible to build an @file{.rc} file yourself by writing a
28055 It is not our objective to explain how to write a resource file. A
28056 complete description of the resource script language can be found in the
28057 Microsoft documentation.
28059 @node Compiling Resources
28060 @subsection Compiling Resources
28063 @cindex Resources, compiling
28066 This section describes how to build a GNAT-compatible (COFF) object file
28067 containing the resources. This is done using the Resource Compiler
28068 @code{windres} as follows:
28071 $ windres -i myres.rc -o myres.o
28075 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28076 file. You can specify an alternate preprocessor (usually named
28077 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28078 parameter. A list of all possible options may be obtained by entering
28079 the command @code{windres} @option{--help}.
28081 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28082 to produce a @file{.res} file (binary resource file). See the
28083 corresponding Microsoft documentation for further details. In this case
28084 you need to use @code{windres} to translate the @file{.res} file to a
28085 GNAT-compatible object file as follows:
28088 $ windres -i myres.res -o myres.o
28091 @node Using Resources
28092 @subsection Using Resources
28093 @cindex Resources, using
28096 To include the resource file in your program just add the
28097 GNAT-compatible object file for the resource(s) to the linker
28098 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28102 $ gnatmake myprog -largs myres.o
28105 @node Debugging a DLL
28106 @section Debugging a DLL
28107 @cindex DLL debugging
28110 * Program and DLL Both Built with GCC/GNAT::
28111 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28115 Debugging a DLL is similar to debugging a standard program. But
28116 we have to deal with two different executable parts: the DLL and the
28117 program that uses it. We have the following four possibilities:
28121 The program and the DLL are built with @code{GCC/GNAT}.
28123 The program is built with foreign tools and the DLL is built with
28126 The program is built with @code{GCC/GNAT} and the DLL is built with
28131 In this section we address only cases one and two above.
28132 There is no point in trying to debug
28133 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28134 information in it. To do so you must use a debugger compatible with the
28135 tools suite used to build the DLL.
28137 @node Program and DLL Both Built with GCC/GNAT
28138 @subsection Program and DLL Both Built with GCC/GNAT
28141 This is the simplest case. Both the DLL and the program have @code{GDB}
28142 compatible debugging information. It is then possible to break anywhere in
28143 the process. Let's suppose here that the main procedure is named
28144 @code{ada_main} and that in the DLL there is an entry point named
28148 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28149 program must have been built with the debugging information (see GNAT -g
28150 switch). Here are the step-by-step instructions for debugging it:
28153 @item Launch @code{GDB} on the main program.
28159 @item Start the program and stop at the beginning of the main procedure
28166 This step is required to be able to set a breakpoint inside the DLL. As long
28167 as the program is not run, the DLL is not loaded. This has the
28168 consequence that the DLL debugging information is also not loaded, so it is not
28169 possible to set a breakpoint in the DLL.
28171 @item Set a breakpoint inside the DLL
28174 (gdb) break ada_dll
28181 At this stage a breakpoint is set inside the DLL. From there on
28182 you can use the standard approach to debug the whole program
28183 (@pxref{Running and Debugging Ada Programs}).
28186 @c This used to work, probably because the DLLs were non-relocatable
28187 @c keep this section around until the problem is sorted out.
28189 To break on the @code{DllMain} routine it is not possible to follow
28190 the procedure above. At the time the program stop on @code{ada_main}
28191 the @code{DllMain} routine as already been called. Either you can use
28192 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28195 @item Launch @code{GDB} on the main program.
28201 @item Load DLL symbols
28204 (gdb) add-sym api.dll
28207 @item Set a breakpoint inside the DLL
28210 (gdb) break ada_dll.adb:45
28213 Note that at this point it is not possible to break using the routine symbol
28214 directly as the program is not yet running. The solution is to break
28215 on the proper line (break in @file{ada_dll.adb} line 45).
28217 @item Start the program
28226 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28227 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28230 * Debugging the DLL Directly::
28231 * Attaching to a Running Process::
28235 In this case things are slightly more complex because it is not possible to
28236 start the main program and then break at the beginning to load the DLL and the
28237 associated DLL debugging information. It is not possible to break at the
28238 beginning of the program because there is no @code{GDB} debugging information,
28239 and therefore there is no direct way of getting initial control. This
28240 section addresses this issue by describing some methods that can be used
28241 to break somewhere in the DLL to debug it.
28244 First suppose that the main procedure is named @code{main} (this is for
28245 example some C code built with Microsoft Visual C) and that there is a
28246 DLL named @code{test.dll} containing an Ada entry point named
28250 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28251 been built with debugging information (see GNAT -g option).
28253 @node Debugging the DLL Directly
28254 @subsubsection Debugging the DLL Directly
28258 Find out the executable starting address
28261 $ objdump --file-header main.exe
28264 The starting address is reported on the last line. For example:
28267 main.exe: file format pei-i386
28268 architecture: i386, flags 0x0000010a:
28269 EXEC_P, HAS_DEBUG, D_PAGED
28270 start address 0x00401010
28274 Launch the debugger on the executable.
28281 Set a breakpoint at the starting address, and launch the program.
28284 $ (gdb) break *0x00401010
28288 The program will stop at the given address.
28291 Set a breakpoint on a DLL subroutine.
28294 (gdb) break ada_dll.adb:45
28297 Or if you want to break using a symbol on the DLL, you need first to
28298 select the Ada language (language used by the DLL).
28301 (gdb) set language ada
28302 (gdb) break ada_dll
28306 Continue the program.
28313 This will run the program until it reaches the breakpoint that has been
28314 set. From that point you can use the standard way to debug a program
28315 as described in (@pxref{Running and Debugging Ada Programs}).
28320 It is also possible to debug the DLL by attaching to a running process.
28322 @node Attaching to a Running Process
28323 @subsubsection Attaching to a Running Process
28324 @cindex DLL debugging, attach to process
28327 With @code{GDB} it is always possible to debug a running process by
28328 attaching to it. It is possible to debug a DLL this way. The limitation
28329 of this approach is that the DLL must run long enough to perform the
28330 attach operation. It may be useful for instance to insert a time wasting
28331 loop in the code of the DLL to meet this criterion.
28335 @item Launch the main program @file{main.exe}.
28341 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28342 that the process PID for @file{main.exe} is 208.
28350 @item Attach to the running process to be debugged.
28356 @item Load the process debugging information.
28359 (gdb) symbol-file main.exe
28362 @item Break somewhere in the DLL.
28365 (gdb) break ada_dll
28368 @item Continue process execution.
28377 This last step will resume the process execution, and stop at
28378 the breakpoint we have set. From there you can use the standard
28379 approach to debug a program as described in
28380 (@pxref{Running and Debugging Ada Programs}).
28382 @node Setting Stack Size from gnatlink
28383 @section Setting Stack Size from @command{gnatlink}
28386 It is possible to specify the program stack size at link time. On modern
28387 versions of Windows, starting with XP, this is mostly useful to set the size of
28388 the main stack (environment task). The other task stacks are set with pragma
28389 Storage_Size or with the @command{gnatbind -d} command.
28391 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28392 reserve size of individual tasks, the link-time stack size applies to all
28393 tasks, and pragma Storage_Size has no effect.
28394 In particular, Stack Overflow checks are made against this
28395 link-time specified size.
28397 This setting can be done with
28398 @command{gnatlink} using either:
28402 @item using @option{-Xlinker} linker option
28405 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28408 This sets the stack reserve size to 0x10000 bytes and the stack commit
28409 size to 0x1000 bytes.
28411 @item using @option{-Wl} linker option
28414 $ gnatlink hello -Wl,--stack=0x1000000
28417 This sets the stack reserve size to 0x1000000 bytes. Note that with
28418 @option{-Wl} option it is not possible to set the stack commit size
28419 because the coma is a separator for this option.
28423 @node Setting Heap Size from gnatlink
28424 @section Setting Heap Size from @command{gnatlink}
28427 Under Windows systems, it is possible to specify the program heap size from
28428 @command{gnatlink} using either:
28432 @item using @option{-Xlinker} linker option
28435 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28438 This sets the heap reserve size to 0x10000 bytes and the heap commit
28439 size to 0x1000 bytes.
28441 @item using @option{-Wl} linker option
28444 $ gnatlink hello -Wl,--heap=0x1000000
28447 This sets the heap reserve size to 0x1000000 bytes. Note that with
28448 @option{-Wl} option it is not possible to set the heap commit size
28449 because the coma is a separator for this option.
28455 @c **********************************
28456 @c * GNU Free Documentation License *
28457 @c **********************************
28459 @c GNU Free Documentation License
28461 @node Index,,GNU Free Documentation License, Top
28467 @c Put table of contents at end, otherwise it precedes the "title page" in
28468 @c the .txt version
28469 @c Edit the pdf file to move the contents to the beginning, after the title