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:
11596 Assume_No_Invalid_Values
11601 Compile_Time_Warning
11603 Component_Alignment
11604 Convention_Identifier
11607 Default_Storage_Pool
11613 External_Name_Casing
11616 Float_Representation
11629 Priority_Specific_Dispatching
11632 Propagate_Exceptions
11635 Restricted_Run_Time
11637 Restrictions_Warnings
11639 Short_Circuit_And_Or
11641 Source_File_Name_Project
11644 Suppress_Exception_Locations
11645 Task_Dispatching_Policy
11651 Wide_Character_Encoding
11656 * Handling of Configuration Pragmas::
11657 * The Configuration Pragmas Files::
11660 @node Handling of Configuration Pragmas
11661 @section Handling of Configuration Pragmas
11663 Configuration pragmas may either appear at the start of a compilation
11664 unit, in which case they apply only to that unit, or they may apply to
11665 all compilations performed in a given compilation environment.
11667 GNAT also provides the @code{gnatchop} utility to provide an automatic
11668 way to handle configuration pragmas following the semantics for
11669 compilations (that is, files with multiple units), described in the RM.
11670 See @ref{Operating gnatchop in Compilation Mode} for details.
11671 However, for most purposes, it will be more convenient to edit the
11672 @file{gnat.adc} file that contains configuration pragmas directly,
11673 as described in the following section.
11675 @node The Configuration Pragmas Files
11676 @section The Configuration Pragmas Files
11677 @cindex @file{gnat.adc}
11680 In GNAT a compilation environment is defined by the current
11681 directory at the time that a compile command is given. This current
11682 directory is searched for a file whose name is @file{gnat.adc}. If
11683 this file is present, it is expected to contain one or more
11684 configuration pragmas that will be applied to the current compilation.
11685 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11688 Configuration pragmas may be entered into the @file{gnat.adc} file
11689 either by running @code{gnatchop} on a source file that consists only of
11690 configuration pragmas, or more conveniently by
11691 direct editing of the @file{gnat.adc} file, which is a standard format
11694 In addition to @file{gnat.adc}, additional files containing configuration
11695 pragmas may be applied to the current compilation using the switch
11696 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11697 contains only configuration pragmas. These configuration pragmas are
11698 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11699 is present and switch @option{-gnatA} is not used).
11701 It is allowed to specify several switches @option{-gnatec}, all of which
11702 will be taken into account.
11704 If you are using project file, a separate mechanism is provided using
11705 project attributes, see @ref{Specifying Configuration Pragmas} for more
11709 Of special interest to GNAT OpenVMS Alpha is the following
11710 configuration pragma:
11712 @smallexample @c ada
11714 pragma Extend_System (Aux_DEC);
11719 In the presence of this pragma, GNAT adds to the definition of the
11720 predefined package SYSTEM all the additional types and subprograms that are
11721 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11724 @node Handling Arbitrary File Naming Conventions Using gnatname
11725 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11726 @cindex Arbitrary File Naming Conventions
11729 * Arbitrary File Naming Conventions::
11730 * Running gnatname::
11731 * Switches for gnatname::
11732 * Examples of gnatname Usage::
11735 @node Arbitrary File Naming Conventions
11736 @section Arbitrary File Naming Conventions
11739 The GNAT compiler must be able to know the source file name of a compilation
11740 unit. When using the standard GNAT default file naming conventions
11741 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11742 does not need additional information.
11745 When the source file names do not follow the standard GNAT default file naming
11746 conventions, the GNAT compiler must be given additional information through
11747 a configuration pragmas file (@pxref{Configuration Pragmas})
11749 When the non-standard file naming conventions are well-defined,
11750 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11751 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11752 if the file naming conventions are irregular or arbitrary, a number
11753 of pragma @code{Source_File_Name} for individual compilation units
11755 To help maintain the correspondence between compilation unit names and
11756 source file names within the compiler,
11757 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11760 @node Running gnatname
11761 @section Running @code{gnatname}
11764 The usual form of the @code{gnatname} command is
11767 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11768 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11769 @c Expanding @ovar macro inline (explanation in macro def comments)
11770 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11771 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11775 All of the arguments are optional. If invoked without any argument,
11776 @code{gnatname} will display its usage.
11779 When used with at least one naming pattern, @code{gnatname} will attempt to
11780 find all the compilation units in files that follow at least one of the
11781 naming patterns. To find these compilation units,
11782 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11786 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11787 Each Naming Pattern is enclosed between double quotes (or single
11788 quotes on Windows).
11789 A Naming Pattern is a regular expression similar to the wildcard patterns
11790 used in file names by the Unix shells or the DOS prompt.
11793 @code{gnatname} may be called with several sections of directories/patterns.
11794 Sections are separated by switch @code{--and}. In each section, there must be
11795 at least one pattern. If no directory is specified in a section, the current
11796 directory (or the project directory is @code{-P} is used) is implied.
11797 The options other that the directory switches and the patterns apply globally
11798 even if they are in different sections.
11801 Examples of Naming Patterns are
11810 For a more complete description of the syntax of Naming Patterns,
11811 see the second kind of regular expressions described in @file{g-regexp.ads}
11812 (the ``Glob'' regular expressions).
11815 When invoked with no switch @code{-P}, @code{gnatname} will create a
11816 configuration pragmas file @file{gnat.adc} in the current working directory,
11817 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11820 @node Switches for gnatname
11821 @section Switches for @code{gnatname}
11824 Switches for @code{gnatname} must precede any specified Naming Pattern.
11827 You may specify any of the following switches to @code{gnatname}:
11833 @cindex @option{--version} @command{gnatname}
11834 Display Copyright and version, then exit disregarding all other options.
11837 @cindex @option{--help} @command{gnatname}
11838 If @option{--version} was not used, display usage, then exit disregarding
11842 Start another section of directories/patterns.
11844 @item ^-c^/CONFIG_FILE=^@file{file}
11845 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11846 Create a configuration pragmas file @file{file} (instead of the default
11849 There may be zero, one or more space between @option{-c} and
11852 @file{file} may include directory information. @file{file} must be
11853 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11854 When a switch @option{^-c^/CONFIG_FILE^} is
11855 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11857 @item ^-d^/SOURCE_DIRS=^@file{dir}
11858 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11859 Look for source files in directory @file{dir}. There may be zero, one or more
11860 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11861 When a switch @option{^-d^/SOURCE_DIRS^}
11862 is specified, the current working directory will not be searched for source
11863 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11864 or @option{^-D^/DIR_FILES^} switch.
11865 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11866 If @file{dir} is a relative path, it is relative to the directory of
11867 the configuration pragmas file specified with switch
11868 @option{^-c^/CONFIG_FILE^},
11869 or to the directory of the project file specified with switch
11870 @option{^-P^/PROJECT_FILE^} or,
11871 if neither switch @option{^-c^/CONFIG_FILE^}
11872 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11873 current working directory. The directory
11874 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11876 @item ^-D^/DIRS_FILE=^@file{file}
11877 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11878 Look for source files in all directories listed in text file @file{file}.
11879 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11881 @file{file} must be an existing, readable text file.
11882 Each nonempty line in @file{file} must be a directory.
11883 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11884 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11887 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11888 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11889 Foreign patterns. Using this switch, it is possible to add sources of languages
11890 other than Ada to the list of sources of a project file.
11891 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11894 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11897 will look for Ada units in all files with the @file{.ada} extension,
11898 and will add to the list of file for project @file{prj.gpr} the C files
11899 with extension @file{.^c^C^}.
11902 @cindex @option{^-h^/HELP^} (@code{gnatname})
11903 Output usage (help) information. The output is written to @file{stdout}.
11905 @item ^-P^/PROJECT_FILE=^@file{proj}
11906 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11907 Create or update project file @file{proj}. There may be zero, one or more space
11908 between @option{-P} and @file{proj}. @file{proj} may include directory
11909 information. @file{proj} must be writable.
11910 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11911 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11912 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11914 @item ^-v^/VERBOSE^
11915 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11916 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11917 This includes name of the file written, the name of the directories to search
11918 and, for each file in those directories whose name matches at least one of
11919 the Naming Patterns, an indication of whether the file contains a unit,
11920 and if so the name of the unit.
11922 @item ^-v -v^/VERBOSE /VERBOSE^
11923 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11924 Very Verbose mode. In addition to the output produced in verbose mode,
11925 for each file in the searched directories whose name matches none of
11926 the Naming Patterns, an indication is given that there is no match.
11928 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11929 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11930 Excluded patterns. Using this switch, it is possible to exclude some files
11931 that would match the name patterns. For example,
11933 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11936 will look for Ada units in all files with the @file{.ada} extension,
11937 except those whose names end with @file{_nt.ada}.
11941 @node Examples of gnatname Usage
11942 @section Examples of @code{gnatname} Usage
11946 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11952 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11957 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11958 and be writable. In addition, the directory
11959 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11960 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11963 Note the optional spaces after @option{-c} and @option{-d}.
11968 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11969 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11972 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11973 /EXCLUDED_PATTERN=*_nt_body.ada
11974 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11975 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11979 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11980 even in conjunction with one or several switches
11981 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11982 are used in this example.
11984 @c *****************************************
11985 @c * G N A T P r o j e c t M a n a g e r *
11986 @c *****************************************
11988 @c ------ macros for projects.texi
11989 @c These macros are needed when building the gprbuild documentation, but
11990 @c should have no effect in the gnat user's guide
11992 @macro CODESAMPLE{TXT}
12000 @macro PROJECTFILE{TXT}
12004 @c simulates a newline when in a @CODESAMPLE
12015 @macro TIPHTML{TXT}
12019 @macro IMPORTANT{TXT}
12034 @include projects.texi
12036 @c *****************************************
12037 @c * Cross-referencing tools
12038 @c *****************************************
12040 @node The Cross-Referencing Tools gnatxref and gnatfind
12041 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12046 The compiler generates cross-referencing information (unless
12047 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12048 This information indicates where in the source each entity is declared and
12049 referenced. Note that entities in package Standard are not included, but
12050 entities in all other predefined units are included in the output.
12052 Before using any of these two tools, you need to compile successfully your
12053 application, so that GNAT gets a chance to generate the cross-referencing
12056 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12057 information to provide the user with the capability to easily locate the
12058 declaration and references to an entity. These tools are quite similar,
12059 the difference being that @code{gnatfind} is intended for locating
12060 definitions and/or references to a specified entity or entities, whereas
12061 @code{gnatxref} is oriented to generating a full report of all
12064 To use these tools, you must not compile your application using the
12065 @option{-gnatx} switch on the @command{gnatmake} command line
12066 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12067 information will not be generated.
12069 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12070 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12073 * Switches for gnatxref::
12074 * Switches for gnatfind::
12075 * Project Files for gnatxref and gnatfind::
12076 * Regular Expressions in gnatfind and gnatxref::
12077 * Examples of gnatxref Usage::
12078 * Examples of gnatfind Usage::
12081 @node Switches for gnatxref
12082 @section @code{gnatxref} Switches
12085 The command invocation for @code{gnatxref} is:
12087 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12088 @c Expanding @ovar macro inline (explanation in macro def comments)
12089 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12098 identifies the source files for which a report is to be generated. The
12099 ``with''ed units will be processed too. You must provide at least one file.
12101 These file names are considered to be regular expressions, so for instance
12102 specifying @file{source*.adb} is the same as giving every file in the current
12103 directory whose name starts with @file{source} and whose extension is
12106 You shouldn't specify any directory name, just base names. @command{gnatxref}
12107 and @command{gnatfind} will be able to locate these files by themselves using
12108 the source path. If you specify directories, no result is produced.
12113 The switches can be:
12117 @cindex @option{--version} @command{gnatxref}
12118 Display Copyright and version, then exit disregarding all other options.
12121 @cindex @option{--help} @command{gnatxref}
12122 If @option{--version} was not used, display usage, then exit disregarding
12125 @item ^-a^/ALL_FILES^
12126 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12127 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12128 the read-only files found in the library search path. Otherwise, these files
12129 will be ignored. This option can be used to protect Gnat sources or your own
12130 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12131 much faster, and their output much smaller. Read-only here refers to access
12132 or permissions status in the file system for the current user.
12135 @cindex @option{-aIDIR} (@command{gnatxref})
12136 When looking for source files also look in directory DIR. The order in which
12137 source file search is undertaken is the same as for @command{gnatmake}.
12140 @cindex @option{-aODIR} (@command{gnatxref})
12141 When searching for library and object files, look in directory
12142 DIR. The order in which library files are searched is the same as for
12143 @command{gnatmake}.
12146 @cindex @option{-nostdinc} (@command{gnatxref})
12147 Do not look for sources in the system default directory.
12150 @cindex @option{-nostdlib} (@command{gnatxref})
12151 Do not look for library files in the system default directory.
12153 @item --ext=@var{extension}
12154 @cindex @option{--ext} (@command{gnatxref})
12155 Specify an alternate ali file extension. The default is @code{ali} and other
12156 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12157 switch. Note that if this switch overrides the default, which means that only
12158 the new extension will be considered.
12160 @item --RTS=@var{rts-path}
12161 @cindex @option{--RTS} (@command{gnatxref})
12162 Specifies the default location of the runtime library. Same meaning as the
12163 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12165 @item ^-d^/DERIVED_TYPES^
12166 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12167 If this switch is set @code{gnatxref} will output the parent type
12168 reference for each matching derived types.
12170 @item ^-f^/FULL_PATHNAME^
12171 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12172 If this switch is set, the output file names will be preceded by their
12173 directory (if the file was found in the search path). If this switch is
12174 not set, the directory will not be printed.
12176 @item ^-g^/IGNORE_LOCALS^
12177 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12178 If this switch is set, information is output only for library-level
12179 entities, ignoring local entities. The use of this switch may accelerate
12180 @code{gnatfind} and @code{gnatxref}.
12183 @cindex @option{-IDIR} (@command{gnatxref})
12184 Equivalent to @samp{-aODIR -aIDIR}.
12187 @cindex @option{-pFILE} (@command{gnatxref})
12188 Specify a project file to use @xref{GNAT Project Manager}.
12189 If you need to use the @file{.gpr}
12190 project files, you should use gnatxref through the GNAT driver
12191 (@command{gnat xref -Pproject}).
12193 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12194 project file in the current directory.
12196 If a project file is either specified or found by the tools, then the content
12197 of the source directory and object directory lines are added as if they
12198 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12199 and @samp{^-aO^OBJECT_SEARCH^}.
12201 Output only unused symbols. This may be really useful if you give your
12202 main compilation unit on the command line, as @code{gnatxref} will then
12203 display every unused entity and 'with'ed package.
12207 Instead of producing the default output, @code{gnatxref} will generate a
12208 @file{tags} file that can be used by vi. For examples how to use this
12209 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12210 to the standard output, thus you will have to redirect it to a file.
12216 All these switches may be in any order on the command line, and may even
12217 appear after the file names. They need not be separated by spaces, thus
12218 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12219 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12221 @node Switches for gnatfind
12222 @section @code{gnatfind} Switches
12225 The command line for @code{gnatfind} is:
12228 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12229 @c @r{[}@var{file1} @var{file2} @dots{}]
12230 @c Expanding @ovar macro inline (explanation in macro def comments)
12231 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12232 @r{[}@var{file1} @var{file2} @dots{}@r{]}
12240 An entity will be output only if it matches the regular expression found
12241 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12243 Omitting the pattern is equivalent to specifying @samp{*}, which
12244 will match any entity. Note that if you do not provide a pattern, you
12245 have to provide both a sourcefile and a line.
12247 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12248 for matching purposes. At the current time there is no support for
12249 8-bit codes other than Latin-1, or for wide characters in identifiers.
12252 @code{gnatfind} will look for references, bodies or declarations
12253 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12254 and column @var{column}. See @ref{Examples of gnatfind Usage}
12255 for syntax examples.
12258 is a decimal integer identifying the line number containing
12259 the reference to the entity (or entities) to be located.
12262 is a decimal integer identifying the exact location on the
12263 line of the first character of the identifier for the
12264 entity reference. Columns are numbered from 1.
12266 @item file1 file2 @dots{}
12267 The search will be restricted to these source files. If none are given, then
12268 the search will be done for every library file in the search path.
12269 These file must appear only after the pattern or sourcefile.
12271 These file names are considered to be regular expressions, so for instance
12272 specifying @file{source*.adb} is the same as giving every file in the current
12273 directory whose name starts with @file{source} and whose extension is
12276 The location of the spec of the entity will always be displayed, even if it
12277 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
12278 occurrences of the entity in the separate units of the ones given on the
12279 command line will also be displayed.
12281 Note that if you specify at least one file in this part, @code{gnatfind} may
12282 sometimes not be able to find the body of the subprograms.
12287 At least one of 'sourcefile' or 'pattern' has to be present on
12290 The following switches are available:
12294 @cindex @option{--version} @command{gnatfind}
12295 Display Copyright and version, then exit disregarding all other options.
12298 @cindex @option{--help} @command{gnatfind}
12299 If @option{--version} was not used, display usage, then exit disregarding
12302 @item ^-a^/ALL_FILES^
12303 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12304 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12305 the read-only files found in the library search path. Otherwise, these files
12306 will be ignored. This option can be used to protect Gnat sources or your own
12307 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12308 much faster, and their output much smaller. Read-only here refers to access
12309 or permission status in the file system for the current user.
12312 @cindex @option{-aIDIR} (@command{gnatfind})
12313 When looking for source files also look in directory DIR. The order in which
12314 source file search is undertaken is the same as for @command{gnatmake}.
12317 @cindex @option{-aODIR} (@command{gnatfind})
12318 When searching for library and object files, look in directory
12319 DIR. The order in which library files are searched is the same as for
12320 @command{gnatmake}.
12323 @cindex @option{-nostdinc} (@command{gnatfind})
12324 Do not look for sources in the system default directory.
12327 @cindex @option{-nostdlib} (@command{gnatfind})
12328 Do not look for library files in the system default directory.
12330 @item --ext=@var{extension}
12331 @cindex @option{--ext} (@command{gnatfind})
12332 Specify an alternate ali file extension. The default is @code{ali} and other
12333 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12334 switch. Note that if this switch overrides the default, which means that only
12335 the new extension will be considered.
12337 @item --RTS=@var{rts-path}
12338 @cindex @option{--RTS} (@command{gnatfind})
12339 Specifies the default location of the runtime library. Same meaning as the
12340 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12342 @item ^-d^/DERIVED_TYPE_INFORMATION^
12343 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12344 If this switch is set, then @code{gnatfind} will output the parent type
12345 reference for each matching derived types.
12347 @item ^-e^/EXPRESSIONS^
12348 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12349 By default, @code{gnatfind} accept the simple regular expression set for
12350 @samp{pattern}. If this switch is set, then the pattern will be
12351 considered as full Unix-style regular expression.
12353 @item ^-f^/FULL_PATHNAME^
12354 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12355 If this switch is set, the output file names will be preceded by their
12356 directory (if the file was found in the search path). If this switch is
12357 not set, the directory will not be printed.
12359 @item ^-g^/IGNORE_LOCALS^
12360 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12361 If this switch is set, information is output only for library-level
12362 entities, ignoring local entities. The use of this switch may accelerate
12363 @code{gnatfind} and @code{gnatxref}.
12366 @cindex @option{-IDIR} (@command{gnatfind})
12367 Equivalent to @samp{-aODIR -aIDIR}.
12370 @cindex @option{-pFILE} (@command{gnatfind})
12371 Specify a project file (@pxref{GNAT Project Manager}) to use.
12372 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12373 project file in the current directory.
12375 If a project file is either specified or found by the tools, then the content
12376 of the source directory and object directory lines are added as if they
12377 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12378 @samp{^-aO^/OBJECT_SEARCH^}.
12380 @item ^-r^/REFERENCES^
12381 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12382 By default, @code{gnatfind} will output only the information about the
12383 declaration, body or type completion of the entities. If this switch is
12384 set, the @code{gnatfind} will locate every reference to the entities in
12385 the files specified on the command line (or in every file in the search
12386 path if no file is given on the command line).
12388 @item ^-s^/PRINT_LINES^
12389 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12390 If this switch is set, then @code{gnatfind} will output the content
12391 of the Ada source file lines were the entity was found.
12393 @item ^-t^/TYPE_HIERARCHY^
12394 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12395 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12396 the specified type. It act like -d option but recursively from parent
12397 type to parent type. When this switch is set it is not possible to
12398 specify more than one file.
12403 All these switches may be in any order on the command line, and may even
12404 appear after the file names. They need not be separated by spaces, thus
12405 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12406 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12408 As stated previously, gnatfind will search in every directory in the
12409 search path. You can force it to look only in the current directory if
12410 you specify @code{*} at the end of the command line.
12412 @node Project Files for gnatxref and gnatfind
12413 @section Project Files for @command{gnatxref} and @command{gnatfind}
12416 Project files allow a programmer to specify how to compile its
12417 application, where to find sources, etc. These files are used
12419 primarily by GPS, but they can also be used
12422 @code{gnatxref} and @code{gnatfind}.
12424 A project file name must end with @file{.gpr}. If a single one is
12425 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12426 extract the information from it. If multiple project files are found, none of
12427 them is read, and you have to use the @samp{-p} switch to specify the one
12430 The following lines can be included, even though most of them have default
12431 values which can be used in most cases.
12432 The lines can be entered in any order in the file.
12433 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12434 each line. If you have multiple instances, only the last one is taken into
12439 [default: @code{"^./^[]^"}]
12440 specifies a directory where to look for source files. Multiple @code{src_dir}
12441 lines can be specified and they will be searched in the order they
12445 [default: @code{"^./^[]^"}]
12446 specifies a directory where to look for object and library files. Multiple
12447 @code{obj_dir} lines can be specified, and they will be searched in the order
12450 @item comp_opt=SWITCHES
12451 [default: @code{""}]
12452 creates a variable which can be referred to subsequently by using
12453 the @code{$@{comp_opt@}} notation. This is intended to store the default
12454 switches given to @command{gnatmake} and @command{gcc}.
12456 @item bind_opt=SWITCHES
12457 [default: @code{""}]
12458 creates a variable which can be referred to subsequently by using
12459 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12460 switches given to @command{gnatbind}.
12462 @item link_opt=SWITCHES
12463 [default: @code{""}]
12464 creates a variable which can be referred to subsequently by using
12465 the @samp{$@{link_opt@}} notation. This is intended to store the default
12466 switches given to @command{gnatlink}.
12468 @item main=EXECUTABLE
12469 [default: @code{""}]
12470 specifies the name of the executable for the application. This variable can
12471 be referred to in the following lines by using the @samp{$@{main@}} notation.
12474 @item comp_cmd=COMMAND
12475 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12478 @item comp_cmd=COMMAND
12479 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12481 specifies the command used to compile a single file in the application.
12484 @item make_cmd=COMMAND
12485 [default: @code{"GNAT MAKE $@{main@}
12486 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12487 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12488 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12491 @item make_cmd=COMMAND
12492 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12493 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12494 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12496 specifies the command used to recompile the whole application.
12498 @item run_cmd=COMMAND
12499 [default: @code{"$@{main@}"}]
12500 specifies the command used to run the application.
12502 @item debug_cmd=COMMAND
12503 [default: @code{"gdb $@{main@}"}]
12504 specifies the command used to debug the application
12509 @command{gnatxref} and @command{gnatfind} only take into account the
12510 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12512 @node Regular Expressions in gnatfind and gnatxref
12513 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12516 As specified in the section about @command{gnatfind}, the pattern can be a
12517 regular expression. Actually, there are to set of regular expressions
12518 which are recognized by the program:
12521 @item globbing patterns
12522 These are the most usual regular expression. They are the same that you
12523 generally used in a Unix shell command line, or in a DOS session.
12525 Here is a more formal grammar:
12532 term ::= elmt -- matches elmt
12533 term ::= elmt elmt -- concatenation (elmt then elmt)
12534 term ::= * -- any string of 0 or more characters
12535 term ::= ? -- matches any character
12536 term ::= [char @{char@}] -- matches any character listed
12537 term ::= [char - char] -- matches any character in range
12541 @item full regular expression
12542 The second set of regular expressions is much more powerful. This is the
12543 type of regular expressions recognized by utilities such a @file{grep}.
12545 The following is the form of a regular expression, expressed in Ada
12546 reference manual style BNF is as follows
12553 regexp ::= term @{| term@} -- alternation (term or term @dots{})
12555 term ::= item @{item@} -- concatenation (item then item)
12557 item ::= elmt -- match elmt
12558 item ::= elmt * -- zero or more elmt's
12559 item ::= elmt + -- one or more elmt's
12560 item ::= elmt ? -- matches elmt or nothing
12563 elmt ::= nschar -- matches given character
12564 elmt ::= [nschar @{nschar@}] -- matches any character listed
12565 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12566 elmt ::= [char - char] -- matches chars in given range
12567 elmt ::= \ char -- matches given character
12568 elmt ::= . -- matches any single character
12569 elmt ::= ( regexp ) -- parens used for grouping
12571 char ::= any character, including special characters
12572 nschar ::= any character except ()[].*+?^^^
12576 Following are a few examples:
12580 will match any of the two strings @samp{abcde} and @samp{fghi},
12583 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12584 @samp{abcccd}, and so on,
12587 will match any string which has only lowercase characters in it (and at
12588 least one character.
12593 @node Examples of gnatxref Usage
12594 @section Examples of @code{gnatxref} Usage
12596 @subsection General Usage
12599 For the following examples, we will consider the following units:
12601 @smallexample @c ada
12607 3: procedure Foo (B : in Integer);
12614 1: package body Main is
12615 2: procedure Foo (B : in Integer) is
12626 2: procedure Print (B : Integer);
12635 The first thing to do is to recompile your application (for instance, in
12636 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12637 the cross-referencing information.
12638 You can then issue any of the following commands:
12640 @item gnatxref main.adb
12641 @code{gnatxref} generates cross-reference information for main.adb
12642 and every unit 'with'ed by main.adb.
12644 The output would be:
12652 Decl: main.ads 3:20
12653 Body: main.adb 2:20
12654 Ref: main.adb 4:13 5:13 6:19
12657 Ref: main.adb 6:8 7:8
12667 Decl: main.ads 3:15
12668 Body: main.adb 2:15
12671 Body: main.adb 1:14
12674 Ref: main.adb 6:12 7:12
12678 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12679 its body is in main.adb, line 1, column 14 and is not referenced any where.
12681 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12682 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12684 @item gnatxref package1.adb package2.ads
12685 @code{gnatxref} will generates cross-reference information for
12686 package1.adb, package2.ads and any other package 'with'ed by any
12692 @subsection Using gnatxref with vi
12694 @code{gnatxref} can generate a tags file output, which can be used
12695 directly from @command{vi}. Note that the standard version of @command{vi}
12696 will not work properly with overloaded symbols. Consider using another
12697 free implementation of @command{vi}, such as @command{vim}.
12700 $ gnatxref -v gnatfind.adb > tags
12704 will generate the tags file for @code{gnatfind} itself (if the sources
12705 are in the search path!).
12707 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12708 (replacing @var{entity} by whatever you are looking for), and vi will
12709 display a new file with the corresponding declaration of entity.
12712 @node Examples of gnatfind Usage
12713 @section Examples of @code{gnatfind} Usage
12717 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12718 Find declarations for all entities xyz referenced at least once in
12719 main.adb. The references are search in every library file in the search
12722 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12725 The output will look like:
12727 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12728 ^directory/^[directory]^main.adb:24:10: xyz <= body
12729 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12733 that is to say, one of the entities xyz found in main.adb is declared at
12734 line 12 of main.ads (and its body is in main.adb), and another one is
12735 declared at line 45 of foo.ads
12737 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12738 This is the same command as the previous one, instead @code{gnatfind} will
12739 display the content of the Ada source file lines.
12741 The output will look like:
12744 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12746 ^directory/^[directory]^main.adb:24:10: xyz <= body
12748 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12753 This can make it easier to find exactly the location your are looking
12756 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12757 Find references to all entities containing an x that are
12758 referenced on line 123 of main.ads.
12759 The references will be searched only in main.ads and foo.adb.
12761 @item gnatfind main.ads:123
12762 Find declarations and bodies for all entities that are referenced on
12763 line 123 of main.ads.
12765 This is the same as @code{gnatfind "*":main.adb:123}.
12767 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12768 Find the declaration for the entity referenced at column 45 in
12769 line 123 of file main.adb in directory mydir. Note that it
12770 is usual to omit the identifier name when the column is given,
12771 since the column position identifies a unique reference.
12773 The column has to be the beginning of the identifier, and should not
12774 point to any character in the middle of the identifier.
12778 @c *********************************
12779 @node The GNAT Pretty-Printer gnatpp
12780 @chapter The GNAT Pretty-Printer @command{gnatpp}
12782 @cindex Pretty-Printer
12785 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12786 for source reformatting / pretty-printing.
12787 It takes an Ada source file as input and generates a reformatted
12789 You can specify various style directives via switches; e.g.,
12790 identifier case conventions, rules of indentation, and comment layout.
12792 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12793 tree for the input source and thus requires the input to be syntactically and
12794 semantically legal.
12795 If this condition is not met, @command{gnatpp} will terminate with an
12796 error message; no output file will be generated.
12798 If the source files presented to @command{gnatpp} contain
12799 preprocessing directives, then the output file will
12800 correspond to the generated source after all
12801 preprocessing is carried out. There is no way
12802 using @command{gnatpp} to obtain pretty printed files that
12803 include the preprocessing directives.
12805 If the compilation unit
12806 contained in the input source depends semantically upon units located
12807 outside the current directory, you have to provide the source search path
12808 when invoking @command{gnatpp}, if these units are contained in files with
12809 names that do not follow the GNAT file naming rules, you have to provide
12810 the configuration file describing the corresponding naming scheme;
12811 see the description of the @command{gnatpp}
12812 switches below. Another possibility is to use a project file and to
12813 call @command{gnatpp} through the @command{gnat} driver
12815 The @command{gnatpp} command has the form
12818 @c $ gnatpp @ovar{switches} @var{filename}
12819 @c Expanding @ovar macro inline (explanation in macro def comments)
12820 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12827 @var{switches} is an optional sequence of switches defining such properties as
12828 the formatting rules, the source search path, and the destination for the
12832 @var{filename} is the name (including the extension) of the source file to
12833 reformat; ``wildcards'' or several file names on the same gnatpp command are
12834 allowed. The file name may contain path information; it does not have to
12835 follow the GNAT file naming rules
12838 @samp{@var{gcc_switches}} is a list of switches for
12839 @command{gcc}. They will be passed on to all compiler invocations made by
12840 @command{gnatelim} to generate the ASIS trees. Here you can provide
12841 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12842 use the @option{-gnatec} switch to set the configuration file,
12843 use the @option{-gnat05} switch if sources should be compiled in
12848 * Switches for gnatpp::
12849 * Formatting Rules::
12852 @node Switches for gnatpp
12853 @section Switches for @command{gnatpp}
12856 The following subsections describe the various switches accepted by
12857 @command{gnatpp}, organized by category.
12860 You specify a switch by supplying a name and generally also a value.
12861 In many cases the values for a switch with a given name are incompatible with
12863 (for example the switch that controls the casing of a reserved word may have
12864 exactly one value: upper case, lower case, or
12865 mixed case) and thus exactly one such switch can be in effect for an
12866 invocation of @command{gnatpp}.
12867 If more than one is supplied, the last one is used.
12868 However, some values for the same switch are mutually compatible.
12869 You may supply several such switches to @command{gnatpp}, but then
12870 each must be specified in full, with both the name and the value.
12871 Abbreviated forms (the name appearing once, followed by each value) are
12873 For example, to set
12874 the alignment of the assignment delimiter both in declarations and in
12875 assignment statements, you must write @option{-A2A3}
12876 (or @option{-A2 -A3}), but not @option{-A23}.
12880 In many cases the set of options for a given qualifier are incompatible with
12881 each other (for example the qualifier that controls the casing of a reserved
12882 word may have exactly one option, which specifies either upper case, lower
12883 case, or mixed case), and thus exactly one such option can be in effect for
12884 an invocation of @command{gnatpp}.
12885 If more than one is supplied, the last one is used.
12886 However, some qualifiers have options that are mutually compatible,
12887 and then you may then supply several such options when invoking
12891 In most cases, it is obvious whether or not the
12892 ^values for a switch with a given name^options for a given qualifier^
12893 are compatible with each other.
12894 When the semantics might not be evident, the summaries below explicitly
12895 indicate the effect.
12898 * Alignment Control::
12900 * Construct Layout Control::
12901 * General Text Layout Control::
12902 * Other Formatting Options::
12903 * Setting the Source Search Path::
12904 * Output File Control::
12905 * Other gnatpp Switches::
12908 @node Alignment Control
12909 @subsection Alignment Control
12910 @cindex Alignment control in @command{gnatpp}
12913 Programs can be easier to read if certain constructs are vertically aligned.
12914 By default all alignments are set ON.
12915 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12916 OFF, and then use one or more of the other
12917 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12918 to activate alignment for specific constructs.
12921 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12925 Set all alignments to ON
12928 @item ^-A0^/ALIGN=OFF^
12929 Set all alignments to OFF
12931 @item ^-A1^/ALIGN=COLONS^
12932 Align @code{:} in declarations
12934 @item ^-A2^/ALIGN=DECLARATIONS^
12935 Align @code{:=} in initializations in declarations
12937 @item ^-A3^/ALIGN=STATEMENTS^
12938 Align @code{:=} in assignment statements
12940 @item ^-A4^/ALIGN=ARROWS^
12941 Align @code{=>} in associations
12943 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12944 Align @code{at} keywords in the component clauses in record
12945 representation clauses
12949 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12952 @node Casing Control
12953 @subsection Casing Control
12954 @cindex Casing control in @command{gnatpp}
12957 @command{gnatpp} allows you to specify the casing for reserved words,
12958 pragma names, attribute designators and identifiers.
12959 For identifiers you may define a
12960 general rule for name casing but also override this rule
12961 via a set of dictionary files.
12963 Three types of casing are supported: lower case, upper case, and mixed case.
12964 Lower and upper case are self-explanatory (but since some letters in
12965 Latin1 and other GNAT-supported character sets
12966 exist only in lower-case form, an upper case conversion will have no
12968 ``Mixed case'' means that the first letter, and also each letter immediately
12969 following an underscore, are converted to their uppercase forms;
12970 all the other letters are converted to their lowercase forms.
12973 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12974 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12975 Attribute designators are lower case
12977 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12978 Attribute designators are upper case
12980 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12981 Attribute designators are mixed case (this is the default)
12983 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12984 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12985 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12986 lower case (this is the default)
12988 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12989 Keywords are upper case
12991 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12992 @item ^-nD^/NAME_CASING=AS_DECLARED^
12993 Name casing for defining occurrences are as they appear in the source file
12994 (this is the default)
12996 @item ^-nU^/NAME_CASING=UPPER_CASE^
12997 Names are in upper case
12999 @item ^-nL^/NAME_CASING=LOWER_CASE^
13000 Names are in lower case
13002 @item ^-nM^/NAME_CASING=MIXED_CASE^
13003 Names are in mixed case
13005 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13006 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13007 Pragma names are lower case
13009 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13010 Pragma names are upper case
13012 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13013 Pragma names are mixed case (this is the default)
13015 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13016 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13017 Use @var{file} as a @emph{dictionary file} that defines
13018 the casing for a set of specified names,
13019 thereby overriding the effect on these names by
13020 any explicit or implicit
13021 ^-n^/NAME_CASING^ switch.
13022 To supply more than one dictionary file,
13023 use ^several @option{-D} switches^a list of files as options^.
13026 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13027 to define the casing for the Ada predefined names and
13028 the names declared in the GNAT libraries.
13030 @item ^-D-^/SPECIFIC_CASING^
13031 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13032 Do not use the default dictionary file;
13033 instead, use the casing
13034 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13039 The structure of a dictionary file, and details on the conventions
13040 used in the default dictionary file, are defined in @ref{Name Casing}.
13042 The @option{^-D-^/SPECIFIC_CASING^} and
13043 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13046 @node Construct Layout Control
13047 @subsection Construct Layout Control
13048 @cindex Layout control in @command{gnatpp}
13051 This group of @command{gnatpp} switches controls the layout of comments and
13052 complex syntactic constructs. See @ref{Formatting Comments} for details
13056 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13057 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13058 All the comments remain unchanged
13060 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13061 GNAT-style comment line indentation (this is the default).
13063 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13064 Reference-manual comment line indentation.
13066 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13067 GNAT-style comment beginning
13069 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13070 Reformat comment blocks
13072 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13073 Keep unchanged special form comments
13075 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13076 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13077 GNAT-style layout (this is the default)
13079 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13082 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13085 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13087 All the VT characters are removed from the comment text. All the HT characters
13088 are expanded with the sequences of space characters to get to the next tab
13091 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13092 @item ^--no-separate-is^/NO_SEPARATE_IS^
13093 Do not place the keyword @code{is} on a separate line in a subprogram body in
13094 case if the spec occupies more then one line.
13096 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13097 @item ^--separate-label^/SEPARATE_LABEL^
13098 Place statement label(s) on a separate line, with the following statement
13101 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13102 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13103 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13104 keyword @code{then} in IF statements on a separate line.
13106 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13107 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13108 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13109 keyword @code{then} in IF statements on a separate line. This option is
13110 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13112 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13113 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13114 Start each USE clause in a context clause from a separate line.
13116 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13117 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13118 Use a separate line for a loop or block statement name, but do not use an extra
13119 indentation level for the statement itself.
13125 The @option{-c1} and @option{-c2} switches are incompatible.
13126 The @option{-c3} and @option{-c4} switches are compatible with each other and
13127 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13128 the other comment formatting switches.
13130 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13135 For the @option{/COMMENTS_LAYOUT} qualifier:
13138 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13140 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13141 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13145 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13146 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13149 @node General Text Layout Control
13150 @subsection General Text Layout Control
13153 These switches allow control over line length and indentation.
13156 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13157 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13158 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13160 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13161 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13162 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13164 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13165 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13166 Indentation level for continuation lines (relative to the line being
13167 continued), @var{nnn} from 1@dots{}9.
13169 value is one less then the (normal) indentation level, unless the
13170 indentation is set to 1 (in which case the default value for continuation
13171 line indentation is also 1)
13174 @node Other Formatting Options
13175 @subsection Other Formatting Options
13178 These switches control the inclusion of missing end/exit labels, and
13179 the indentation level in @b{case} statements.
13182 @item ^-e^/NO_MISSED_LABELS^
13183 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13184 Do not insert missing end/exit labels. An end label is the name of
13185 a construct that may optionally be repeated at the end of the
13186 construct's declaration;
13187 e.g., the names of packages, subprograms, and tasks.
13188 An exit label is the name of a loop that may appear as target
13189 of an exit statement within the loop.
13190 By default, @command{gnatpp} inserts these end/exit labels when
13191 they are absent from the original source. This option suppresses such
13192 insertion, so that the formatted source reflects the original.
13194 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13195 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13196 Insert a Form Feed character after a pragma Page.
13198 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13199 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13200 Do not use an additional indentation level for @b{case} alternatives
13201 and variants if there are @var{nnn} or more (the default
13203 If @var{nnn} is 0, an additional indentation level is
13204 used for @b{case} alternatives and variants regardless of their number.
13207 @node Setting the Source Search Path
13208 @subsection Setting the Source Search Path
13211 To define the search path for the input source file, @command{gnatpp}
13212 uses the same switches as the GNAT compiler, with the same effects.
13215 @item ^-I^/SEARCH=^@var{dir}
13216 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13217 The same as the corresponding gcc switch
13219 @item ^-I-^/NOCURRENT_DIRECTORY^
13220 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13221 The same as the corresponding gcc switch
13223 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13224 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13225 The same as the corresponding gcc switch
13227 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13228 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13229 The same as the corresponding gcc switch
13233 @node Output File Control
13234 @subsection Output File Control
13237 By default the output is sent to the file whose name is obtained by appending
13238 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13239 (if the file with this name already exists, it is unconditionally overwritten).
13240 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13241 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13243 The output may be redirected by the following switches:
13246 @item ^-pipe^/STANDARD_OUTPUT^
13247 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13248 Send the output to @code{Standard_Output}
13250 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13251 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13252 Write the output into @var{output_file}.
13253 If @var{output_file} already exists, @command{gnatpp} terminates without
13254 reading or processing the input file.
13256 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13257 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13258 Write the output into @var{output_file}, overwriting the existing file
13259 (if one is present).
13261 @item ^-r^/REPLACE^
13262 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13263 Replace the input source file with the reformatted output, and copy the
13264 original input source into the file whose name is obtained by appending the
13265 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13266 If a file with this name already exists, @command{gnatpp} terminates without
13267 reading or processing the input file.
13269 @item ^-rf^/OVERRIDING_REPLACE^
13270 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13271 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13272 already exists, it is overwritten.
13274 @item ^-rnb^/REPLACE_NO_BACKUP^
13275 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13276 Replace the input source file with the reformatted output without
13277 creating any backup copy of the input source.
13279 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13280 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13281 Specifies the format of the reformatted output file. The @var{xxx}
13282 ^string specified with the switch^option^ may be either
13284 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13285 @item ``@option{^crlf^CRLF^}''
13286 the same as @option{^crlf^CRLF^}
13287 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13288 @item ``@option{^lf^LF^}''
13289 the same as @option{^unix^UNIX^}
13292 @item ^-W^/RESULT_ENCODING=^@var{e}
13293 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13294 Specify the wide character encoding method used to write the code in the
13296 @var{e} is one of the following:
13304 Upper half encoding
13306 @item ^s^SHIFT_JIS^
13316 Brackets encoding (default value)
13322 Options @option{^-pipe^/STANDARD_OUTPUT^},
13323 @option{^-o^/OUTPUT^} and
13324 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13325 contains only one file to reformat.
13327 @option{^--eol^/END_OF_LINE^}
13329 @option{^-W^/RESULT_ENCODING^}
13330 cannot be used together
13331 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13333 @node Other gnatpp Switches
13334 @subsection Other @code{gnatpp} Switches
13337 The additional @command{gnatpp} switches are defined in this subsection.
13340 @item ^-files @var{filename}^/FILES=@var{filename}^
13341 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13342 Take the argument source files from the specified file. This file should be an
13343 ordinary text file containing file names separated by spaces or
13344 line breaks. You can use this switch more than once in the same call to
13345 @command{gnatpp}. You also can combine this switch with an explicit list of
13348 @item ^-v^/VERBOSE^
13349 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13351 @command{gnatpp} generates version information and then
13352 a trace of the actions it takes to produce or obtain the ASIS tree.
13354 @item ^-w^/WARNINGS^
13355 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13357 @command{gnatpp} generates a warning whenever it cannot provide
13358 a required layout in the result source.
13361 @node Formatting Rules
13362 @section Formatting Rules
13365 The following subsections show how @command{gnatpp} treats ``white space'',
13366 comments, program layout, and name casing.
13367 They provide the detailed descriptions of the switches shown above.
13370 * White Space and Empty Lines::
13371 * Formatting Comments::
13372 * Construct Layout::
13376 @node White Space and Empty Lines
13377 @subsection White Space and Empty Lines
13380 @command{gnatpp} does not have an option to control space characters.
13381 It will add or remove spaces according to the style illustrated by the
13382 examples in the @cite{Ada Reference Manual}.
13384 The only format effectors
13385 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13386 that will appear in the output file are platform-specific line breaks,
13387 and also format effectors within (but not at the end of) comments.
13388 In particular, each horizontal tab character that is not inside
13389 a comment will be treated as a space and thus will appear in the
13390 output file as zero or more spaces depending on
13391 the reformatting of the line in which it appears.
13392 The only exception is a Form Feed character, which is inserted after a
13393 pragma @code{Page} when @option{-ff} is set.
13395 The output file will contain no lines with trailing ``white space'' (spaces,
13398 Empty lines in the original source are preserved
13399 only if they separate declarations or statements.
13400 In such contexts, a
13401 sequence of two or more empty lines is replaced by exactly one empty line.
13402 Note that a blank line will be removed if it separates two ``comment blocks''
13403 (a comment block is a sequence of whole-line comments).
13404 In order to preserve a visual separation between comment blocks, use an
13405 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13406 Likewise, if for some reason you wish to have a sequence of empty lines,
13407 use a sequence of empty comments instead.
13409 @node Formatting Comments
13410 @subsection Formatting Comments
13413 Comments in Ada code are of two kinds:
13416 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13417 ``white space'') on a line
13420 an @emph{end-of-line comment}, which follows some other Ada lexical element
13425 The indentation of a whole-line comment is that of either
13426 the preceding or following line in
13427 the formatted source, depending on switch settings as will be described below.
13429 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13430 between the end of the preceding Ada lexical element and the beginning
13431 of the comment as appear in the original source,
13432 unless either the comment has to be split to
13433 satisfy the line length limitation, or else the next line contains a
13434 whole line comment that is considered a continuation of this end-of-line
13435 comment (because it starts at the same position).
13437 cases, the start of the end-of-line comment is moved right to the nearest
13438 multiple of the indentation level.
13439 This may result in a ``line overflow'' (the right-shifted comment extending
13440 beyond the maximum line length), in which case the comment is split as
13443 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13444 (GNAT-style comment line indentation)
13445 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13446 (reference-manual comment line indentation).
13447 With reference-manual style, a whole-line comment is indented as if it
13448 were a declaration or statement at the same place
13449 (i.e., according to the indentation of the preceding line(s)).
13450 With GNAT style, a whole-line comment that is immediately followed by an
13451 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13452 word @b{begin}, is indented based on the construct that follows it.
13455 @smallexample @c ada
13467 Reference-manual indentation produces:
13469 @smallexample @c ada
13481 while GNAT-style indentation produces:
13483 @smallexample @c ada
13495 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13496 (GNAT style comment beginning) has the following
13501 For each whole-line comment that does not end with two hyphens,
13502 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13503 to ensure that there are at least two spaces between these hyphens and the
13504 first non-blank character of the comment.
13508 For an end-of-line comment, if in the original source the next line is a
13509 whole-line comment that starts at the same position
13510 as the end-of-line comment,
13511 then the whole-line comment (and all whole-line comments
13512 that follow it and that start at the same position)
13513 will start at this position in the output file.
13516 That is, if in the original source we have:
13518 @smallexample @c ada
13521 A := B + C; -- B must be in the range Low1..High1
13522 -- C must be in the range Low2..High2
13523 --B+C will be in the range Low1+Low2..High1+High2
13529 Then in the formatted source we get
13531 @smallexample @c ada
13534 A := B + C; -- B must be in the range Low1..High1
13535 -- C must be in the range Low2..High2
13536 -- B+C will be in the range Low1+Low2..High1+High2
13542 A comment that exceeds the line length limit will be split.
13544 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13545 the line belongs to a reformattable block, splitting the line generates a
13546 @command{gnatpp} warning.
13547 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13548 comments may be reformatted in typical
13549 word processor style (that is, moving words between lines and putting as
13550 many words in a line as possible).
13553 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13554 that has a special format (that is, a character that is neither a letter nor digit
13555 not white space nor line break immediately following the leading @code{--} of
13556 the comment) should be without any change moved from the argument source
13557 into reformatted source. This switch allows to preserve comments that are used
13558 as a special marks in the code (e.g.@: SPARK annotation).
13560 @node Construct Layout
13561 @subsection Construct Layout
13564 In several cases the suggested layout in the Ada Reference Manual includes
13565 an extra level of indentation that many programmers prefer to avoid. The
13566 affected cases include:
13570 @item Record type declaration (RM 3.8)
13572 @item Record representation clause (RM 13.5.1)
13574 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13576 @item Block statement in case if a block has a statement identifier (RM 5.6)
13580 In compact mode (when GNAT style layout or compact layout is set),
13581 the pretty printer uses one level of indentation instead
13582 of two. This is achieved in the record definition and record representation
13583 clause cases by putting the @code{record} keyword on the same line as the
13584 start of the declaration or representation clause, and in the block and loop
13585 case by putting the block or loop header on the same line as the statement
13589 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13590 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13591 layout on the one hand, and uncompact layout
13592 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13593 can be illustrated by the following examples:
13597 @multitable @columnfractions .5 .5
13598 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13601 @smallexample @c ada
13608 @smallexample @c ada
13617 @smallexample @c ada
13619 a at 0 range 0 .. 31;
13620 b at 4 range 0 .. 31;
13624 @smallexample @c ada
13627 a at 0 range 0 .. 31;
13628 b at 4 range 0 .. 31;
13633 @smallexample @c ada
13641 @smallexample @c ada
13651 @smallexample @c ada
13652 Clear : for J in 1 .. 10 loop
13657 @smallexample @c ada
13659 for J in 1 .. 10 loop
13670 GNAT style, compact layout Uncompact layout
13672 type q is record type q is
13673 a : integer; record
13674 b : integer; a : integer;
13675 end record; b : integer;
13678 for q use record for q use
13679 a at 0 range 0 .. 31; record
13680 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
13681 end record; b at 4 range 0 .. 31;
13684 Block : declare Block :
13685 A : Integer := 3; declare
13686 begin A : Integer := 3;
13688 end Block; Proc (A, A);
13691 Clear : for J in 1 .. 10 loop Clear :
13692 A (J) := 0; for J in 1 .. 10 loop
13693 end loop Clear; A (J) := 0;
13700 A further difference between GNAT style layout and compact layout is that
13701 GNAT style layout inserts empty lines as separation for
13702 compound statements, return statements and bodies.
13704 Note that the layout specified by
13705 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13706 for named block and loop statements overrides the layout defined by these
13707 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13708 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13709 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13712 @subsection Name Casing
13715 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13716 the same casing as the corresponding defining identifier.
13718 You control the casing for defining occurrences via the
13719 @option{^-n^/NAME_CASING^} switch.
13721 With @option{-nD} (``as declared'', which is the default),
13724 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13726 defining occurrences appear exactly as in the source file
13727 where they are declared.
13728 The other ^values for this switch^options for this qualifier^ ---
13729 @option{^-nU^UPPER_CASE^},
13730 @option{^-nL^LOWER_CASE^},
13731 @option{^-nM^MIXED_CASE^} ---
13733 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13734 If @command{gnatpp} changes the casing of a defining
13735 occurrence, it analogously changes the casing of all the
13736 usage occurrences of this name.
13738 If the defining occurrence of a name is not in the source compilation unit
13739 currently being processed by @command{gnatpp}, the casing of each reference to
13740 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13741 switch (subject to the dictionary file mechanism described below).
13742 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13744 casing for the defining occurrence of the name.
13746 Some names may need to be spelled with casing conventions that are not
13747 covered by the upper-, lower-, and mixed-case transformations.
13748 You can arrange correct casing by placing such names in a
13749 @emph{dictionary file},
13750 and then supplying a @option{^-D^/DICTIONARY^} switch.
13751 The casing of names from dictionary files overrides
13752 any @option{^-n^/NAME_CASING^} switch.
13754 To handle the casing of Ada predefined names and the names from GNAT libraries,
13755 @command{gnatpp} assumes a default dictionary file.
13756 The name of each predefined entity is spelled with the same casing as is used
13757 for the entity in the @cite{Ada Reference Manual}.
13758 The name of each entity in the GNAT libraries is spelled with the same casing
13759 as is used in the declaration of that entity.
13761 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13762 default dictionary file.
13763 Instead, the casing for predefined and GNAT-defined names will be established
13764 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13765 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13766 will appear as just shown,
13767 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13768 To ensure that even such names are rendered in uppercase,
13769 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13770 (or else, less conveniently, place these names in upper case in a dictionary
13773 A dictionary file is
13774 a plain text file; each line in this file can be either a blank line
13775 (containing only space characters and ASCII.HT characters), an Ada comment
13776 line, or the specification of exactly one @emph{casing schema}.
13778 A casing schema is a string that has the following syntax:
13782 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13784 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13789 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13790 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13792 The casing schema string can be followed by white space and/or an Ada-style
13793 comment; any amount of white space is allowed before the string.
13795 If a dictionary file is passed as
13797 the value of a @option{-D@var{file}} switch
13800 an option to the @option{/DICTIONARY} qualifier
13803 simple name and every identifier, @command{gnatpp} checks if the dictionary
13804 defines the casing for the name or for some of its parts (the term ``subword''
13805 is used below to denote the part of a name which is delimited by ``_'' or by
13806 the beginning or end of the word and which does not contain any ``_'' inside):
13810 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13811 the casing defined by the dictionary; no subwords are checked for this word
13814 for every subword @command{gnatpp} checks if the dictionary contains the
13815 corresponding string of the form @code{*@var{simple_identifier}*},
13816 and if it does, the casing of this @var{simple_identifier} is used
13820 if the whole name does not contain any ``_'' inside, and if for this name
13821 the dictionary contains two entries - one of the form @var{identifier},
13822 and another - of the form *@var{simple_identifier}*, then the first one
13823 is applied to define the casing of this name
13826 if more than one dictionary file is passed as @command{gnatpp} switches, each
13827 dictionary adds new casing exceptions and overrides all the existing casing
13828 exceptions set by the previous dictionaries
13831 when @command{gnatpp} checks if the word or subword is in the dictionary,
13832 this check is not case sensitive
13836 For example, suppose we have the following source to reformat:
13838 @smallexample @c ada
13841 name1 : integer := 1;
13842 name4_name3_name2 : integer := 2;
13843 name2_name3_name4 : Boolean;
13846 name2_name3_name4 := name4_name3_name2 > name1;
13852 And suppose we have two dictionaries:
13869 If @command{gnatpp} is called with the following switches:
13873 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13876 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13881 then we will get the following name casing in the @command{gnatpp} output:
13883 @smallexample @c ada
13886 NAME1 : Integer := 1;
13887 Name4_NAME3_Name2 : Integer := 2;
13888 Name2_NAME3_Name4 : Boolean;
13891 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13896 @c *********************************
13897 @node The GNAT Metric Tool gnatmetric
13898 @chapter The GNAT Metric Tool @command{gnatmetric}
13900 @cindex Metric tool
13903 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13904 for computing various program metrics.
13905 It takes an Ada source file as input and generates a file containing the
13906 metrics data as output. Various switches control which
13907 metrics are computed and output.
13909 @command{gnatmetric} generates and uses the ASIS
13910 tree for the input source and thus requires the input to be syntactically and
13911 semantically legal.
13912 If this condition is not met, @command{gnatmetric} will generate
13913 an error message; no metric information for this file will be
13914 computed and reported.
13916 If the compilation unit contained in the input source depends semantically
13917 upon units in files located outside the current directory, you have to provide
13918 the source search path when invoking @command{gnatmetric}.
13919 If it depends semantically upon units that are contained
13920 in files with names that do not follow the GNAT file naming rules, you have to
13921 provide the configuration file describing the corresponding naming scheme (see
13922 the description of the @command{gnatmetric} switches below.)
13923 Alternatively, you may use a project file and invoke @command{gnatmetric}
13924 through the @command{gnat} driver.
13926 The @command{gnatmetric} command has the form
13929 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13930 @c Expanding @ovar macro inline (explanation in macro def comments)
13931 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13938 @var{switches} specify the metrics to compute and define the destination for
13942 Each @var{filename} is the name (including the extension) of a source
13943 file to process. ``Wildcards'' are allowed, and
13944 the file name may contain path information.
13945 If no @var{filename} is supplied, then the @var{switches} list must contain
13947 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13948 Including both a @option{-files} switch and one or more
13949 @var{filename} arguments is permitted.
13952 @samp{@var{gcc_switches}} is a list of switches for
13953 @command{gcc}. They will be passed on to all compiler invocations made by
13954 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13955 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13956 and use the @option{-gnatec} switch to set the configuration file,
13957 use the @option{-gnat05} switch if sources should be compiled in
13962 * Switches for gnatmetric::
13965 @node Switches for gnatmetric
13966 @section Switches for @command{gnatmetric}
13969 The following subsections describe the various switches accepted by
13970 @command{gnatmetric}, organized by category.
13973 * Output Files Control::
13974 * Disable Metrics For Local Units::
13975 * Specifying a set of metrics to compute::
13976 * Other gnatmetric Switches::
13977 * Generate project-wide metrics::
13980 @node Output Files Control
13981 @subsection Output File Control
13982 @cindex Output file control in @command{gnatmetric}
13985 @command{gnatmetric} has two output formats. It can generate a
13986 textual (human-readable) form, and also XML. By default only textual
13987 output is generated.
13989 When generating the output in textual form, @command{gnatmetric} creates
13990 for each Ada source file a corresponding text file
13991 containing the computed metrics, except for the case when the set of metrics
13992 specified by gnatmetric parameters consists only of metrics that are computed
13993 for the whole set of analyzed sources, but not for each Ada source.
13994 By default, this file is placed in the same directory as where the source
13995 file is located, and its name is obtained
13996 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13999 All the output information generated in XML format is placed in a single
14000 file. By default this file is placed in the current directory and has the
14001 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14003 Some of the computed metrics are summed over the units passed to
14004 @command{gnatmetric}; for example, the total number of lines of code.
14005 By default this information is sent to @file{stdout}, but a file
14006 can be specified with the @option{-og} switch.
14008 The following switches control the @command{gnatmetric} output:
14011 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14013 Generate the XML output
14015 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14017 Generate the XML output and the XML schema file that describes the structure
14018 of the XML metric report, this schema is assigned to the XML file. The schema
14019 file has the same name as the XML output file with @file{.xml} suffix replaced
14022 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14023 @item ^-nt^/NO_TEXT^
14024 Do not generate the output in text form (implies @option{^-x^/XML^})
14026 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14027 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14028 Put text files with detailed metrics into @var{output_dir}
14030 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14031 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14032 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14033 in the name of the output file.
14035 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14036 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14037 Put global metrics into @var{file_name}
14039 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14040 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14041 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14043 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14044 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14045 Use ``short'' source file names in the output. (The @command{gnatmetric}
14046 output includes the name(s) of the Ada source file(s) from which the metrics
14047 are computed. By default each name includes the absolute path. The
14048 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14049 to exclude all directory information from the file names that are output.)
14053 @node Disable Metrics For Local Units
14054 @subsection Disable Metrics For Local Units
14055 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14058 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14060 unit per one source file. It computes line metrics for the whole source
14061 file, and it also computes syntax
14062 and complexity metrics for the file's outermost unit.
14064 By default, @command{gnatmetric} will also compute all metrics for certain
14065 kinds of locally declared program units:
14069 subprogram (and generic subprogram) bodies;
14072 package (and generic package) specs and bodies;
14075 task object and type specifications and bodies;
14078 protected object and type specifications and bodies.
14082 These kinds of entities will be referred to as
14083 @emph{eligible local program units}, or simply @emph{eligible local units},
14084 @cindex Eligible local unit (for @command{gnatmetric})
14085 in the discussion below.
14087 Note that a subprogram declaration, generic instantiation,
14088 or renaming declaration only receives metrics
14089 computation when it appear as the outermost entity
14092 Suppression of metrics computation for eligible local units can be
14093 obtained via the following switch:
14096 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14097 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14098 Do not compute detailed metrics for eligible local program units
14102 @node Specifying a set of metrics to compute
14103 @subsection Specifying a set of metrics to compute
14106 By default all the metrics are computed and reported. The switches
14107 described in this subsection allow you to control, on an individual
14108 basis, whether metrics are computed and
14109 reported. If at least one positive metric
14110 switch is specified (that is, a switch that defines that a given
14111 metric or set of metrics is to be computed), then only
14112 explicitly specified metrics are reported.
14115 * Line Metrics Control::
14116 * Syntax Metrics Control::
14117 * Complexity Metrics Control::
14118 * Coupling Metrics Control::
14121 @node Line Metrics Control
14122 @subsubsection Line Metrics Control
14123 @cindex Line metrics control in @command{gnatmetric}
14126 For any (legal) source file, and for each of its
14127 eligible local program units, @command{gnatmetric} computes the following
14132 the total number of lines;
14135 the total number of code lines (i.e., non-blank lines that are not comments)
14138 the number of comment lines
14141 the number of code lines containing end-of-line comments;
14144 the comment percentage: the ratio between the number of lines that contain
14145 comments and the number of all non-blank lines, expressed as a percentage;
14148 the number of empty lines and lines containing only space characters and/or
14149 format effectors (blank lines)
14152 the average number of code lines in subprogram bodies, task bodies, entry
14153 bodies and statement sequences in package bodies (this metric is only computed
14154 across the whole set of the analyzed units)
14159 @command{gnatmetric} sums the values of the line metrics for all the
14160 files being processed and then generates the cumulative results. The tool
14161 also computes for all the files being processed the average number of code
14164 You can use the following switches to select the specific line metrics
14165 to be computed and reported.
14168 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14171 @cindex @option{--no-lines@var{x}}
14174 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14175 Report all the line metrics
14177 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14178 Do not report any of line metrics
14180 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14181 Report the number of all lines
14183 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14184 Do not report the number of all lines
14186 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14187 Report the number of code lines
14189 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14190 Do not report the number of code lines
14192 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14193 Report the number of comment lines
14195 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14196 Do not report the number of comment lines
14198 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14199 Report the number of code lines containing
14200 end-of-line comments
14202 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14203 Do not report the number of code lines containing
14204 end-of-line comments
14206 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14207 Report the comment percentage in the program text
14209 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14210 Do not report the comment percentage in the program text
14212 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14213 Report the number of blank lines
14215 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14216 Do not report the number of blank lines
14218 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14219 Report the average number of code lines in subprogram bodies, task bodies,
14220 entry bodies and statement sequences in package bodies. The metric is computed
14221 and reported for the whole set of processed Ada sources only.
14223 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14224 Do not report the average number of code lines in subprogram bodies,
14225 task bodies, entry bodies and statement sequences in package bodies.
14229 @node Syntax Metrics Control
14230 @subsubsection Syntax Metrics Control
14231 @cindex Syntax metrics control in @command{gnatmetric}
14234 @command{gnatmetric} computes various syntactic metrics for the
14235 outermost unit and for each eligible local unit:
14238 @item LSLOC (``Logical Source Lines Of Code'')
14239 The total number of declarations and the total number of statements. Note
14240 that the definition of declarations is the one given in the reference
14244 ``Each of the following is defined to be a declaration: any basic_declaration;
14245 an enumeration_literal_specification; a discriminant_specification;
14246 a component_declaration; a loop_parameter_specification; a
14247 parameter_specification; a subprogram_body; an entry_declaration;
14248 an entry_index_specification; a choice_parameter_specification;
14249 a generic_formal_parameter_declaration.''
14251 This means for example that each enumeration literal adds one to the count,
14252 as well as each subprogram parameter.
14254 Thus the results from this metric will be significantly greater than might
14255 be expected from a naive view of counting semicolons.
14257 @item Maximal static nesting level of inner program units
14259 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14260 package, a task unit, a protected unit, a
14261 protected entry, a generic unit, or an explicitly declared subprogram other
14262 than an enumeration literal.''
14264 @item Maximal nesting level of composite syntactic constructs
14265 This corresponds to the notion of the
14266 maximum nesting level in the GNAT built-in style checks
14267 (@pxref{Style Checking})
14271 For the outermost unit in the file, @command{gnatmetric} additionally computes
14272 the following metrics:
14275 @item Public subprograms
14276 This metric is computed for package specs. It is the
14277 number of subprograms and generic subprograms declared in the visible
14278 part (including the visible part of nested packages, protected objects, and
14281 @item All subprograms
14282 This metric is computed for bodies and subunits. The
14283 metric is equal to a total number of subprogram bodies in the compilation
14285 Neither generic instantiations nor renamings-as-a-body nor body stubs
14286 are counted. Any subprogram body is counted, independently of its nesting
14287 level and enclosing constructs. Generic bodies and bodies of protected
14288 subprograms are counted in the same way as ``usual'' subprogram bodies.
14291 This metric is computed for package specs and
14292 generic package declarations. It is the total number of types
14293 that can be referenced from outside this compilation unit, plus the
14294 number of types from all the visible parts of all the visible generic
14295 packages. Generic formal types are not counted. Only types, not subtypes,
14299 Along with the total number of public types, the following
14300 types are counted and reported separately:
14307 Root tagged types (abstract, non-abstract, private, non-private). Type
14308 extensions are @emph{not} counted
14311 Private types (including private extensions)
14322 This metric is computed for any compilation unit. It is equal to the total
14323 number of the declarations of different types given in the compilation unit.
14324 The private and the corresponding full type declaration are counted as one
14325 type declaration. Incomplete type declarations and generic formal types
14327 No distinction is made among different kinds of types (abstract,
14328 private etc.); the total number of types is computed and reported.
14333 By default, all the syntax metrics are computed and reported. You can use the
14334 following switches to select specific syntax metrics.
14338 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14341 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14344 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14345 Report all the syntax metrics
14347 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14348 Do not report any of syntax metrics
14350 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14351 Report the total number of declarations
14353 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14354 Do not report the total number of declarations
14356 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14357 Report the total number of statements
14359 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14360 Do not report the total number of statements
14362 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14363 Report the number of public subprograms in a compilation unit
14365 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14366 Do not report the number of public subprograms in a compilation unit
14368 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14369 Report the number of all the subprograms in a compilation unit
14371 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14372 Do not report the number of all the subprograms in a compilation unit
14374 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14375 Report the number of public types in a compilation unit
14377 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14378 Do not report the number of public types in a compilation unit
14380 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14381 Report the number of all the types in a compilation unit
14383 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14384 Do not report the number of all the types in a compilation unit
14386 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14387 Report the maximal program unit nesting level
14389 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14390 Do not report the maximal program unit nesting level
14392 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14393 Report the maximal construct nesting level
14395 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14396 Do not report the maximal construct nesting level
14400 @node Complexity Metrics Control
14401 @subsubsection Complexity Metrics Control
14402 @cindex Complexity metrics control in @command{gnatmetric}
14405 For a program unit that is an executable body (a subprogram body (including
14406 generic bodies), task body, entry body or a package body containing
14407 its own statement sequence) @command{gnatmetric} computes the following
14408 complexity metrics:
14412 McCabe cyclomatic complexity;
14415 McCabe essential complexity;
14418 maximal loop nesting level;
14421 extra exit points (for subprograms);
14425 The McCabe cyclomatic complexity metric is defined
14426 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14428 According to McCabe, both control statements and short-circuit control forms
14429 should be taken into account when computing cyclomatic complexity. For each
14430 body, we compute three metric values:
14434 the complexity introduced by control
14435 statements only, without taking into account short-circuit forms,
14438 the complexity introduced by short-circuit control forms only, and
14442 cyclomatic complexity, which is the sum of these two values.
14447 The origin of cyclomatic complexity metric is the need to estimate the number
14448 of independent paths in the control flow graph that in turn gives the number
14449 of tests needed to satisfy paths coverage testing completeness criterion.
14450 Considered from the testing point of view, a static Ada @code{loop} (that is,
14451 the @code{loop} statement having static subtype in loop parameter
14452 specification) does not add to cyclomatic complexity. By providing
14453 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14454 may specify that such loops should not be counted when computing the
14455 cyclomatic complexity metric
14457 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14458 counted for the code that is reduced by excluding all the pure structural Ada
14459 control statements. An compound statement is considered as a non-structural
14460 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14461 or if it contains a @code{goto} statement that transfers the control outside
14462 the operator. A selective accept statement with @code{terminate} alternative
14463 is considered as non-structural statement. When computing this metric,
14464 @code{exit} statements are treated in the same way as @code{goto}
14465 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14467 The Ada essential complexity metric defined here is intended to quantify
14468 the extent to which the software is unstructured. It is adapted from
14469 the McCabe essential complexity metric defined in
14470 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14471 suitable for typical Ada usage. For example, short circuit forms
14472 are not penalized as unstructured in the Ada essential complexity metric.
14474 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14475 the code in the exception handlers and in all the nested program units.
14477 By default, all the complexity metrics are computed and reported.
14478 For more fine-grained control you can use
14479 the following switches:
14482 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14485 @cindex @option{--no-complexity@var{x}}
14488 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14489 Report all the complexity metrics
14491 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14492 Do not report any of complexity metrics
14494 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14495 Report the McCabe Cyclomatic Complexity
14497 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14498 Do not report the McCabe Cyclomatic Complexity
14500 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14501 Report the Essential Complexity
14503 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14504 Do not report the Essential Complexity
14506 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14507 Report maximal loop nesting level
14509 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14510 Do not report maximal loop nesting level
14512 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14513 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14514 task bodies, entry bodies and statement sequences in package bodies.
14515 The metric is computed and reported for whole set of processed Ada sources
14518 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14519 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14520 bodies, task bodies, entry bodies and statement sequences in package bodies
14522 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14523 @item ^-ne^/NO_EXITS_AS_GOTOS^
14524 Do not consider @code{exit} statements as @code{goto}s when
14525 computing Essential Complexity
14527 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14528 @item ^--no-static-loop^/NO_STATIC_LOOP^
14529 Do not consider static loops when computing cyclomatic complexity
14531 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14532 Report the extra exit points for subprogram bodies. As an exit point, this
14533 metric counts @code{return} statements and raise statements in case when the
14534 raised exception is not handled in the same body. In case of a function this
14535 metric subtracts 1 from the number of exit points, because a function body
14536 must contain at least one @code{return} statement.
14538 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14539 Do not report the extra exit points for subprogram bodies
14543 @node Coupling Metrics Control
14544 @subsubsection Coupling Metrics Control
14545 @cindex Coupling metrics control in @command{gnatmetric}
14548 @cindex Coupling metrics (in in @command{gnatmetric})
14549 Coupling metrics measure the dependencies between a given entity and other
14550 entities the program consists of. The goal of these metrics is to estimate the
14551 stability of the whole program considered as the collection of entities
14552 (modules, classes etc.).
14554 Gnatmetric computes the following coupling metrics:
14559 @emph{object-oriented coupling} - for classes in traditional object-oriented
14563 @emph{unit coupling} - for all the program units making up a program;
14566 @emph{control coupling} - this metric counts dependencies between a unit and
14567 only those units that define subprograms;
14571 Two kinds of coupling metrics are computed:
14574 @item fan-out coupling (efferent coupling)
14575 @cindex fan-out coupling
14576 @cindex efferent coupling
14577 the number of entities the given entity depends upon. It
14578 estimates in what extent the given entity depends on the changes in
14581 @item fan-in coupling (afferent coupling)
14582 @cindex fan-in coupling
14583 @cindex afferent coupling
14584 the number of entities that depend on a given entity.
14585 It estimates in what extent the ``external world'' depends on the changes in a
14591 Object-oriented coupling metrics are metrics that measure the dependencies
14592 between a given class (or a group of classes) and the other classes in the
14593 program. In this subsection the term ``class'' is used in its traditional
14594 object-oriented programming sense (an instantiable module that contains data
14595 and/or method members). A @emph{category} (of classes) is a group of closely
14596 related classes that are reused and/or modified together.
14598 A class @code{K}'s fan-out coupling is the number of classes
14599 that @code{K} depends upon.
14600 A category's fan-out coupling is the number of classes outside the
14601 category that the classes inside the category depend upon.
14603 A class @code{K}'s fan-in coupling is the number of classes
14604 that depend upon @code{K}.
14605 A category's fan-in coupling is the number of classes outside the
14606 category that depend on classes belonging to the category.
14608 Ada's implementation of the object-oriented paradigm does not use the
14609 traditional class notion, so the definition of the coupling
14610 metrics for Ada maps the class and class category notions
14611 onto Ada constructs.
14613 For the coupling metrics, several kinds of modules -- a library package,
14614 a library generic package, and a library generic package instantiation --
14615 that define a tagged type or an interface type are
14616 considered to be a class. A category consists of a library package (or
14617 a library generic package) that defines a tagged or an interface type,
14618 together with all its descendant (generic) packages that define tagged
14619 or interface types. That is a
14620 category is an Ada hierarchy of library-level program units. So class coupling
14621 in case of Ada is called as tagged coupling, and category coupling - as
14622 hierarchy coupling.
14624 For any package counted as a class, its body and subunits (if any) are
14625 considered together with its spec when counting the dependencies, and coupling
14626 metrics are reported for spec units only. For dependencies between classes,
14627 the Ada semantic dependencies are considered. For object-oriented coupling
14628 metrics, only dependencies on units that are considered as classes, are
14631 For unit and control coupling also not compilation units but program units are
14632 counted. That is, for a package, its spec, its body and its subunits (if any)
14633 are considered as making up one unit, and the dependencies that are counted
14634 are the dependencies of all these compilation units collected together as
14635 the dependencies as a (whole) unit. And metrics are reported for spec
14636 compilation units only (or for a subprogram body unit in case if there is no
14637 separate spec for the given subprogram).
14639 For unit coupling, dependencies between all kinds of program units are
14640 considered. For control coupling, for each unit the dependencies of this unit
14641 upon units that define subprograms are counted, so control fan-out coupling
14642 is reported for all units, but control fan-in coupling - only for the units
14643 that define subprograms.
14650 When computing coupling metrics, @command{gnatmetric} counts only
14651 dependencies between units that are arguments of the gnatmetric call.
14652 Coupling metrics are program-wide (or project-wide) metrics, so to
14653 get a valid result, you should call @command{gnatmetric} for
14654 the whole set of sources that make up your program. It can be done
14655 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14656 option (see @ref{The GNAT Driver and Project Files} for details).
14658 By default, all the coupling metrics are disabled. You can use the following
14659 switches to specify the coupling metrics to be computed and reported:
14664 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14665 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14666 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14667 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14671 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14674 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14675 Report all the coupling metrics
14677 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14678 Report tagged (class) fan-out coupling
14680 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14681 Report tagged (class) fan-in coupling
14683 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14684 Report hierarchy (category) fan-out coupling
14686 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14687 Report hierarchy (category) fan-in coupling
14689 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14690 Report unit fan-out coupling
14692 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14693 Report unit fan-in coupling
14695 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14696 Report control fan-out coupling
14698 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14699 Report control fan-in coupling
14702 @node Other gnatmetric Switches
14703 @subsection Other @code{gnatmetric} Switches
14706 Additional @command{gnatmetric} switches are as follows:
14709 @item ^-files @var{filename}^/FILES=@var{filename}^
14710 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14711 Take the argument source files from the specified file. This file should be an
14712 ordinary text file containing file names separated by spaces or
14713 line breaks. You can use this switch more than once in the same call to
14714 @command{gnatmetric}. You also can combine this switch with
14715 an explicit list of files.
14717 @item ^-v^/VERBOSE^
14718 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14720 @command{gnatmetric} generates version information and then
14721 a trace of sources being processed.
14724 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14728 @node Generate project-wide metrics
14729 @subsection Generate project-wide metrics
14731 In order to compute metrics on all units of a given project, you can use
14732 the @command{gnat} driver along with the @option{-P} option:
14738 If the project @code{proj} depends upon other projects, you can compute
14739 the metrics on the project closure using the @option{-U} option:
14741 gnat metric -Pproj -U
14745 Finally, if not all the units are relevant to a particular main
14746 program in the project closure, you can generate metrics for the set
14747 of units needed to create a given main program (unit closure) using
14748 the @option{-U} option followed by the name of the main unit:
14750 gnat metric -Pproj -U main
14754 @c ***********************************
14755 @node File Name Krunching Using gnatkr
14756 @chapter File Name Krunching Using @code{gnatkr}
14760 This chapter discusses the method used by the compiler to shorten
14761 the default file names chosen for Ada units so that they do not
14762 exceed the maximum length permitted. It also describes the
14763 @code{gnatkr} utility that can be used to determine the result of
14764 applying this shortening.
14768 * Krunching Method::
14769 * Examples of gnatkr Usage::
14773 @section About @code{gnatkr}
14776 The default file naming rule in GNAT
14777 is that the file name must be derived from
14778 the unit name. The exact default rule is as follows:
14781 Take the unit name and replace all dots by hyphens.
14783 If such a replacement occurs in the
14784 second character position of a name, and the first character is
14785 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14786 then replace the dot by the character
14787 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14788 instead of a minus.
14790 The reason for this exception is to avoid clashes
14791 with the standard names for children of System, Ada, Interfaces,
14792 and GNAT, which use the prefixes
14793 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14796 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14797 switch of the compiler activates a ``krunching''
14798 circuit that limits file names to nn characters (where nn is a decimal
14799 integer). For example, using OpenVMS,
14800 where the maximum file name length is
14801 39, the value of nn is usually set to 39, but if you want to generate
14802 a set of files that would be usable if ported to a system with some
14803 different maximum file length, then a different value can be specified.
14804 The default value of 39 for OpenVMS need not be specified.
14806 The @code{gnatkr} utility can be used to determine the krunched name for
14807 a given file, when krunched to a specified maximum length.
14810 @section Using @code{gnatkr}
14813 The @code{gnatkr} command has the form
14817 @c $ gnatkr @var{name} @ovar{length}
14818 @c Expanding @ovar macro inline (explanation in macro def comments)
14819 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14825 $ gnatkr @var{name} /COUNT=nn
14830 @var{name} is the uncrunched file name, derived from the name of the unit
14831 in the standard manner described in the previous section (i.e., in particular
14832 all dots are replaced by hyphens). The file name may or may not have an
14833 extension (defined as a suffix of the form period followed by arbitrary
14834 characters other than period). If an extension is present then it will
14835 be preserved in the output. For example, when krunching @file{hellofile.ads}
14836 to eight characters, the result will be hellofil.ads.
14838 Note: for compatibility with previous versions of @code{gnatkr} dots may
14839 appear in the name instead of hyphens, but the last dot will always be
14840 taken as the start of an extension. So if @code{gnatkr} is given an argument
14841 such as @file{Hello.World.adb} it will be treated exactly as if the first
14842 period had been a hyphen, and for example krunching to eight characters
14843 gives the result @file{hellworl.adb}.
14845 Note that the result is always all lower case (except on OpenVMS where it is
14846 all upper case). Characters of the other case are folded as required.
14848 @var{length} represents the length of the krunched name. The default
14849 when no argument is given is ^8^39^ characters. A length of zero stands for
14850 unlimited, in other words do not chop except for system files where the
14851 implied crunching length is always eight characters.
14854 The output is the krunched name. The output has an extension only if the
14855 original argument was a file name with an extension.
14857 @node Krunching Method
14858 @section Krunching Method
14861 The initial file name is determined by the name of the unit that the file
14862 contains. The name is formed by taking the full expanded name of the
14863 unit and replacing the separating dots with hyphens and
14864 using ^lowercase^uppercase^
14865 for all letters, except that a hyphen in the second character position is
14866 replaced by a ^tilde^dollar sign^ if the first character is
14867 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14868 The extension is @code{.ads} for a
14869 spec and @code{.adb} for a body.
14870 Krunching does not affect the extension, but the file name is shortened to
14871 the specified length by following these rules:
14875 The name is divided into segments separated by hyphens, tildes or
14876 underscores and all hyphens, tildes, and underscores are
14877 eliminated. If this leaves the name short enough, we are done.
14880 If the name is too long, the longest segment is located (left-most
14881 if there are two of equal length), and shortened by dropping
14882 its last character. This is repeated until the name is short enough.
14884 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14885 to fit the name into 8 characters as required by some operating systems.
14888 our-strings-wide_fixed 22
14889 our strings wide fixed 19
14890 our string wide fixed 18
14891 our strin wide fixed 17
14892 our stri wide fixed 16
14893 our stri wide fixe 15
14894 our str wide fixe 14
14895 our str wid fixe 13
14901 Final file name: oustwifi.adb
14905 The file names for all predefined units are always krunched to eight
14906 characters. The krunching of these predefined units uses the following
14907 special prefix replacements:
14911 replaced by @file{^a^A^-}
14914 replaced by @file{^g^G^-}
14917 replaced by @file{^i^I^-}
14920 replaced by @file{^s^S^-}
14923 These system files have a hyphen in the second character position. That
14924 is why normal user files replace such a character with a
14925 ^tilde^dollar sign^, to
14926 avoid confusion with system file names.
14928 As an example of this special rule, consider
14929 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14932 ada-strings-wide_fixed 22
14933 a- strings wide fixed 18
14934 a- string wide fixed 17
14935 a- strin wide fixed 16
14936 a- stri wide fixed 15
14937 a- stri wide fixe 14
14938 a- str wide fixe 13
14944 Final file name: a-stwifi.adb
14948 Of course no file shortening algorithm can guarantee uniqueness over all
14949 possible unit names, and if file name krunching is used then it is your
14950 responsibility to ensure that no name clashes occur. The utility
14951 program @code{gnatkr} is supplied for conveniently determining the
14952 krunched name of a file.
14954 @node Examples of gnatkr Usage
14955 @section Examples of @code{gnatkr} Usage
14962 $ gnatkr very_long_unit_name.ads --> velounna.ads
14963 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14964 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14965 $ gnatkr grandparent-parent-child --> grparchi
14967 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14968 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14971 @node Preprocessing Using gnatprep
14972 @chapter Preprocessing Using @code{gnatprep}
14976 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14978 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14979 special GNAT features.
14980 For further discussion of conditional compilation in general, see
14981 @ref{Conditional Compilation}.
14984 * Preprocessing Symbols::
14986 * Switches for gnatprep::
14987 * Form of Definitions File::
14988 * Form of Input Text for gnatprep::
14991 @node Preprocessing Symbols
14992 @section Preprocessing Symbols
14995 Preprocessing symbols are defined in definition files and referred to in
14996 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14997 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14998 all characters need to be in the ASCII set (no accented letters).
15000 @node Using gnatprep
15001 @section Using @code{gnatprep}
15004 To call @code{gnatprep} use
15007 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15008 @c Expanding @ovar macro inline (explanation in macro def comments)
15009 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15016 is an optional sequence of switches as described in the next section.
15019 is the full name of the input file, which is an Ada source
15020 file containing preprocessor directives.
15023 is the full name of the output file, which is an Ada source
15024 in standard Ada form. When used with GNAT, this file name will
15025 normally have an ads or adb suffix.
15028 is the full name of a text file containing definitions of
15029 preprocessing symbols to be referenced by the preprocessor. This argument is
15030 optional, and can be replaced by the use of the @option{-D} switch.
15034 @node Switches for gnatprep
15035 @section Switches for @code{gnatprep}
15040 @item ^-b^/BLANK_LINES^
15041 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15042 Causes both preprocessor lines and the lines deleted by
15043 preprocessing to be replaced by blank lines in the output source file,
15044 preserving line numbers in the output file.
15046 @item ^-c^/COMMENTS^
15047 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15048 Causes both preprocessor lines and the lines deleted
15049 by preprocessing to be retained in the output source as comments marked
15050 with the special string @code{"--! "}. This option will result in line numbers
15051 being preserved in the output file.
15053 @item ^-C^/REPLACE_IN_COMMENTS^
15054 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15055 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15056 If this option is specified, then comments are scanned and any $symbol
15057 substitutions performed as in program text. This is particularly useful
15058 when structured comments are used (e.g., when writing programs in the
15059 SPARK dialect of Ada). Note that this switch is not available when
15060 doing integrated preprocessing (it would be useless in this context
15061 since comments are ignored by the compiler in any case).
15063 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15064 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15065 Defines a new preprocessing symbol, associated with value. If no value is given
15066 on the command line, then symbol is considered to be @code{True}. This switch
15067 can be used in place of a definition file.
15071 @cindex @option{/REMOVE} (@command{gnatprep})
15072 This is the default setting which causes lines deleted by preprocessing
15073 to be entirely removed from the output file.
15076 @item ^-r^/REFERENCE^
15077 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15078 Causes a @code{Source_Reference} pragma to be generated that
15079 references the original input file, so that error messages will use
15080 the file name of this original file. The use of this switch implies
15081 that preprocessor lines are not to be removed from the file, so its
15082 use will force @option{^-b^/BLANK_LINES^} mode if
15083 @option{^-c^/COMMENTS^}
15084 has not been specified explicitly.
15086 Note that if the file to be preprocessed contains multiple units, then
15087 it will be necessary to @code{gnatchop} the output file from
15088 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15089 in the preprocessed file, it will be respected by
15090 @code{gnatchop ^-r^/REFERENCE^}
15091 so that the final chopped files will correctly refer to the original
15092 input source file for @code{gnatprep}.
15094 @item ^-s^/SYMBOLS^
15095 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15096 Causes a sorted list of symbol names and values to be
15097 listed on the standard output file.
15099 @item ^-u^/UNDEFINED^
15100 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15101 Causes undefined symbols to be treated as having the value FALSE in the context
15102 of a preprocessor test. In the absence of this option, an undefined symbol in
15103 a @code{#if} or @code{#elsif} test will be treated as an error.
15109 Note: if neither @option{-b} nor @option{-c} is present,
15110 then preprocessor lines and
15111 deleted lines are completely removed from the output, unless -r is
15112 specified, in which case -b is assumed.
15115 @node Form of Definitions File
15116 @section Form of Definitions File
15119 The definitions file contains lines of the form
15126 where symbol is a preprocessing symbol, and value is one of the following:
15130 Empty, corresponding to a null substitution
15132 A string literal using normal Ada syntax
15134 Any sequence of characters from the set
15135 (letters, digits, period, underline).
15139 Comment lines may also appear in the definitions file, starting with
15140 the usual @code{--},
15141 and comments may be added to the definitions lines.
15143 @node Form of Input Text for gnatprep
15144 @section Form of Input Text for @code{gnatprep}
15147 The input text may contain preprocessor conditional inclusion lines,
15148 as well as general symbol substitution sequences.
15150 The preprocessor conditional inclusion commands have the form
15155 #if @i{expression} @r{[}then@r{]}
15157 #elsif @i{expression} @r{[}then@r{]}
15159 #elsif @i{expression} @r{[}then@r{]}
15170 In this example, @i{expression} is defined by the following grammar:
15172 @i{expression} ::= <symbol>
15173 @i{expression} ::= <symbol> = "<value>"
15174 @i{expression} ::= <symbol> = <symbol>
15175 @i{expression} ::= <symbol> 'Defined
15176 @i{expression} ::= not @i{expression}
15177 @i{expression} ::= @i{expression} and @i{expression}
15178 @i{expression} ::= @i{expression} or @i{expression}
15179 @i{expression} ::= @i{expression} and then @i{expression}
15180 @i{expression} ::= @i{expression} or else @i{expression}
15181 @i{expression} ::= ( @i{expression} )
15184 The following restriction exists: it is not allowed to have "and" or "or"
15185 following "not" in the same expression without parentheses. For example, this
15192 This should be one of the following:
15200 For the first test (@i{expression} ::= <symbol>) the symbol must have
15201 either the value true or false, that is to say the right-hand of the
15202 symbol definition must be one of the (case-insensitive) literals
15203 @code{True} or @code{False}. If the value is true, then the
15204 corresponding lines are included, and if the value is false, they are
15207 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15208 the symbol has been defined in the definition file or by a @option{-D}
15209 switch on the command line. Otherwise, the test is false.
15211 The equality tests are case insensitive, as are all the preprocessor lines.
15213 If the symbol referenced is not defined in the symbol definitions file,
15214 then the effect depends on whether or not switch @option{-u}
15215 is specified. If so, then the symbol is treated as if it had the value
15216 false and the test fails. If this switch is not specified, then
15217 it is an error to reference an undefined symbol. It is also an error to
15218 reference a symbol that is defined with a value other than @code{True}
15221 The use of the @code{not} operator inverts the sense of this logical test.
15222 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15223 operators, without parentheses. For example, "if not X or Y then" is not
15224 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15226 The @code{then} keyword is optional as shown
15228 The @code{#} must be the first non-blank character on a line, but
15229 otherwise the format is free form. Spaces or tabs may appear between
15230 the @code{#} and the keyword. The keywords and the symbols are case
15231 insensitive as in normal Ada code. Comments may be used on a
15232 preprocessor line, but other than that, no other tokens may appear on a
15233 preprocessor line. Any number of @code{elsif} clauses can be present,
15234 including none at all. The @code{else} is optional, as in Ada.
15236 The @code{#} marking the start of a preprocessor line must be the first
15237 non-blank character on the line, i.e., it must be preceded only by
15238 spaces or horizontal tabs.
15240 Symbol substitution outside of preprocessor lines is obtained by using
15248 anywhere within a source line, except in a comment or within a
15249 string literal. The identifier
15250 following the @code{$} must match one of the symbols defined in the symbol
15251 definition file, and the result is to substitute the value of the
15252 symbol in place of @code{$symbol} in the output file.
15254 Note that although the substitution of strings within a string literal
15255 is not possible, it is possible to have a symbol whose defined value is
15256 a string literal. So instead of setting XYZ to @code{hello} and writing:
15259 Header : String := "$XYZ";
15263 you should set XYZ to @code{"hello"} and write:
15266 Header : String := $XYZ;
15270 and then the substitution will occur as desired.
15272 @node The GNAT Library Browser gnatls
15273 @chapter The GNAT Library Browser @code{gnatls}
15275 @cindex Library browser
15278 @code{gnatls} is a tool that outputs information about compiled
15279 units. It gives the relationship between objects, unit names and source
15280 files. It can also be used to check the source dependencies of a unit
15281 as well as various characteristics.
15283 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15284 driver (see @ref{The GNAT Driver and Project Files}).
15288 * Switches for gnatls::
15289 * Examples of gnatls Usage::
15292 @node Running gnatls
15293 @section Running @code{gnatls}
15296 The @code{gnatls} command has the form
15299 $ gnatls switches @var{object_or_ali_file}
15303 The main argument is the list of object or @file{ali} files
15304 (@pxref{The Ada Library Information Files})
15305 for which information is requested.
15307 In normal mode, without additional option, @code{gnatls} produces a
15308 four-column listing. Each line represents information for a specific
15309 object. The first column gives the full path of the object, the second
15310 column gives the name of the principal unit in this object, the third
15311 column gives the status of the source and the fourth column gives the
15312 full path of the source representing this unit.
15313 Here is a simple example of use:
15317 ^./^[]^demo1.o demo1 DIF demo1.adb
15318 ^./^[]^demo2.o demo2 OK demo2.adb
15319 ^./^[]^hello.o h1 OK hello.adb
15320 ^./^[]^instr-child.o instr.child MOK instr-child.adb
15321 ^./^[]^instr.o instr OK instr.adb
15322 ^./^[]^tef.o tef DIF tef.adb
15323 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
15324 ^./^[]^tgef.o tgef DIF tgef.adb
15328 The first line can be interpreted as follows: the main unit which is
15330 object file @file{demo1.o} is demo1, whose main source is in
15331 @file{demo1.adb}. Furthermore, the version of the source used for the
15332 compilation of demo1 has been modified (DIF). Each source file has a status
15333 qualifier which can be:
15336 @item OK (unchanged)
15337 The version of the source file used for the compilation of the
15338 specified unit corresponds exactly to the actual source file.
15340 @item MOK (slightly modified)
15341 The version of the source file used for the compilation of the
15342 specified unit differs from the actual source file but not enough to
15343 require recompilation. If you use gnatmake with the qualifier
15344 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15345 MOK will not be recompiled.
15347 @item DIF (modified)
15348 No version of the source found on the path corresponds to the source
15349 used to build this object.
15351 @item ??? (file not found)
15352 No source file was found for this unit.
15354 @item HID (hidden, unchanged version not first on PATH)
15355 The version of the source that corresponds exactly to the source used
15356 for compilation has been found on the path but it is hidden by another
15357 version of the same source that has been modified.
15361 @node Switches for gnatls
15362 @section Switches for @code{gnatls}
15365 @code{gnatls} recognizes the following switches:
15369 @cindex @option{--version} @command{gnatls}
15370 Display Copyright and version, then exit disregarding all other options.
15373 @cindex @option{--help} @command{gnatls}
15374 If @option{--version} was not used, display usage, then exit disregarding
15377 @item ^-a^/ALL_UNITS^
15378 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15379 Consider all units, including those of the predefined Ada library.
15380 Especially useful with @option{^-d^/DEPENDENCIES^}.
15382 @item ^-d^/DEPENDENCIES^
15383 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15384 List sources from which specified units depend on.
15386 @item ^-h^/OUTPUT=OPTIONS^
15387 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15388 Output the list of options.
15390 @item ^-o^/OUTPUT=OBJECTS^
15391 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15392 Only output information about object files.
15394 @item ^-s^/OUTPUT=SOURCES^
15395 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15396 Only output information about source files.
15398 @item ^-u^/OUTPUT=UNITS^
15399 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15400 Only output information about compilation units.
15402 @item ^-files^/FILES^=@var{file}
15403 @cindex @option{^-files^/FILES^} (@code{gnatls})
15404 Take as arguments the files listed in text file @var{file}.
15405 Text file @var{file} may contain empty lines that are ignored.
15406 Each nonempty line should contain the name of an existing file.
15407 Several such switches may be specified simultaneously.
15409 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15410 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15411 @itemx ^-I^/SEARCH=^@var{dir}
15412 @itemx ^-I-^/NOCURRENT_DIRECTORY^
15414 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15415 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15416 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15417 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15418 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15419 flags (@pxref{Switches for gnatmake}).
15421 @item --RTS=@var{rts-path}
15422 @cindex @option{--RTS} (@code{gnatls})
15423 Specifies the default location of the runtime library. Same meaning as the
15424 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15426 @item ^-v^/OUTPUT=VERBOSE^
15427 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15428 Verbose mode. Output the complete source, object and project paths. Do not use
15429 the default column layout but instead use long format giving as much as
15430 information possible on each requested units, including special
15431 characteristics such as:
15434 @item Preelaborable
15435 The unit is preelaborable in the Ada sense.
15438 No elaboration code has been produced by the compiler for this unit.
15441 The unit is pure in the Ada sense.
15443 @item Elaborate_Body
15444 The unit contains a pragma Elaborate_Body.
15447 The unit contains a pragma Remote_Types.
15449 @item Shared_Passive
15450 The unit contains a pragma Shared_Passive.
15453 This unit is part of the predefined environment and cannot be modified
15456 @item Remote_Call_Interface
15457 The unit contains a pragma Remote_Call_Interface.
15463 @node Examples of gnatls Usage
15464 @section Example of @code{gnatls} Usage
15468 Example of using the verbose switch. Note how the source and
15469 object paths are affected by the -I switch.
15472 $ gnatls -v -I.. demo1.o
15474 GNATLS 5.03w (20041123-34)
15475 Copyright 1997-2004 Free Software Foundation, Inc.
15477 Source Search Path:
15478 <Current_Directory>
15480 /home/comar/local/adainclude/
15482 Object Search Path:
15483 <Current_Directory>
15485 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15487 Project Search Path:
15488 <Current_Directory>
15489 /home/comar/local/lib/gnat/
15494 Kind => subprogram body
15495 Flags => No_Elab_Code
15496 Source => demo1.adb modified
15500 The following is an example of use of the dependency list.
15501 Note the use of the -s switch
15502 which gives a straight list of source files. This can be useful for
15503 building specialized scripts.
15506 $ gnatls -d demo2.o
15507 ./demo2.o demo2 OK demo2.adb
15513 $ gnatls -d -s -a demo1.o
15515 /home/comar/local/adainclude/ada.ads
15516 /home/comar/local/adainclude/a-finali.ads
15517 /home/comar/local/adainclude/a-filico.ads
15518 /home/comar/local/adainclude/a-stream.ads
15519 /home/comar/local/adainclude/a-tags.ads
15522 /home/comar/local/adainclude/gnat.ads
15523 /home/comar/local/adainclude/g-io.ads
15525 /home/comar/local/adainclude/system.ads
15526 /home/comar/local/adainclude/s-exctab.ads
15527 /home/comar/local/adainclude/s-finimp.ads
15528 /home/comar/local/adainclude/s-finroo.ads
15529 /home/comar/local/adainclude/s-secsta.ads
15530 /home/comar/local/adainclude/s-stalib.ads
15531 /home/comar/local/adainclude/s-stoele.ads
15532 /home/comar/local/adainclude/s-stratt.ads
15533 /home/comar/local/adainclude/s-tasoli.ads
15534 /home/comar/local/adainclude/s-unstyp.ads
15535 /home/comar/local/adainclude/unchconv.ads
15541 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15543 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15544 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15545 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15546 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15547 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15551 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15552 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15554 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15555 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15556 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15557 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15558 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15559 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15560 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15561 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15562 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15563 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15564 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15568 @node Cleaning Up Using gnatclean
15569 @chapter Cleaning Up Using @code{gnatclean}
15571 @cindex Cleaning tool
15574 @code{gnatclean} is a tool that allows the deletion of files produced by the
15575 compiler, binder and linker, including ALI files, object files, tree files,
15576 expanded source files, library files, interface copy source files, binder
15577 generated files and executable files.
15580 * Running gnatclean::
15581 * Switches for gnatclean::
15582 @c * Examples of gnatclean Usage::
15585 @node Running gnatclean
15586 @section Running @code{gnatclean}
15589 The @code{gnatclean} command has the form:
15592 $ gnatclean switches @var{names}
15596 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15597 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15598 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15601 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15602 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15603 the linker. In informative-only mode, specified by switch
15604 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15605 normal mode is listed, but no file is actually deleted.
15607 @node Switches for gnatclean
15608 @section Switches for @code{gnatclean}
15611 @code{gnatclean} recognizes the following switches:
15615 @cindex @option{--version} @command{gnatclean}
15616 Display Copyright and version, then exit disregarding all other options.
15619 @cindex @option{--help} @command{gnatclean}
15620 If @option{--version} was not used, display usage, then exit disregarding
15623 @item ^--subdirs^/SUBDIRS^=subdir
15624 Actual object directory of each project file is the subdirectory subdir of the
15625 object directory specified or defaulted in the project file.
15627 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15628 By default, shared library projects are not allowed to import static library
15629 projects. When this switch is used on the command line, this restriction is
15632 @item ^-c^/COMPILER_FILES_ONLY^
15633 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15634 Only attempt to delete the files produced by the compiler, not those produced
15635 by the binder or the linker. The files that are not to be deleted are library
15636 files, interface copy files, binder generated files and executable files.
15638 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15639 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15640 Indicate that ALI and object files should normally be found in directory
15643 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15644 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15645 When using project files, if some errors or warnings are detected during
15646 parsing and verbose mode is not in effect (no use of switch
15647 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15648 file, rather than its simple file name.
15651 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15652 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15654 @item ^-n^/NODELETE^
15655 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15656 Informative-only mode. Do not delete any files. Output the list of the files
15657 that would have been deleted if this switch was not specified.
15659 @item ^-P^/PROJECT_FILE=^@var{project}
15660 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15661 Use project file @var{project}. Only one such switch can be used.
15662 When cleaning a project file, the files produced by the compilation of the
15663 immediate sources or inherited sources of the project files are to be
15664 deleted. This is not depending on the presence or not of executable names
15665 on the command line.
15668 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15669 Quiet output. If there are no errors, do not output anything, except in
15670 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15671 (switch ^-n^/NODELETE^).
15673 @item ^-r^/RECURSIVE^
15674 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15675 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15676 clean all imported and extended project files, recursively. If this switch
15677 is not specified, only the files related to the main project file are to be
15678 deleted. This switch has no effect if no project file is specified.
15680 @item ^-v^/VERBOSE^
15681 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15684 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15685 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15686 Indicates the verbosity of the parsing of GNAT project files.
15687 @xref{Switches Related to Project Files}.
15689 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15690 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15691 Indicates that external variable @var{name} has the value @var{value}.
15692 The Project Manager will use this value for occurrences of
15693 @code{external(name)} when parsing the project file.
15694 @xref{Switches Related to Project Files}.
15696 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15697 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15698 When searching for ALI and object files, look in directory
15701 @item ^-I^/SEARCH=^@var{dir}
15702 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15703 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15705 @item ^-I-^/NOCURRENT_DIRECTORY^
15706 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15707 @cindex Source files, suppressing search
15708 Do not look for ALI or object files in the directory
15709 where @code{gnatclean} was invoked.
15713 @c @node Examples of gnatclean Usage
15714 @c @section Examples of @code{gnatclean} Usage
15717 @node GNAT and Libraries
15718 @chapter GNAT and Libraries
15719 @cindex Library, building, installing, using
15722 This chapter describes how to build and use libraries with GNAT, and also shows
15723 how to recompile the GNAT run-time library. You should be familiar with the
15724 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15728 * Introduction to Libraries in GNAT::
15729 * General Ada Libraries::
15730 * Stand-alone Ada Libraries::
15731 * Rebuilding the GNAT Run-Time Library::
15734 @node Introduction to Libraries in GNAT
15735 @section Introduction to Libraries in GNAT
15738 A library is, conceptually, a collection of objects which does not have its
15739 own main thread of execution, but rather provides certain services to the
15740 applications that use it. A library can be either statically linked with the
15741 application, in which case its code is directly included in the application,
15742 or, on platforms that support it, be dynamically linked, in which case
15743 its code is shared by all applications making use of this library.
15745 GNAT supports both types of libraries.
15746 In the static case, the compiled code can be provided in different ways. The
15747 simplest approach is to provide directly the set of objects resulting from
15748 compilation of the library source files. Alternatively, you can group the
15749 objects into an archive using whatever commands are provided by the operating
15750 system. For the latter case, the objects are grouped into a shared library.
15752 In the GNAT environment, a library has three types of components:
15758 @xref{The Ada Library Information Files}.
15760 Object files, an archive or a shared library.
15764 A GNAT library may expose all its source files, which is useful for
15765 documentation purposes. Alternatively, it may expose only the units needed by
15766 an external user to make use of the library. That is to say, the specs
15767 reflecting the library services along with all the units needed to compile
15768 those specs, which can include generic bodies or any body implementing an
15769 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15770 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15772 All compilation units comprising an application, including those in a library,
15773 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15774 computes the elaboration order from the @file{ALI} files and this is why they
15775 constitute a mandatory part of GNAT libraries.
15776 @emph{Stand-alone libraries} are the exception to this rule because a specific
15777 library elaboration routine is produced independently of the application(s)
15780 @node General Ada Libraries
15781 @section General Ada Libraries
15784 * Building a library::
15785 * Installing a library::
15786 * Using a library::
15789 @node Building a library
15790 @subsection Building a library
15793 The easiest way to build a library is to use the Project Manager,
15794 which supports a special type of project called a @emph{Library Project}
15795 (@pxref{Library Projects}).
15797 A project is considered a library project, when two project-level attributes
15798 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15799 control different aspects of library configuration, additional optional
15800 project-level attributes can be specified:
15803 This attribute controls whether the library is to be static or dynamic
15805 @item Library_Version
15806 This attribute specifies the library version; this value is used
15807 during dynamic linking of shared libraries to determine if the currently
15808 installed versions of the binaries are compatible.
15810 @item Library_Options
15812 These attributes specify additional low-level options to be used during
15813 library generation, and redefine the actual application used to generate
15818 The GNAT Project Manager takes full care of the library maintenance task,
15819 including recompilation of the source files for which objects do not exist
15820 or are not up to date, assembly of the library archive, and installation of
15821 the library (i.e., copying associated source, object and @file{ALI} files
15822 to the specified location).
15824 Here is a simple library project file:
15825 @smallexample @c ada
15827 for Source_Dirs use ("src1", "src2");
15828 for Object_Dir use "obj";
15829 for Library_Name use "mylib";
15830 for Library_Dir use "lib";
15831 for Library_Kind use "dynamic";
15836 and the compilation command to build and install the library:
15838 @smallexample @c ada
15839 $ gnatmake -Pmy_lib
15843 It is not entirely trivial to perform manually all the steps required to
15844 produce a library. We recommend that you use the GNAT Project Manager
15845 for this task. In special cases where this is not desired, the necessary
15846 steps are discussed below.
15848 There are various possibilities for compiling the units that make up the
15849 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15850 with a conventional script. For simple libraries, it is also possible to create
15851 a dummy main program which depends upon all the packages that comprise the
15852 interface of the library. This dummy main program can then be given to
15853 @command{gnatmake}, which will ensure that all necessary objects are built.
15855 After this task is accomplished, you should follow the standard procedure
15856 of the underlying operating system to produce the static or shared library.
15858 Here is an example of such a dummy program:
15859 @smallexample @c ada
15861 with My_Lib.Service1;
15862 with My_Lib.Service2;
15863 with My_Lib.Service3;
15864 procedure My_Lib_Dummy is
15872 Here are the generic commands that will build an archive or a shared library.
15875 # compiling the library
15876 $ gnatmake -c my_lib_dummy.adb
15878 # we don't need the dummy object itself
15879 $ rm my_lib_dummy.o my_lib_dummy.ali
15881 # create an archive with the remaining objects
15882 $ ar rc libmy_lib.a *.o
15883 # some systems may require "ranlib" to be run as well
15885 # or create a shared library
15886 $ gcc -shared -o libmy_lib.so *.o
15887 # some systems may require the code to have been compiled with -fPIC
15889 # remove the object files that are now in the library
15892 # Make the ALI files read-only so that gnatmake will not try to
15893 # regenerate the objects that are in the library
15898 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15899 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15900 be accessed by the directive @option{-l@var{xxx}} at link time.
15902 @node Installing a library
15903 @subsection Installing a library
15904 @cindex @code{ADA_PROJECT_PATH}
15905 @cindex @code{GPR_PROJECT_PATH}
15908 If you use project files, library installation is part of the library build
15909 process (@pxref{Installing a library with project files}).
15911 When project files are not an option, it is also possible, but not recommended,
15912 to install the library so that the sources needed to use the library are on the
15913 Ada source path and the ALI files & libraries be on the Ada Object path (see
15914 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15915 administrator can place general-purpose libraries in the default compiler
15916 paths, by specifying the libraries' location in the configuration files
15917 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15918 must be located in the GNAT installation tree at the same place as the gcc spec
15919 file. The location of the gcc spec file can be determined as follows:
15925 The configuration files mentioned above have a simple format: each line
15926 must contain one unique directory name.
15927 Those names are added to the corresponding path
15928 in their order of appearance in the file. The names can be either absolute
15929 or relative; in the latter case, they are relative to where theses files
15932 The files @file{ada_source_path} and @file{ada_object_path} might not be
15934 GNAT installation, in which case, GNAT will look for its run-time library in
15935 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15936 objects and @file{ALI} files). When the files exist, the compiler does not
15937 look in @file{adainclude} and @file{adalib}, and thus the
15938 @file{ada_source_path} file
15939 must contain the location for the GNAT run-time sources (which can simply
15940 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15941 contain the location for the GNAT run-time objects (which can simply
15944 You can also specify a new default path to the run-time library at compilation
15945 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15946 the run-time library you want your program to be compiled with. This switch is
15947 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15948 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15950 It is possible to install a library before or after the standard GNAT
15951 library, by reordering the lines in the configuration files. In general, a
15952 library must be installed before the GNAT library if it redefines
15955 @node Using a library
15956 @subsection Using a library
15958 @noindent Once again, the project facility greatly simplifies the use of
15959 libraries. In this context, using a library is just a matter of adding a
15960 @code{with} clause in the user project. For instance, to make use of the
15961 library @code{My_Lib} shown in examples in earlier sections, you can
15964 @smallexample @c projectfile
15971 Even if you have a third-party, non-Ada library, you can still use GNAT's
15972 Project Manager facility to provide a wrapper for it. For example, the
15973 following project, when @code{with}ed by your main project, will link with the
15974 third-party library @file{liba.a}:
15976 @smallexample @c projectfile
15979 for Externally_Built use "true";
15980 for Source_Files use ();
15981 for Library_Dir use "lib";
15982 for Library_Name use "a";
15983 for Library_Kind use "static";
15987 This is an alternative to the use of @code{pragma Linker_Options}. It is
15988 especially interesting in the context of systems with several interdependent
15989 static libraries where finding a proper linker order is not easy and best be
15990 left to the tools having visibility over project dependence information.
15993 In order to use an Ada library manually, you need to make sure that this
15994 library is on both your source and object path
15995 (see @ref{Search Paths and the Run-Time Library (RTL)}
15996 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15997 in an archive or a shared library, you need to specify the desired
15998 library at link time.
16000 For example, you can use the library @file{mylib} installed in
16001 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16004 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16009 This can be expressed more simply:
16014 when the following conditions are met:
16017 @file{/dir/my_lib_src} has been added by the user to the environment
16018 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16019 @file{ada_source_path}
16021 @file{/dir/my_lib_obj} has been added by the user to the environment
16022 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16023 @file{ada_object_path}
16025 a pragma @code{Linker_Options} has been added to one of the sources.
16028 @smallexample @c ada
16029 pragma Linker_Options ("-lmy_lib");
16033 @node Stand-alone Ada Libraries
16034 @section Stand-alone Ada Libraries
16035 @cindex Stand-alone library, building, using
16038 * Introduction to Stand-alone Libraries::
16039 * Building a Stand-alone Library::
16040 * Creating a Stand-alone Library to be used in a non-Ada context::
16041 * Restrictions in Stand-alone Libraries::
16044 @node Introduction to Stand-alone Libraries
16045 @subsection Introduction to Stand-alone Libraries
16048 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16050 elaborate the Ada units that are included in the library. In contrast with
16051 an ordinary library, which consists of all sources, objects and @file{ALI}
16053 library, a SAL may specify a restricted subset of compilation units
16054 to serve as a library interface. In this case, the fully
16055 self-sufficient set of files will normally consist of an objects
16056 archive, the sources of interface units' specs, and the @file{ALI}
16057 files of interface units.
16058 If an interface spec contains a generic unit or an inlined subprogram,
16060 source must also be provided; if the units that must be provided in the source
16061 form depend on other units, the source and @file{ALI} files of those must
16064 The main purpose of a SAL is to minimize the recompilation overhead of client
16065 applications when a new version of the library is installed. Specifically,
16066 if the interface sources have not changed, client applications do not need to
16067 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16068 version, controlled by @code{Library_Version} attribute, is not changed,
16069 then the clients do not need to be relinked.
16071 SALs also allow the library providers to minimize the amount of library source
16072 text exposed to the clients. Such ``information hiding'' might be useful or
16073 necessary for various reasons.
16075 Stand-alone libraries are also well suited to be used in an executable whose
16076 main routine is not written in Ada.
16078 @node Building a Stand-alone Library
16079 @subsection Building a Stand-alone Library
16082 GNAT's Project facility provides a simple way of building and installing
16083 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16084 To be a Stand-alone Library Project, in addition to the two attributes
16085 that make a project a Library Project (@code{Library_Name} and
16086 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16087 @code{Library_Interface} must be defined. For example:
16089 @smallexample @c projectfile
16091 for Library_Dir use "lib_dir";
16092 for Library_Name use "dummy";
16093 for Library_Interface use ("int1", "int1.child");
16098 Attribute @code{Library_Interface} has a non-empty string list value,
16099 each string in the list designating a unit contained in an immediate source
16100 of the project file.
16102 When a Stand-alone Library is built, first the binder is invoked to build
16103 a package whose name depends on the library name
16104 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16105 This binder-generated package includes initialization and
16106 finalization procedures whose
16107 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16109 above). The object corresponding to this package is included in the library.
16111 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16112 calling of these procedures if a static SAL is built, or if a shared SAL
16114 with the project-level attribute @code{Library_Auto_Init} set to
16117 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16118 (those that are listed in attribute @code{Library_Interface}) are copied to
16119 the Library Directory. As a consequence, only the Interface Units may be
16120 imported from Ada units outside of the library. If other units are imported,
16121 the binding phase will fail.
16123 The attribute @code{Library_Src_Dir} may be specified for a
16124 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16125 single string value. Its value must be the path (absolute or relative to the
16126 project directory) of an existing directory. This directory cannot be the
16127 object directory or one of the source directories, but it can be the same as
16128 the library directory. The sources of the Interface
16129 Units of the library that are needed by an Ada client of the library will be
16130 copied to the designated directory, called the Interface Copy directory.
16131 These sources include the specs of the Interface Units, but they may also
16132 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16133 are used, or when there is a generic unit in the spec. Before the sources
16134 are copied to the Interface Copy directory, an attempt is made to delete all
16135 files in the Interface Copy directory.
16137 Building stand-alone libraries by hand is somewhat tedious, but for those
16138 occasions when it is necessary here are the steps that you need to perform:
16141 Compile all library sources.
16144 Invoke the binder with the switch @option{-n} (No Ada main program),
16145 with all the @file{ALI} files of the interfaces, and
16146 with the switch @option{-L} to give specific names to the @code{init}
16147 and @code{final} procedures. For example:
16149 gnatbind -n int1.ali int2.ali -Lsal1
16153 Compile the binder generated file:
16159 Link the dynamic library with all the necessary object files,
16160 indicating to the linker the names of the @code{init} (and possibly
16161 @code{final}) procedures for automatic initialization (and finalization).
16162 The built library should be placed in a directory different from
16163 the object directory.
16166 Copy the @code{ALI} files of the interface to the library directory,
16167 add in this copy an indication that it is an interface to a SAL
16168 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16169 with letter ``P'') and make the modified copy of the @file{ALI} file
16174 Using SALs is not different from using other libraries
16175 (see @ref{Using a library}).
16177 @node Creating a Stand-alone Library to be used in a non-Ada context
16178 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16181 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16184 The only extra step required is to ensure that library interface subprograms
16185 are compatible with the main program, by means of @code{pragma Export}
16186 or @code{pragma Convention}.
16188 Here is an example of simple library interface for use with C main program:
16190 @smallexample @c ada
16191 package My_Package is
16193 procedure Do_Something;
16194 pragma Export (C, Do_Something, "do_something");
16196 procedure Do_Something_Else;
16197 pragma Export (C, Do_Something_Else, "do_something_else");
16203 On the foreign language side, you must provide a ``foreign'' view of the
16204 library interface; remember that it should contain elaboration routines in
16205 addition to interface subprograms.
16207 The example below shows the content of @code{mylib_interface.h} (note
16208 that there is no rule for the naming of this file, any name can be used)
16210 /* the library elaboration procedure */
16211 extern void mylibinit (void);
16213 /* the library finalization procedure */
16214 extern void mylibfinal (void);
16216 /* the interface exported by the library */
16217 extern void do_something (void);
16218 extern void do_something_else (void);
16222 Libraries built as explained above can be used from any program, provided
16223 that the elaboration procedures (named @code{mylibinit} in the previous
16224 example) are called before the library services are used. Any number of
16225 libraries can be used simultaneously, as long as the elaboration
16226 procedure of each library is called.
16228 Below is an example of a C program that uses the @code{mylib} library.
16231 #include "mylib_interface.h"
16236 /* First, elaborate the library before using it */
16239 /* Main program, using the library exported entities */
16241 do_something_else ();
16243 /* Library finalization at the end of the program */
16250 Note that invoking any library finalization procedure generated by
16251 @code{gnatbind} shuts down the Ada run-time environment.
16253 finalization of all Ada libraries must be performed at the end of the program.
16254 No call to these libraries or to the Ada run-time library should be made
16255 after the finalization phase.
16257 @node Restrictions in Stand-alone Libraries
16258 @subsection Restrictions in Stand-alone Libraries
16261 The pragmas listed below should be used with caution inside libraries,
16262 as they can create incompatibilities with other Ada libraries:
16264 @item pragma @code{Locking_Policy}
16265 @item pragma @code{Queuing_Policy}
16266 @item pragma @code{Task_Dispatching_Policy}
16267 @item pragma @code{Unreserve_All_Interrupts}
16271 When using a library that contains such pragmas, the user must make sure
16272 that all libraries use the same pragmas with the same values. Otherwise,
16273 @code{Program_Error} will
16274 be raised during the elaboration of the conflicting
16275 libraries. The usage of these pragmas and its consequences for the user
16276 should therefore be well documented.
16278 Similarly, the traceback in the exception occurrence mechanism should be
16279 enabled or disabled in a consistent manner across all libraries.
16280 Otherwise, Program_Error will be raised during the elaboration of the
16281 conflicting libraries.
16283 If the @code{Version} or @code{Body_Version}
16284 attributes are used inside a library, then you need to
16285 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16286 libraries, so that version identifiers can be properly computed.
16287 In practice these attributes are rarely used, so this is unlikely
16288 to be a consideration.
16290 @node Rebuilding the GNAT Run-Time Library
16291 @section Rebuilding the GNAT Run-Time Library
16292 @cindex GNAT Run-Time Library, rebuilding
16293 @cindex Building the GNAT Run-Time Library
16294 @cindex Rebuilding the GNAT Run-Time Library
16295 @cindex Run-Time Library, rebuilding
16298 It may be useful to recompile the GNAT library in various contexts, the
16299 most important one being the use of partition-wide configuration pragmas
16300 such as @code{Normalize_Scalars}. A special Makefile called
16301 @code{Makefile.adalib} is provided to that effect and can be found in
16302 the directory containing the GNAT library. The location of this
16303 directory depends on the way the GNAT environment has been installed and can
16304 be determined by means of the command:
16311 The last entry in the object search path usually contains the
16312 gnat library. This Makefile contains its own documentation and in
16313 particular the set of instructions needed to rebuild a new library and
16316 @node Using the GNU make Utility
16317 @chapter Using the GNU @code{make} Utility
16321 This chapter offers some examples of makefiles that solve specific
16322 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16323 make, make, GNU @code{make}}), nor does it try to replace the
16324 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16326 All the examples in this section are specific to the GNU version of
16327 make. Although @command{make} is a standard utility, and the basic language
16328 is the same, these examples use some advanced features found only in
16332 * Using gnatmake in a Makefile::
16333 * Automatically Creating a List of Directories::
16334 * Generating the Command Line Switches::
16335 * Overcoming Command Line Length Limits::
16338 @node Using gnatmake in a Makefile
16339 @section Using gnatmake in a Makefile
16344 Complex project organizations can be handled in a very powerful way by
16345 using GNU make combined with gnatmake. For instance, here is a Makefile
16346 which allows you to build each subsystem of a big project into a separate
16347 shared library. Such a makefile allows you to significantly reduce the link
16348 time of very big applications while maintaining full coherence at
16349 each step of the build process.
16351 The list of dependencies are handled automatically by
16352 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16353 the appropriate directories.
16355 Note that you should also read the example on how to automatically
16356 create the list of directories
16357 (@pxref{Automatically Creating a List of Directories})
16358 which might help you in case your project has a lot of subdirectories.
16363 @font@heightrm=cmr8
16366 ## This Makefile is intended to be used with the following directory
16368 ## - The sources are split into a series of csc (computer software components)
16369 ## Each of these csc is put in its own directory.
16370 ## Their name are referenced by the directory names.
16371 ## They will be compiled into shared library (although this would also work
16372 ## with static libraries
16373 ## - The main program (and possibly other packages that do not belong to any
16374 ## csc is put in the top level directory (where the Makefile is).
16375 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16376 ## \_ second_csc (sources) __ lib (will contain the library)
16378 ## Although this Makefile is build for shared library, it is easy to modify
16379 ## to build partial link objects instead (modify the lines with -shared and
16382 ## With this makefile, you can change any file in the system or add any new
16383 ## file, and everything will be recompiled correctly (only the relevant shared
16384 ## objects will be recompiled, and the main program will be re-linked).
16386 # The list of computer software component for your project. This might be
16387 # generated automatically.
16390 # Name of the main program (no extension)
16393 # If we need to build objects with -fPIC, uncomment the following line
16396 # The following variable should give the directory containing libgnat.so
16397 # You can get this directory through 'gnatls -v'. This is usually the last
16398 # directory in the Object_Path.
16401 # The directories for the libraries
16402 # (This macro expands the list of CSC to the list of shared libraries, you
16403 # could simply use the expanded form:
16404 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16405 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16407 $@{MAIN@}: objects $@{LIB_DIR@}
16408 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16409 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16412 # recompile the sources
16413 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16415 # Note: In a future version of GNAT, the following commands will be simplified
16416 # by a new tool, gnatmlib
16418 mkdir -p $@{dir $@@ @}
16419 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16420 cd $@{dir $@@ @} && cp -f ../*.ali .
16422 # The dependencies for the modules
16423 # Note that we have to force the expansion of *.o, since in some cases
16424 # make won't be able to do it itself.
16425 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16426 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16427 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16429 # Make sure all of the shared libraries are in the path before starting the
16432 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16435 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16436 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16437 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16438 $@{RM@} *.o *.ali $@{MAIN@}
16441 @node Automatically Creating a List of Directories
16442 @section Automatically Creating a List of Directories
16445 In most makefiles, you will have to specify a list of directories, and
16446 store it in a variable. For small projects, it is often easier to
16447 specify each of them by hand, since you then have full control over what
16448 is the proper order for these directories, which ones should be
16451 However, in larger projects, which might involve hundreds of
16452 subdirectories, it might be more convenient to generate this list
16455 The example below presents two methods. The first one, although less
16456 general, gives you more control over the list. It involves wildcard
16457 characters, that are automatically expanded by @command{make}. Its
16458 shortcoming is that you need to explicitly specify some of the
16459 organization of your project, such as for instance the directory tree
16460 depth, whether some directories are found in a separate tree, @enddots{}
16462 The second method is the most general one. It requires an external
16463 program, called @command{find}, which is standard on all Unix systems. All
16464 the directories found under a given root directory will be added to the
16470 @font@heightrm=cmr8
16473 # The examples below are based on the following directory hierarchy:
16474 # All the directories can contain any number of files
16475 # ROOT_DIRECTORY -> a -> aa -> aaa
16478 # -> b -> ba -> baa
16481 # This Makefile creates a variable called DIRS, that can be reused any time
16482 # you need this list (see the other examples in this section)
16484 # The root of your project's directory hierarchy
16488 # First method: specify explicitly the list of directories
16489 # This allows you to specify any subset of all the directories you need.
16492 DIRS := a/aa/ a/ab/ b/ba/
16495 # Second method: use wildcards
16496 # Note that the argument(s) to wildcard below should end with a '/'.
16497 # Since wildcards also return file names, we have to filter them out
16498 # to avoid duplicate directory names.
16499 # We thus use make's @code{dir} and @code{sort} functions.
16500 # It sets DIRs to the following value (note that the directories aaa and baa
16501 # are not given, unless you change the arguments to wildcard).
16502 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16505 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16506 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16509 # Third method: use an external program
16510 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16511 # This is the most complete command: it sets DIRs to the following value:
16512 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16515 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16519 @node Generating the Command Line Switches
16520 @section Generating the Command Line Switches
16523 Once you have created the list of directories as explained in the
16524 previous section (@pxref{Automatically Creating a List of Directories}),
16525 you can easily generate the command line arguments to pass to gnatmake.
16527 For the sake of completeness, this example assumes that the source path
16528 is not the same as the object path, and that you have two separate lists
16532 # see "Automatically creating a list of directories" to create
16537 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16538 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16541 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16544 @node Overcoming Command Line Length Limits
16545 @section Overcoming Command Line Length Limits
16548 One problem that might be encountered on big projects is that many
16549 operating systems limit the length of the command line. It is thus hard to give
16550 gnatmake the list of source and object directories.
16552 This example shows how you can set up environment variables, which will
16553 make @command{gnatmake} behave exactly as if the directories had been
16554 specified on the command line, but have a much higher length limit (or
16555 even none on most systems).
16557 It assumes that you have created a list of directories in your Makefile,
16558 using one of the methods presented in
16559 @ref{Automatically Creating a List of Directories}.
16560 For the sake of completeness, we assume that the object
16561 path (where the ALI files are found) is different from the sources patch.
16563 Note a small trick in the Makefile below: for efficiency reasons, we
16564 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16565 expanded immediately by @code{make}. This way we overcome the standard
16566 make behavior which is to expand the variables only when they are
16569 On Windows, if you are using the standard Windows command shell, you must
16570 replace colons with semicolons in the assignments to these variables.
16575 @font@heightrm=cmr8
16578 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16579 # This is the same thing as putting the -I arguments on the command line.
16580 # (the equivalent of using -aI on the command line would be to define
16581 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16582 # You can of course have different values for these variables.
16584 # Note also that we need to keep the previous values of these variables, since
16585 # they might have been set before running 'make' to specify where the GNAT
16586 # library is installed.
16588 # see "Automatically creating a list of directories" to create these
16594 space:=$@{empty@} $@{empty@}
16595 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16596 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16597 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16598 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16599 export ADA_INCLUDE_PATH
16600 export ADA_OBJECTS_PATH
16607 @node Memory Management Issues
16608 @chapter Memory Management Issues
16611 This chapter describes some useful memory pools provided in the GNAT library
16612 and in particular the GNAT Debug Pool facility, which can be used to detect
16613 incorrect uses of access values (including ``dangling references'').
16615 It also describes the @command{gnatmem} tool, which can be used to track down
16620 * Some Useful Memory Pools::
16621 * The GNAT Debug Pool Facility::
16623 * The gnatmem Tool::
16627 @node Some Useful Memory Pools
16628 @section Some Useful Memory Pools
16629 @findex Memory Pool
16630 @cindex storage, pool
16633 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16634 storage pool. Allocations use the standard system call @code{malloc} while
16635 deallocations use the standard system call @code{free}. No reclamation is
16636 performed when the pool goes out of scope. For performance reasons, the
16637 standard default Ada allocators/deallocators do not use any explicit storage
16638 pools but if they did, they could use this storage pool without any change in
16639 behavior. That is why this storage pool is used when the user
16640 manages to make the default implicit allocator explicit as in this example:
16641 @smallexample @c ada
16642 type T1 is access Something;
16643 -- no Storage pool is defined for T2
16644 type T2 is access Something_Else;
16645 for T2'Storage_Pool use T1'Storage_Pool;
16646 -- the above is equivalent to
16647 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16651 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16652 pool. The allocation strategy is similar to @code{Pool_Local}'s
16653 except that the all
16654 storage allocated with this pool is reclaimed when the pool object goes out of
16655 scope. This pool provides a explicit mechanism similar to the implicit one
16656 provided by several Ada 83 compilers for allocations performed through a local
16657 access type and whose purpose was to reclaim memory when exiting the
16658 scope of a given local access. As an example, the following program does not
16659 leak memory even though it does not perform explicit deallocation:
16661 @smallexample @c ada
16662 with System.Pool_Local;
16663 procedure Pooloc1 is
16664 procedure Internal is
16665 type A is access Integer;
16666 X : System.Pool_Local.Unbounded_Reclaim_Pool;
16667 for A'Storage_Pool use X;
16670 for I in 1 .. 50 loop
16675 for I in 1 .. 100 loop
16682 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16683 @code{Storage_Size} is specified for an access type.
16684 The whole storage for the pool is
16685 allocated at once, usually on the stack at the point where the access type is
16686 elaborated. It is automatically reclaimed when exiting the scope where the
16687 access type is defined. This package is not intended to be used directly by the
16688 user and it is implicitly used for each such declaration:
16690 @smallexample @c ada
16691 type T1 is access Something;
16692 for T1'Storage_Size use 10_000;
16695 @node The GNAT Debug Pool Facility
16696 @section The GNAT Debug Pool Facility
16698 @cindex storage, pool, memory corruption
16701 The use of unchecked deallocation and unchecked conversion can easily
16702 lead to incorrect memory references. The problems generated by such
16703 references are usually difficult to tackle because the symptoms can be
16704 very remote from the origin of the problem. In such cases, it is
16705 very helpful to detect the problem as early as possible. This is the
16706 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16708 In order to use the GNAT specific debugging pool, the user must
16709 associate a debug pool object with each of the access types that may be
16710 related to suspected memory problems. See Ada Reference Manual 13.11.
16711 @smallexample @c ada
16712 type Ptr is access Some_Type;
16713 Pool : GNAT.Debug_Pools.Debug_Pool;
16714 for Ptr'Storage_Pool use Pool;
16718 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16719 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16720 allow the user to redefine allocation and deallocation strategies. They
16721 also provide a checkpoint for each dereference, through the use of
16722 the primitive operation @code{Dereference} which is implicitly called at
16723 each dereference of an access value.
16725 Once an access type has been associated with a debug pool, operations on
16726 values of the type may raise four distinct exceptions,
16727 which correspond to four potential kinds of memory corruption:
16730 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16732 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16734 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16736 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16740 For types associated with a Debug_Pool, dynamic allocation is performed using
16741 the standard GNAT allocation routine. References to all allocated chunks of
16742 memory are kept in an internal dictionary. Several deallocation strategies are
16743 provided, whereupon the user can choose to release the memory to the system,
16744 keep it allocated for further invalid access checks, or fill it with an easily
16745 recognizable pattern for debug sessions. The memory pattern is the old IBM
16746 hexadecimal convention: @code{16#DEADBEEF#}.
16748 See the documentation in the file g-debpoo.ads for more information on the
16749 various strategies.
16751 Upon each dereference, a check is made that the access value denotes a
16752 properly allocated memory location. Here is a complete example of use of
16753 @code{Debug_Pools}, that includes typical instances of memory corruption:
16754 @smallexample @c ada
16758 with Gnat.Io; use Gnat.Io;
16759 with Unchecked_Deallocation;
16760 with Unchecked_Conversion;
16761 with GNAT.Debug_Pools;
16762 with System.Storage_Elements;
16763 with Ada.Exceptions; use Ada.Exceptions;
16764 procedure Debug_Pool_Test is
16766 type T is access Integer;
16767 type U is access all T;
16769 P : GNAT.Debug_Pools.Debug_Pool;
16770 for T'Storage_Pool use P;
16772 procedure Free is new Unchecked_Deallocation (Integer, T);
16773 function UC is new Unchecked_Conversion (U, T);
16776 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16786 Put_Line (Integer'Image(B.all));
16788 when E : others => Put_Line ("raised: " & Exception_Name (E));
16793 when E : others => Put_Line ("raised: " & Exception_Name (E));
16797 Put_Line (Integer'Image(B.all));
16799 when E : others => Put_Line ("raised: " & Exception_Name (E));
16804 when E : others => Put_Line ("raised: " & Exception_Name (E));
16807 end Debug_Pool_Test;
16811 The debug pool mechanism provides the following precise diagnostics on the
16812 execution of this erroneous program:
16815 Total allocated bytes : 0
16816 Total deallocated bytes : 0
16817 Current Water Mark: 0
16821 Total allocated bytes : 8
16822 Total deallocated bytes : 0
16823 Current Water Mark: 8
16826 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16827 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16828 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16829 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16831 Total allocated bytes : 8
16832 Total deallocated bytes : 4
16833 Current Water Mark: 4
16838 @node The gnatmem Tool
16839 @section The @command{gnatmem} Tool
16843 The @code{gnatmem} utility monitors dynamic allocation and
16844 deallocation activity in a program, and displays information about
16845 incorrect deallocations and possible sources of memory leaks.
16846 It is designed to work in association with a static runtime library
16847 only and in this context provides three types of information:
16850 General information concerning memory management, such as the total
16851 number of allocations and deallocations, the amount of allocated
16852 memory and the high water mark, i.e.@: the largest amount of allocated
16853 memory in the course of program execution.
16856 Backtraces for all incorrect deallocations, that is to say deallocations
16857 which do not correspond to a valid allocation.
16860 Information on each allocation that is potentially the origin of a memory
16865 * Running gnatmem::
16866 * Switches for gnatmem::
16867 * Example of gnatmem Usage::
16870 @node Running gnatmem
16871 @subsection Running @code{gnatmem}
16874 @code{gnatmem} makes use of the output created by the special version of
16875 allocation and deallocation routines that record call information. This
16876 allows to obtain accurate dynamic memory usage history at a minimal cost to
16877 the execution speed. Note however, that @code{gnatmem} is not supported on
16878 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16879 Solaris and Windows NT/2000/XP (x86).
16882 The @code{gnatmem} command has the form
16885 @c $ gnatmem @ovar{switches} user_program
16886 @c Expanding @ovar macro inline (explanation in macro def comments)
16887 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16891 The program must have been linked with the instrumented version of the
16892 allocation and deallocation routines. This is done by linking with the
16893 @file{libgmem.a} library. For correct symbolic backtrace information,
16894 the user program should be compiled with debugging options
16895 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16898 $ gnatmake -g my_program -largs -lgmem
16902 As library @file{libgmem.a} contains an alternate body for package
16903 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16904 when an executable is linked with library @file{libgmem.a}. It is then not
16905 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16908 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16909 This file contains information about all allocations and deallocations
16910 performed by the program. It is produced by the instrumented allocations and
16911 deallocations routines and will be used by @code{gnatmem}.
16913 In order to produce symbolic backtrace information for allocations and
16914 deallocations performed by the GNAT run-time library, you need to use a
16915 version of that library that has been compiled with the @option{-g} switch
16916 (see @ref{Rebuilding the GNAT Run-Time Library}).
16918 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16919 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16920 @option{-i} switch, gnatmem will assume that this file can be found in the
16921 current directory. For example, after you have executed @file{my_program},
16922 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16925 $ gnatmem my_program
16929 This will produce the output with the following format:
16931 *************** debut cc
16933 $ gnatmem my_program
16937 Total number of allocations : 45
16938 Total number of deallocations : 6
16939 Final Water Mark (non freed mem) : 11.29 Kilobytes
16940 High Water Mark : 11.40 Kilobytes
16945 Allocation Root # 2
16946 -------------------
16947 Number of non freed allocations : 11
16948 Final Water Mark (non freed mem) : 1.16 Kilobytes
16949 High Water Mark : 1.27 Kilobytes
16951 my_program.adb:23 my_program.alloc
16957 The first block of output gives general information. In this case, the
16958 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16959 Unchecked_Deallocation routine occurred.
16962 Subsequent paragraphs display information on all allocation roots.
16963 An allocation root is a specific point in the execution of the program
16964 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16965 construct. This root is represented by an execution backtrace (or subprogram
16966 call stack). By default the backtrace depth for allocations roots is 1, so
16967 that a root corresponds exactly to a source location. The backtrace can
16968 be made deeper, to make the root more specific.
16970 @node Switches for gnatmem
16971 @subsection Switches for @code{gnatmem}
16974 @code{gnatmem} recognizes the following switches:
16979 @cindex @option{-q} (@code{gnatmem})
16980 Quiet. Gives the minimum output needed to identify the origin of the
16981 memory leaks. Omits statistical information.
16984 @cindex @var{N} (@code{gnatmem})
16985 N is an integer literal (usually between 1 and 10) which controls the
16986 depth of the backtraces defining allocation root. The default value for
16987 N is 1. The deeper the backtrace, the more precise the localization of
16988 the root. Note that the total number of roots can depend on this
16989 parameter. This parameter must be specified @emph{before} the name of the
16990 executable to be analyzed, to avoid ambiguity.
16993 @cindex @option{-b} (@code{gnatmem})
16994 This switch has the same effect as just depth parameter.
16996 @item -i @var{file}
16997 @cindex @option{-i} (@code{gnatmem})
16998 Do the @code{gnatmem} processing starting from @file{file}, rather than
16999 @file{gmem.out} in the current directory.
17002 @cindex @option{-m} (@code{gnatmem})
17003 This switch causes @code{gnatmem} to mask the allocation roots that have less
17004 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17005 examine even the roots that didn't result in leaks.
17008 @cindex @option{-s} (@code{gnatmem})
17009 This switch causes @code{gnatmem} to sort the allocation roots according to the
17010 specified order of sort criteria, each identified by a single letter. The
17011 currently supported criteria are @code{n, h, w} standing respectively for
17012 number of unfreed allocations, high watermark, and final watermark
17013 corresponding to a specific root. The default order is @code{nwh}.
17017 @node Example of gnatmem Usage
17018 @subsection Example of @code{gnatmem} Usage
17021 The following example shows the use of @code{gnatmem}
17022 on a simple memory-leaking program.
17023 Suppose that we have the following Ada program:
17025 @smallexample @c ada
17028 with Unchecked_Deallocation;
17029 procedure Test_Gm is
17031 type T is array (1..1000) of Integer;
17032 type Ptr is access T;
17033 procedure Free is new Unchecked_Deallocation (T, Ptr);
17036 procedure My_Alloc is
17041 procedure My_DeAlloc is
17049 for I in 1 .. 5 loop
17050 for J in I .. 5 loop
17061 The program needs to be compiled with debugging option and linked with
17062 @code{gmem} library:
17065 $ gnatmake -g test_gm -largs -lgmem
17069 Then we execute the program as usual:
17076 Then @code{gnatmem} is invoked simply with
17082 which produces the following output (result may vary on different platforms):
17087 Total number of allocations : 18
17088 Total number of deallocations : 5
17089 Final Water Mark (non freed mem) : 53.00 Kilobytes
17090 High Water Mark : 56.90 Kilobytes
17092 Allocation Root # 1
17093 -------------------
17094 Number of non freed allocations : 11
17095 Final Water Mark (non freed mem) : 42.97 Kilobytes
17096 High Water Mark : 46.88 Kilobytes
17098 test_gm.adb:11 test_gm.my_alloc
17100 Allocation Root # 2
17101 -------------------
17102 Number of non freed allocations : 1
17103 Final Water Mark (non freed mem) : 10.02 Kilobytes
17104 High Water Mark : 10.02 Kilobytes
17106 s-secsta.adb:81 system.secondary_stack.ss_init
17108 Allocation Root # 3
17109 -------------------
17110 Number of non freed allocations : 1
17111 Final Water Mark (non freed mem) : 12 Bytes
17112 High Water Mark : 12 Bytes
17114 s-secsta.adb:181 system.secondary_stack.ss_init
17118 Note that the GNAT run time contains itself a certain number of
17119 allocations that have no corresponding deallocation,
17120 as shown here for root #2 and root
17121 #3. This is a normal behavior when the number of non-freed allocations
17122 is one, it allocates dynamic data structures that the run time needs for
17123 the complete lifetime of the program. Note also that there is only one
17124 allocation root in the user program with a single line back trace:
17125 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17126 program shows that 'My_Alloc' is called at 2 different points in the
17127 source (line 21 and line 24). If those two allocation roots need to be
17128 distinguished, the backtrace depth parameter can be used:
17131 $ gnatmem 3 test_gm
17135 which will give the following output:
17140 Total number of allocations : 18
17141 Total number of deallocations : 5
17142 Final Water Mark (non freed mem) : 53.00 Kilobytes
17143 High Water Mark : 56.90 Kilobytes
17145 Allocation Root # 1
17146 -------------------
17147 Number of non freed allocations : 10
17148 Final Water Mark (non freed mem) : 39.06 Kilobytes
17149 High Water Mark : 42.97 Kilobytes
17151 test_gm.adb:11 test_gm.my_alloc
17152 test_gm.adb:24 test_gm
17153 b_test_gm.c:52 main
17155 Allocation Root # 2
17156 -------------------
17157 Number of non freed allocations : 1
17158 Final Water Mark (non freed mem) : 10.02 Kilobytes
17159 High Water Mark : 10.02 Kilobytes
17161 s-secsta.adb:81 system.secondary_stack.ss_init
17162 s-secsta.adb:283 <system__secondary_stack___elabb>
17163 b_test_gm.c:33 adainit
17165 Allocation Root # 3
17166 -------------------
17167 Number of non freed allocations : 1
17168 Final Water Mark (non freed mem) : 3.91 Kilobytes
17169 High Water Mark : 3.91 Kilobytes
17171 test_gm.adb:11 test_gm.my_alloc
17172 test_gm.adb:21 test_gm
17173 b_test_gm.c:52 main
17175 Allocation Root # 4
17176 -------------------
17177 Number of non freed allocations : 1
17178 Final Water Mark (non freed mem) : 12 Bytes
17179 High Water Mark : 12 Bytes
17181 s-secsta.adb:181 system.secondary_stack.ss_init
17182 s-secsta.adb:283 <system__secondary_stack___elabb>
17183 b_test_gm.c:33 adainit
17187 The allocation root #1 of the first example has been split in 2 roots #1
17188 and #3 thanks to the more precise associated backtrace.
17192 @node Stack Related Facilities
17193 @chapter Stack Related Facilities
17196 This chapter describes some useful tools associated with stack
17197 checking and analysis. In
17198 particular, it deals with dynamic and static stack usage measurements.
17201 * Stack Overflow Checking::
17202 * Static Stack Usage Analysis::
17203 * Dynamic Stack Usage Analysis::
17206 @node Stack Overflow Checking
17207 @section Stack Overflow Checking
17208 @cindex Stack Overflow Checking
17209 @cindex -fstack-check
17212 For most operating systems, @command{gcc} does not perform stack overflow
17213 checking by default. This means that if the main environment task or
17214 some other task exceeds the available stack space, then unpredictable
17215 behavior will occur. Most native systems offer some level of protection by
17216 adding a guard page at the end of each task stack. This mechanism is usually
17217 not enough for dealing properly with stack overflow situations because
17218 a large local variable could ``jump'' above the guard page.
17219 Furthermore, when the
17220 guard page is hit, there may not be any space left on the stack for executing
17221 the exception propagation code. Enabling stack checking avoids
17224 To activate stack checking, compile all units with the gcc option
17225 @option{-fstack-check}. For example:
17228 gcc -c -fstack-check package1.adb
17232 Units compiled with this option will generate extra instructions to check
17233 that any use of the stack (for procedure calls or for declaring local
17234 variables in declare blocks) does not exceed the available stack space.
17235 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17237 For declared tasks, the stack size is controlled by the size
17238 given in an applicable @code{Storage_Size} pragma or by the value specified
17239 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17240 the default size as defined in the GNAT runtime otherwise.
17242 For the environment task, the stack size depends on
17243 system defaults and is unknown to the compiler. Stack checking
17244 may still work correctly if a fixed
17245 size stack is allocated, but this cannot be guaranteed.
17247 To ensure that a clean exception is signalled for stack
17248 overflow, set the environment variable
17249 @env{GNAT_STACK_LIMIT} to indicate the maximum
17250 stack area that can be used, as in:
17251 @cindex GNAT_STACK_LIMIT
17254 SET GNAT_STACK_LIMIT 1600
17258 The limit is given in kilobytes, so the above declaration would
17259 set the stack limit of the environment task to 1.6 megabytes.
17260 Note that the only purpose of this usage is to limit the amount
17261 of stack used by the environment task. If it is necessary to
17262 increase the amount of stack for the environment task, then this
17263 is an operating systems issue, and must be addressed with the
17264 appropriate operating systems commands.
17267 To have a fixed size stack in the environment task, the stack must be put
17268 in the P0 address space and its size specified. Use these switches to
17272 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17276 The quotes are required to keep case. The number after @samp{STACK=} is the
17277 size of the environmental task stack in pagelets (512 bytes). In this example
17278 the stack size is about 2 megabytes.
17281 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17282 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
17283 more details about the @option{/p0image} qualifier and the @option{stack}
17287 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17288 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17289 stack in kilobytes. For example:
17292 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17296 @node Static Stack Usage Analysis
17297 @section Static Stack Usage Analysis
17298 @cindex Static Stack Usage Analysis
17299 @cindex -fstack-usage
17302 A unit compiled with @option{-fstack-usage} will generate an extra file
17304 the maximum amount of stack used, on a per-function basis.
17305 The file has the same
17306 basename as the target object file with a @file{.su} extension.
17307 Each line of this file is made up of three fields:
17311 The name of the function.
17315 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17318 The second field corresponds to the size of the known part of the function
17321 The qualifier @code{static} means that the function frame size
17323 It usually means that all local variables have a static size.
17324 In this case, the second field is a reliable measure of the function stack
17327 The qualifier @code{dynamic} means that the function frame size is not static.
17328 It happens mainly when some local variables have a dynamic size. When this
17329 qualifier appears alone, the second field is not a reliable measure
17330 of the function stack analysis. When it is qualified with @code{bounded}, it
17331 means that the second field is a reliable maximum of the function stack
17334 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17335 subprogram whose stack usage might be larger than the specified amount of
17336 bytes. The wording is in keeping with the qualifier documented above.
17338 @node Dynamic Stack Usage Analysis
17339 @section Dynamic Stack Usage Analysis
17342 It is possible to measure the maximum amount of stack used by a task, by
17343 adding a switch to @command{gnatbind}, as:
17346 $ gnatbind -u0 file
17350 With this option, at each task termination, its stack usage is output on
17352 It is not always convenient to output the stack usage when the program
17353 is still running. Hence, it is possible to delay this output until program
17354 termination. for a given number of tasks specified as the argument of the
17355 @option{-u} option. For instance:
17358 $ gnatbind -u100 file
17362 will buffer the stack usage information of the first 100 tasks to terminate and
17363 output this info at program termination. Results are displayed in four
17367 Index | Task Name | Stack Size | Stack Usage
17374 is a number associated with each task.
17377 is the name of the task analyzed.
17380 is the maximum size for the stack.
17383 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17384 is not entirely analyzed, and it's not possible to know exactly how
17385 much has actually been used.
17390 The environment task stack, e.g., the stack that contains the main unit, is
17391 only processed when the environment variable GNAT_STACK_LIMIT is set.
17394 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17395 stack usage reports at run-time. See its body for the details.
17397 @c *********************************
17399 @c *********************************
17400 @node Verifying Properties Using gnatcheck
17401 @chapter Verifying Properties Using @command{gnatcheck}
17403 @cindex @command{gnatcheck}
17406 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17407 of Ada source files according to a given set of semantic rules.
17410 In order to check compliance with a given rule, @command{gnatcheck} has to
17411 semantically analyze the Ada sources.
17412 Therefore, checks can only be performed on
17413 legal Ada units. Moreover, when a unit depends semantically upon units located
17414 outside the current directory, the source search path has to be provided when
17415 calling @command{gnatcheck}, either through a specified project file or
17416 through @command{gnatcheck} switches.
17418 For full details, refer to @cite{GNATcheck Reference Manual} document.
17421 @c *********************************
17422 @node Creating Sample Bodies Using gnatstub
17423 @chapter Creating Sample Bodies Using @command{gnatstub}
17427 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17428 for library unit declarations.
17430 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17431 driver (see @ref{The GNAT Driver and Project Files}).
17433 To create a body stub, @command{gnatstub} has to compile the library
17434 unit declaration. Therefore, bodies can be created only for legal
17435 library units. Moreover, if a library unit depends semantically upon
17436 units located outside the current directory, you have to provide
17437 the source search path when calling @command{gnatstub}, see the description
17438 of @command{gnatstub} switches below.
17440 By default, all the program unit body stubs generated by @code{gnatstub}
17441 raise the predefined @code{Program_Error} exception, which will catch
17442 accidental calls of generated stubs. This behavior can be changed with
17443 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17446 * Running gnatstub::
17447 * Switches for gnatstub::
17450 @node Running gnatstub
17451 @section Running @command{gnatstub}
17454 @command{gnatstub} has the command-line interface of the form
17457 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17458 @c Expanding @ovar macro inline (explanation in macro def comments)
17459 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17466 is the name of the source file that contains a library unit declaration
17467 for which a body must be created. The file name may contain the path
17469 The file name does not have to follow the GNAT file name conventions. If the
17471 does not follow GNAT file naming conventions, the name of the body file must
17473 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17474 If the file name follows the GNAT file naming
17475 conventions and the name of the body file is not provided,
17478 of the body file from the argument file name by replacing the @file{.ads}
17480 with the @file{.adb} suffix.
17483 indicates the directory in which the body stub is to be placed (the default
17487 @item @samp{@var{gcc_switches}} is a list of switches for
17488 @command{gcc}. They will be passed on to all compiler invocations made by
17489 @command{gnatelim} to generate the ASIS trees. Here you can provide
17490 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17491 use the @option{-gnatec} switch to set the configuration file,
17492 use the @option{-gnat05} switch if sources should be compiled in
17496 is an optional sequence of switches as described in the next section
17499 @node Switches for gnatstub
17500 @section Switches for @command{gnatstub}
17506 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17507 If the destination directory already contains a file with the name of the
17509 for the argument spec file, replace it with the generated body stub.
17511 @item ^-hs^/HEADER=SPEC^
17512 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17513 Put the comment header (i.e., all the comments preceding the
17514 compilation unit) from the source of the library unit declaration
17515 into the body stub.
17517 @item ^-hg^/HEADER=GENERAL^
17518 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17519 Put a sample comment header into the body stub.
17521 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17522 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17523 Use the content of the file as the comment header for a generated body stub.
17527 @cindex @option{-IDIR} (@command{gnatstub})
17529 @cindex @option{-I-} (@command{gnatstub})
17532 @item /NOCURRENT_DIRECTORY
17533 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17535 ^These switches have ^This switch has^ the same meaning as in calls to
17537 ^They define ^It defines ^ the source search path in the call to
17538 @command{gcc} issued
17539 by @command{gnatstub} to compile an argument source file.
17541 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17542 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17543 This switch has the same meaning as in calls to @command{gcc}.
17544 It defines the additional configuration file to be passed to the call to
17545 @command{gcc} issued
17546 by @command{gnatstub} to compile an argument source file.
17548 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17549 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17550 (@var{n} is a non-negative integer). Set the maximum line length in the
17551 body stub to @var{n}; the default is 79. The maximum value that can be
17552 specified is 32767. Note that in the special case of configuration
17553 pragma files, the maximum is always 32767 regardless of whether or
17554 not this switch appears.
17556 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17557 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17558 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17559 the generated body sample to @var{n}.
17560 The default indentation is 3.
17562 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17563 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17564 Order local bodies alphabetically. (By default local bodies are ordered
17565 in the same way as the corresponding local specs in the argument spec file.)
17567 @item ^-i^/INDENTATION=^@var{n}
17568 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17569 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17571 @item ^-k^/TREE_FILE=SAVE^
17572 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17573 Do not remove the tree file (i.e., the snapshot of the compiler internal
17574 structures used by @command{gnatstub}) after creating the body stub.
17576 @item ^-l^/LINE_LENGTH=^@var{n}
17577 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17578 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17580 @item ^--no-exception^/NO_EXCEPTION^
17581 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17582 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17583 This is not always possible for function stubs.
17585 @item ^--no-local-header^/NO_LOCAL_HEADER^
17586 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17587 Do not place local comment header with unit name before body stub for a
17590 @item ^-o ^/BODY=^@var{body-name}
17591 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17592 Body file name. This should be set if the argument file name does not
17594 the GNAT file naming
17595 conventions. If this switch is omitted the default name for the body will be
17597 from the argument file name according to the GNAT file naming conventions.
17600 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17601 Quiet mode: do not generate a confirmation when a body is
17602 successfully created, and do not generate a message when a body is not
17606 @item ^-r^/TREE_FILE=REUSE^
17607 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17608 Reuse the tree file (if it exists) instead of creating it. Instead of
17609 creating the tree file for the library unit declaration, @command{gnatstub}
17610 tries to find it in the current directory and use it for creating
17611 a body. If the tree file is not found, no body is created. This option
17612 also implies @option{^-k^/SAVE^}, whether or not
17613 the latter is set explicitly.
17615 @item ^-t^/TREE_FILE=OVERWRITE^
17616 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17617 Overwrite the existing tree file. If the current directory already
17618 contains the file which, according to the GNAT file naming rules should
17619 be considered as a tree file for the argument source file,
17621 will refuse to create the tree file needed to create a sample body
17622 unless this option is set.
17624 @item ^-v^/VERBOSE^
17625 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17626 Verbose mode: generate version information.
17630 @c *********************************
17631 @node Generating Ada Bindings for C and C++ headers
17632 @chapter Generating Ada Bindings for C and C++ headers
17636 GNAT now comes with a binding generator for C and C++ headers which is
17637 intended to do 95% of the tedious work of generating Ada specs from C
17638 or C++ header files.
17640 Note that this capability is not intended to generate 100% correct Ada specs,
17641 and will is some cases require manual adjustments, although it can often
17642 be used out of the box in practice.
17644 Some of the known limitations include:
17647 @item only very simple character constant macros are translated into Ada
17648 constants. Function macros (macros with arguments) are partially translated
17649 as comments, to be completed manually if needed.
17650 @item some extensions (e.g. vector types) are not supported
17651 @item pointers to pointers or complex structures are mapped to System.Address
17652 @item identifiers with identical name (except casing) will generate compilation
17653 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
17656 The code generated is using the Ada 2005 syntax, which makes it
17657 easier to interface with other languages than previous versions of Ada.
17660 * Running the binding generator::
17661 * Generating bindings for C++ headers::
17665 @node Running the binding generator
17666 @section Running the binding generator
17669 The binding generator is part of the @command{gcc} compiler and can be
17670 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
17671 spec files for the header files specified on the command line, and all
17672 header files needed by these files transitively. For example:
17675 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
17676 $ gcc -c -gnat05 *.ads
17679 will generate, under GNU/Linux, the following files: @file{time_h.ads},
17680 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
17681 correspond to the files @file{/usr/include/time.h},
17682 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
17683 mode these Ada specs.
17685 The @code{-C} switch tells @command{gcc} to extract comments from headers,
17686 and will attempt to generate corresponding Ada comments.
17688 If you want to generate a single Ada file and not the transitive closure, you
17689 can use instead the @option{-fdump-ada-spec-slim} switch.
17691 Note that we recommend when possible to use the @command{g++} driver to
17692 generate bindings, even for most C headers, since this will in general
17693 generate better Ada specs. For generating bindings for C++ headers, it is
17694 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
17695 is equivalent in this case. If @command{g++} cannot work on your C headers
17696 because of incompatibilities between C and C++, then you can fallback to
17697 @command{gcc} instead.
17699 For an example of better bindings generated from the C++ front-end,
17700 the name of the parameters (when available) are actually ignored by the C
17701 front-end. Consider the following C header:
17704 extern void foo (int variable);
17707 with the C front-end, @code{variable} is ignored, and the above is handled as:
17710 extern void foo (int);
17713 generating a generic:
17716 procedure foo (param1 : int);
17719 with the C++ front-end, the name is available, and we generate:
17722 procedure foo (variable : int);
17725 In some cases, the generated bindings will be more complete or more meaningful
17726 when defining some macros, which you can do via the @option{-D} switch. This
17727 is for example the case with @file{Xlib.h} under GNU/Linux:
17730 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
17733 The above will generate more complete bindings than a straight call without
17734 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
17736 In other cases, it is not possible to parse a header file in a stand alone
17737 manner, because other include files need to be included first. In this
17738 case, the solution is to create a small header file including the needed
17739 @code{#include} and possible @code{#define} directives. For example, to
17740 generate Ada bindings for @file{readline/readline.h}, you need to first
17741 include @file{stdio.h}, so you can create a file with the following two
17742 lines in e.g. @file{readline1.h}:
17746 #include <readline/readline.h>
17749 and then generate Ada bindings from this file:
17752 $ g++ -c -fdump-ada-spec readline1.h
17755 @node Generating bindings for C++ headers
17756 @section Generating bindings for C++ headers
17759 Generating bindings for C++ headers is done using the same options, always
17760 with the @command{g++} compiler.
17762 In this mode, C++ classes will be mapped to Ada tagged types, constructors
17763 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
17764 multiple inheritance of abstract classes will be mapped to Ada interfaces
17765 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
17766 information on interfacing to C++).
17768 For example, given the following C++ header file:
17775 virtual int Number_Of_Teeth () = 0;
17780 virtual void Set_Owner (char* Name) = 0;
17786 virtual void Set_Age (int New_Age);
17789 class Dog : Animal, Carnivore, Domestic @{
17794 virtual int Number_Of_Teeth ();
17795 virtual void Set_Owner (char* Name);
17803 The corresponding Ada code is generated:
17805 @smallexample @c ada
17808 package Class_Carnivore is
17809 type Carnivore is limited interface;
17810 pragma Import (CPP, Carnivore);
17812 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
17814 use Class_Carnivore;
17816 package Class_Domestic is
17817 type Domestic is limited interface;
17818 pragma Import (CPP, Domestic);
17820 procedure Set_Owner
17821 (this : access Domestic;
17822 Name : Interfaces.C.Strings.chars_ptr) is abstract;
17824 use Class_Domestic;
17826 package Class_Animal is
17827 type Animal is tagged limited record
17828 Age_Count : aliased int;
17830 pragma Import (CPP, Animal);
17832 procedure Set_Age (this : access Animal; New_Age : int);
17833 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
17837 package Class_Dog is
17838 type Dog is new Animal and Carnivore and Domestic with record
17839 Tooth_Count : aliased int;
17840 Owner : Interfaces.C.Strings.chars_ptr;
17842 pragma Import (CPP, Dog);
17844 function Number_Of_Teeth (this : access Dog) return int;
17845 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
17847 procedure Set_Owner
17848 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
17849 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
17851 function New_Dog return Dog;
17852 pragma CPP_Constructor (New_Dog);
17853 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
17864 @item -fdump-ada-spec
17865 @cindex @option{-fdump-ada-spec} (@command{gcc})
17866 Generate Ada spec files for the given header files transitively (including
17867 all header files that these headers depend upon).
17869 @item -fdump-ada-spec-slim
17870 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
17871 Generate Ada spec files for the header files specified on the command line
17875 @cindex @option{-C} (@command{gcc})
17876 Extract comments from headers and generate Ada comments in the Ada spec files.
17879 @node Other Utility Programs
17880 @chapter Other Utility Programs
17883 This chapter discusses some other utility programs available in the Ada
17887 * Using Other Utility Programs with GNAT::
17888 * The External Symbol Naming Scheme of GNAT::
17889 * Converting Ada Files to html with gnathtml::
17890 * Installing gnathtml::
17897 @node Using Other Utility Programs with GNAT
17898 @section Using Other Utility Programs with GNAT
17901 The object files generated by GNAT are in standard system format and in
17902 particular the debugging information uses this format. This means
17903 programs generated by GNAT can be used with existing utilities that
17904 depend on these formats.
17907 In general, any utility program that works with C will also often work with
17908 Ada programs generated by GNAT. This includes software utilities such as
17909 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17913 @node The External Symbol Naming Scheme of GNAT
17914 @section The External Symbol Naming Scheme of GNAT
17917 In order to interpret the output from GNAT, when using tools that are
17918 originally intended for use with other languages, it is useful to
17919 understand the conventions used to generate link names from the Ada
17922 All link names are in all lowercase letters. With the exception of library
17923 procedure names, the mechanism used is simply to use the full expanded
17924 Ada name with dots replaced by double underscores. For example, suppose
17925 we have the following package spec:
17927 @smallexample @c ada
17938 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17939 the corresponding link name is @code{qrs__mn}.
17941 Of course if a @code{pragma Export} is used this may be overridden:
17943 @smallexample @c ada
17948 pragma Export (Var1, C, External_Name => "var1_name");
17950 pragma Export (Var2, C, Link_Name => "var2_link_name");
17957 In this case, the link name for @var{Var1} is whatever link name the
17958 C compiler would assign for the C function @var{var1_name}. This typically
17959 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17960 system conventions, but other possibilities exist. The link name for
17961 @var{Var2} is @var{var2_link_name}, and this is not operating system
17965 One exception occurs for library level procedures. A potential ambiguity
17966 arises between the required name @code{_main} for the C main program,
17967 and the name we would otherwise assign to an Ada library level procedure
17968 called @code{Main} (which might well not be the main program).
17970 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17971 names. So if we have a library level procedure such as
17973 @smallexample @c ada
17976 procedure Hello (S : String);
17982 the external name of this procedure will be @var{_ada_hello}.
17985 @node Converting Ada Files to html with gnathtml
17986 @section Converting Ada Files to HTML with @code{gnathtml}
17989 This @code{Perl} script allows Ada source files to be browsed using
17990 standard Web browsers. For installation procedure, see the section
17991 @xref{Installing gnathtml}.
17993 Ada reserved keywords are highlighted in a bold font and Ada comments in
17994 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17995 switch to suppress the generation of cross-referencing information, user
17996 defined variables and types will appear in a different color; you will
17997 be able to click on any identifier and go to its declaration.
17999 The command line is as follow:
18001 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18002 @c Expanding @ovar macro inline (explanation in macro def comments)
18003 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18007 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18008 an html file for every ada file, and a global file called @file{index.htm}.
18009 This file is an index of every identifier defined in the files.
18011 The available ^switches^options^ are the following ones:
18015 @cindex @option{-83} (@code{gnathtml})
18016 Only the Ada 83 subset of keywords will be highlighted.
18018 @item -cc @var{color}
18019 @cindex @option{-cc} (@code{gnathtml})
18020 This option allows you to change the color used for comments. The default
18021 value is green. The color argument can be any name accepted by html.
18024 @cindex @option{-d} (@code{gnathtml})
18025 If the Ada files depend on some other files (for instance through
18026 @code{with} clauses, the latter files will also be converted to html.
18027 Only the files in the user project will be converted to html, not the files
18028 in the run-time library itself.
18031 @cindex @option{-D} (@code{gnathtml})
18032 This command is the same as @option{-d} above, but @command{gnathtml} will
18033 also look for files in the run-time library, and generate html files for them.
18035 @item -ext @var{extension}
18036 @cindex @option{-ext} (@code{gnathtml})
18037 This option allows you to change the extension of the generated HTML files.
18038 If you do not specify an extension, it will default to @file{htm}.
18041 @cindex @option{-f} (@code{gnathtml})
18042 By default, gnathtml will generate html links only for global entities
18043 ('with'ed units, global variables and types,@dots{}). If you specify
18044 @option{-f} on the command line, then links will be generated for local
18047 @item -l @var{number}
18048 @cindex @option{-l} (@code{gnathtml})
18049 If this ^switch^option^ is provided and @var{number} is not 0, then
18050 @code{gnathtml} will number the html files every @var{number} line.
18053 @cindex @option{-I} (@code{gnathtml})
18054 Specify a directory to search for library files (@file{.ALI} files) and
18055 source files. You can provide several -I switches on the command line,
18056 and the directories will be parsed in the order of the command line.
18059 @cindex @option{-o} (@code{gnathtml})
18060 Specify the output directory for html files. By default, gnathtml will
18061 saved the generated html files in a subdirectory named @file{html/}.
18063 @item -p @var{file}
18064 @cindex @option{-p} (@code{gnathtml})
18065 If you are using Emacs and the most recent Emacs Ada mode, which provides
18066 a full Integrated Development Environment for compiling, checking,
18067 running and debugging applications, you may use @file{.gpr} files
18068 to give the directories where Emacs can find sources and object files.
18070 Using this ^switch^option^, you can tell gnathtml to use these files.
18071 This allows you to get an html version of your application, even if it
18072 is spread over multiple directories.
18074 @item -sc @var{color}
18075 @cindex @option{-sc} (@code{gnathtml})
18076 This ^switch^option^ allows you to change the color used for symbol
18078 The default value is red. The color argument can be any name accepted by html.
18080 @item -t @var{file}
18081 @cindex @option{-t} (@code{gnathtml})
18082 This ^switch^option^ provides the name of a file. This file contains a list of
18083 file names to be converted, and the effect is exactly as though they had
18084 appeared explicitly on the command line. This
18085 is the recommended way to work around the command line length limit on some
18090 @node Installing gnathtml
18091 @section Installing @code{gnathtml}
18094 @code{Perl} needs to be installed on your machine to run this script.
18095 @code{Perl} is freely available for almost every architecture and
18096 Operating System via the Internet.
18098 On Unix systems, you may want to modify the first line of the script
18099 @code{gnathtml}, to explicitly tell the Operating system where Perl
18100 is. The syntax of this line is:
18102 #!full_path_name_to_perl
18106 Alternatively, you may run the script using the following command line:
18109 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18110 @c Expanding @ovar macro inline (explanation in macro def comments)
18111 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18120 The GNAT distribution provides an Ada 95 template for the HP Language
18121 Sensitive Editor (LSE), a component of DECset. In order to
18122 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18129 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18130 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18131 the collection phase with the /DEBUG qualifier.
18134 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18135 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18136 $ RUN/DEBUG <PROGRAM_NAME>
18142 @c ******************************
18143 @node Code Coverage and Profiling
18144 @chapter Code Coverage and Profiling
18145 @cindex Code Coverage
18149 This chapter describes how to use @code{gcov} - coverage testing tool - and
18150 @code{gprof} - profiler tool - on your Ada programs.
18153 * Code Coverage of Ada Programs using gcov::
18154 * Profiling an Ada Program using gprof::
18157 @node Code Coverage of Ada Programs using gcov
18158 @section Code Coverage of Ada Programs using gcov
18160 @cindex -fprofile-arcs
18161 @cindex -ftest-coverage
18163 @cindex Code Coverage
18166 @code{gcov} is a test coverage program: it analyzes the execution of a given
18167 program on selected tests, to help you determine the portions of the program
18168 that are still untested.
18170 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18171 User's Guide. You can refer to this documentation for a more complete
18174 This chapter provides a quick startup guide, and
18175 details some Gnat-specific features.
18178 * Quick startup guide::
18182 @node Quick startup guide
18183 @subsection Quick startup guide
18185 In order to perform coverage analysis of a program using @code{gcov}, 3
18190 Code instrumentation during the compilation process
18192 Execution of the instrumented program
18194 Execution of the @code{gcov} tool to generate the result.
18197 The code instrumentation needed by gcov is created at the object level:
18198 The source code is not modified in any way, because the instrumentation code is
18199 inserted by gcc during the compilation process. To compile your code with code
18200 coverage activated, you need to recompile your whole project using the
18202 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18203 @code{-fprofile-arcs}.
18206 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18207 -largs -fprofile-arcs
18210 This compilation process will create @file{.gcno} files together with
18211 the usual object files.
18213 Once the program is compiled with coverage instrumentation, you can
18214 run it as many times as needed - on portions of a test suite for
18215 example. The first execution will produce @file{.gcda} files at the
18216 same location as the @file{.gcno} files. The following executions
18217 will update those files, so that a cumulative result of the covered
18218 portions of the program is generated.
18220 Finally, you need to call the @code{gcov} tool. The different options of
18221 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18223 This will create annotated source files with a @file{.gcov} extension:
18224 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18226 @node Gnat specifics
18227 @subsection Gnat specifics
18229 Because Ada semantics, portions of the source code may be shared among
18230 several object files. This is the case for example when generics are
18231 involved, when inlining is active or when declarations generate initialisation
18232 calls. In order to take
18233 into account this shared code, you need to call @code{gcov} on all
18234 source files of the tested program at once.
18236 The list of source files might exceed the system's maximum command line
18237 length. In order to bypass this limitation, a new mechanism has been
18238 implemented in @code{gcov}: you can now list all your project's files into a
18239 text file, and provide this file to gcov as a parameter, preceded by a @@
18240 (e.g. @samp{gcov @@mysrclist.txt}).
18242 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18243 not supported as there can be unresolved symbols during the final link.
18245 @node Profiling an Ada Program using gprof
18246 @section Profiling an Ada Program using gprof
18252 This section is not meant to be an exhaustive documentation of @code{gprof}.
18253 Full documentation for it can be found in the GNU Profiler User's Guide
18254 documentation that is part of this GNAT distribution.
18256 Profiling a program helps determine the parts of a program that are executed
18257 most often, and are therefore the most time-consuming.
18259 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18260 better handle Ada programs and multitasking.
18261 It is currently supported on the following platforms
18266 solaris sparc/sparc64/x86
18272 In order to profile a program using @code{gprof}, 3 steps are needed:
18276 Code instrumentation, requiring a full recompilation of the project with the
18279 Execution of the program under the analysis conditions, i.e. with the desired
18282 Analysis of the results using the @code{gprof} tool.
18286 The following sections detail the different steps, and indicate how
18287 to interpret the results:
18289 * Compilation for profiling::
18290 * Program execution::
18292 * Interpretation of profiling results::
18295 @node Compilation for profiling
18296 @subsection Compilation for profiling
18300 In order to profile a program the first step is to tell the compiler
18301 to generate the necessary profiling information. The compiler switch to be used
18302 is @code{-pg}, which must be added to other compilation switches. This
18303 switch needs to be specified both during compilation and link stages, and can
18304 be specified once when using gnatmake:
18307 gnatmake -f -pg -P my_project
18311 Note that only the objects that were compiled with the @samp{-pg} switch will
18312 be profiled; if you need to profile your whole project, use the @samp{-f}
18313 gnatmake switch to force full recompilation.
18315 @node Program execution
18316 @subsection Program execution
18319 Once the program has been compiled for profiling, you can run it as usual.
18321 The only constraint imposed by profiling is that the program must terminate
18322 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18325 Once the program completes execution, a data file called @file{gmon.out} is
18326 generated in the directory where the program was launched from. If this file
18327 already exists, it will be overwritten.
18329 @node Running gprof
18330 @subsection Running gprof
18333 The @code{gprof} tool is called as follow:
18336 gprof my_prog gmon.out
18347 The complete form of the gprof command line is the following:
18350 gprof [^switches^options^] [executable [data-file]]
18354 @code{gprof} supports numerous ^switch^options^. The order of these
18355 ^switch^options^ does not matter. The full list of options can be found in
18356 the GNU Profiler User's Guide documentation that comes with this documentation.
18358 The following is the subset of those switches that is most relevant:
18362 @item --demangle[=@var{style}]
18363 @itemx --no-demangle
18364 @cindex @option{--demangle} (@code{gprof})
18365 These options control whether symbol names should be demangled when
18366 printing output. The default is to demangle C++ symbols. The
18367 @code{--no-demangle} option may be used to turn off demangling. Different
18368 compilers have different mangling styles. The optional demangling style
18369 argument can be used to choose an appropriate demangling style for your
18370 compiler, in particular Ada symbols generated by GNAT can be demangled using
18371 @code{--demangle=gnat}.
18373 @item -e @var{function_name}
18374 @cindex @option{-e} (@code{gprof})
18375 The @samp{-e @var{function}} option tells @code{gprof} not to print
18376 information about the function @var{function_name} (and its
18377 children@dots{}) in the call graph. The function will still be listed
18378 as a child of any functions that call it, but its index number will be
18379 shown as @samp{[not printed]}. More than one @samp{-e} option may be
18380 given; only one @var{function_name} may be indicated with each @samp{-e}
18383 @item -E @var{function_name}
18384 @cindex @option{-E} (@code{gprof})
18385 The @code{-E @var{function}} option works like the @code{-e} option, but
18386 execution time spent in the function (and children who were not called from
18387 anywhere else), will not be used to compute the percentages-of-time for
18388 the call graph. More than one @samp{-E} option may be given; only one
18389 @var{function_name} may be indicated with each @samp{-E} option.
18391 @item -f @var{function_name}
18392 @cindex @option{-f} (@code{gprof})
18393 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18394 call graph to the function @var{function_name} and its children (and
18395 their children@dots{}). More than one @samp{-f} option may be given;
18396 only one @var{function_name} may be indicated with each @samp{-f}
18399 @item -F @var{function_name}
18400 @cindex @option{-F} (@code{gprof})
18401 The @samp{-F @var{function}} option works like the @code{-f} option, but
18402 only time spent in the function and its children (and their
18403 children@dots{}) will be used to determine total-time and
18404 percentages-of-time for the call graph. More than one @samp{-F} option
18405 may be given; only one @var{function_name} may be indicated with each
18406 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
18410 @node Interpretation of profiling results
18411 @subsection Interpretation of profiling results
18415 The results of the profiling analysis are represented by two arrays: the
18416 'flat profile' and the 'call graph'. Full documentation of those outputs
18417 can be found in the GNU Profiler User's Guide.
18419 The flat profile shows the time spent in each function of the program, and how
18420 many time it has been called. This allows you to locate easily the most
18421 time-consuming functions.
18423 The call graph shows, for each subprogram, the subprograms that call it,
18424 and the subprograms that it calls. It also provides an estimate of the time
18425 spent in each of those callers/called subprograms.
18428 @c ******************************
18429 @node Running and Debugging Ada Programs
18430 @chapter Running and Debugging Ada Programs
18434 This chapter discusses how to debug Ada programs.
18436 It applies to GNAT on the Alpha OpenVMS platform;
18437 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18438 since HP has implemented Ada support in the OpenVMS debugger on I64.
18441 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18445 The illegality may be a violation of the static semantics of Ada. In
18446 that case GNAT diagnoses the constructs in the program that are illegal.
18447 It is then a straightforward matter for the user to modify those parts of
18451 The illegality may be a violation of the dynamic semantics of Ada. In
18452 that case the program compiles and executes, but may generate incorrect
18453 results, or may terminate abnormally with some exception.
18456 When presented with a program that contains convoluted errors, GNAT
18457 itself may terminate abnormally without providing full diagnostics on
18458 the incorrect user program.
18462 * The GNAT Debugger GDB::
18464 * Introduction to GDB Commands::
18465 * Using Ada Expressions::
18466 * Calling User-Defined Subprograms::
18467 * Using the Next Command in a Function::
18470 * Debugging Generic Units::
18471 * Remote Debugging using gdbserver::
18472 * GNAT Abnormal Termination or Failure to Terminate::
18473 * Naming Conventions for GNAT Source Files::
18474 * Getting Internal Debugging Information::
18475 * Stack Traceback::
18481 @node The GNAT Debugger GDB
18482 @section The GNAT Debugger GDB
18485 @code{GDB} is a general purpose, platform-independent debugger that
18486 can be used to debug mixed-language programs compiled with @command{gcc},
18487 and in particular is capable of debugging Ada programs compiled with
18488 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18489 complex Ada data structures.
18491 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18493 located in the GNU:[DOCS] directory,
18495 for full details on the usage of @code{GDB}, including a section on
18496 its usage on programs. This manual should be consulted for full
18497 details. The section that follows is a brief introduction to the
18498 philosophy and use of @code{GDB}.
18500 When GNAT programs are compiled, the compiler optionally writes debugging
18501 information into the generated object file, including information on
18502 line numbers, and on declared types and variables. This information is
18503 separate from the generated code. It makes the object files considerably
18504 larger, but it does not add to the size of the actual executable that
18505 will be loaded into memory, and has no impact on run-time performance. The
18506 generation of debug information is triggered by the use of the
18507 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18508 used to carry out the compilations. It is important to emphasize that
18509 the use of these options does not change the generated code.
18511 The debugging information is written in standard system formats that
18512 are used by many tools, including debuggers and profilers. The format
18513 of the information is typically designed to describe C types and
18514 semantics, but GNAT implements a translation scheme which allows full
18515 details about Ada types and variables to be encoded into these
18516 standard C formats. Details of this encoding scheme may be found in
18517 the file exp_dbug.ads in the GNAT source distribution. However, the
18518 details of this encoding are, in general, of no interest to a user,
18519 since @code{GDB} automatically performs the necessary decoding.
18521 When a program is bound and linked, the debugging information is
18522 collected from the object files, and stored in the executable image of
18523 the program. Again, this process significantly increases the size of
18524 the generated executable file, but it does not increase the size of
18525 the executable program itself. Furthermore, if this program is run in
18526 the normal manner, it runs exactly as if the debug information were
18527 not present, and takes no more actual memory.
18529 However, if the program is run under control of @code{GDB}, the
18530 debugger is activated. The image of the program is loaded, at which
18531 point it is ready to run. If a run command is given, then the program
18532 will run exactly as it would have if @code{GDB} were not present. This
18533 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
18534 entirely non-intrusive until a breakpoint is encountered. If no
18535 breakpoint is ever hit, the program will run exactly as it would if no
18536 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18537 the debugging information and can respond to user commands to inspect
18538 variables, and more generally to report on the state of execution.
18542 @section Running GDB
18545 This section describes how to initiate the debugger.
18546 @c The above sentence is really just filler, but it was otherwise
18547 @c clumsy to get the first paragraph nonindented given the conditional
18548 @c nature of the description
18551 The debugger can be launched from a @code{GPS} menu or
18552 directly from the command line. The description below covers the latter use.
18553 All the commands shown can be used in the @code{GPS} debug console window,
18554 but there are usually more GUI-based ways to achieve the same effect.
18557 The command to run @code{GDB} is
18560 $ ^gdb program^GDB PROGRAM^
18564 where @code{^program^PROGRAM^} is the name of the executable file. This
18565 activates the debugger and results in a prompt for debugger commands.
18566 The simplest command is simply @code{run}, which causes the program to run
18567 exactly as if the debugger were not present. The following section
18568 describes some of the additional commands that can be given to @code{GDB}.
18570 @c *******************************
18571 @node Introduction to GDB Commands
18572 @section Introduction to GDB Commands
18575 @code{GDB} contains a large repertoire of commands. @xref{Top,,
18576 Debugging with GDB, gdb, Debugging with GDB},
18578 located in the GNU:[DOCS] directory,
18580 for extensive documentation on the use
18581 of these commands, together with examples of their use. Furthermore,
18582 the command @command{help} invoked from within GDB activates a simple help
18583 facility which summarizes the available commands and their options.
18584 In this section we summarize a few of the most commonly
18585 used commands to give an idea of what @code{GDB} is about. You should create
18586 a simple program with debugging information and experiment with the use of
18587 these @code{GDB} commands on the program as you read through the
18591 @item set args @var{arguments}
18592 The @var{arguments} list above is a list of arguments to be passed to
18593 the program on a subsequent run command, just as though the arguments
18594 had been entered on a normal invocation of the program. The @code{set args}
18595 command is not needed if the program does not require arguments.
18598 The @code{run} command causes execution of the program to start from
18599 the beginning. If the program is already running, that is to say if
18600 you are currently positioned at a breakpoint, then a prompt will ask
18601 for confirmation that you want to abandon the current execution and
18604 @item breakpoint @var{location}
18605 The breakpoint command sets a breakpoint, that is to say a point at which
18606 execution will halt and @code{GDB} will await further
18607 commands. @var{location} is
18608 either a line number within a file, given in the format @code{file:linenumber},
18609 or it is the name of a subprogram. If you request that a breakpoint be set on
18610 a subprogram that is overloaded, a prompt will ask you to specify on which of
18611 those subprograms you want to breakpoint. You can also
18612 specify that all of them should be breakpointed. If the program is run
18613 and execution encounters the breakpoint, then the program
18614 stops and @code{GDB} signals that the breakpoint was encountered by
18615 printing the line of code before which the program is halted.
18617 @item catch exception @var{name}
18618 This command causes the program execution to stop whenever exception
18619 @var{name} is raised. If @var{name} is omitted, then the execution is
18620 suspended when any exception is raised.
18622 @item print @var{expression}
18623 This will print the value of the given expression. Most simple
18624 Ada expression formats are properly handled by @code{GDB}, so the expression
18625 can contain function calls, variables, operators, and attribute references.
18628 Continues execution following a breakpoint, until the next breakpoint or the
18629 termination of the program.
18632 Executes a single line after a breakpoint. If the next statement
18633 is a subprogram call, execution continues into (the first statement of)
18634 the called subprogram.
18637 Executes a single line. If this line is a subprogram call, executes and
18638 returns from the call.
18641 Lists a few lines around the current source location. In practice, it
18642 is usually more convenient to have a separate edit window open with the
18643 relevant source file displayed. Successive applications of this command
18644 print subsequent lines. The command can be given an argument which is a
18645 line number, in which case it displays a few lines around the specified one.
18648 Displays a backtrace of the call chain. This command is typically
18649 used after a breakpoint has occurred, to examine the sequence of calls that
18650 leads to the current breakpoint. The display includes one line for each
18651 activation record (frame) corresponding to an active subprogram.
18654 At a breakpoint, @code{GDB} can display the values of variables local
18655 to the current frame. The command @code{up} can be used to
18656 examine the contents of other active frames, by moving the focus up
18657 the stack, that is to say from callee to caller, one frame at a time.
18660 Moves the focus of @code{GDB} down from the frame currently being
18661 examined to the frame of its callee (the reverse of the previous command),
18663 @item frame @var{n}
18664 Inspect the frame with the given number. The value 0 denotes the frame
18665 of the current breakpoint, that is to say the top of the call stack.
18670 The above list is a very short introduction to the commands that
18671 @code{GDB} provides. Important additional capabilities, including conditional
18672 breakpoints, the ability to execute command sequences on a breakpoint,
18673 the ability to debug at the machine instruction level and many other
18674 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
18675 Debugging with GDB}. Note that most commands can be abbreviated
18676 (for example, c for continue, bt for backtrace).
18678 @node Using Ada Expressions
18679 @section Using Ada Expressions
18680 @cindex Ada expressions
18683 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18684 extensions. The philosophy behind the design of this subset is
18688 That @code{GDB} should provide basic literals and access to operations for
18689 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18690 leaving more sophisticated computations to subprograms written into the
18691 program (which therefore may be called from @code{GDB}).
18694 That type safety and strict adherence to Ada language restrictions
18695 are not particularly important to the @code{GDB} user.
18698 That brevity is important to the @code{GDB} user.
18702 Thus, for brevity, the debugger acts as if there were
18703 implicit @code{with} and @code{use} clauses in effect for all user-written
18704 packages, thus making it unnecessary to fully qualify most names with
18705 their packages, regardless of context. Where this causes ambiguity,
18706 @code{GDB} asks the user's intent.
18708 For details on the supported Ada syntax, see @ref{Top,, Debugging with
18709 GDB, gdb, Debugging with GDB}.
18711 @node Calling User-Defined Subprograms
18712 @section Calling User-Defined Subprograms
18715 An important capability of @code{GDB} is the ability to call user-defined
18716 subprograms while debugging. This is achieved simply by entering
18717 a subprogram call statement in the form:
18720 call subprogram-name (parameters)
18724 The keyword @code{call} can be omitted in the normal case where the
18725 @code{subprogram-name} does not coincide with any of the predefined
18726 @code{GDB} commands.
18728 The effect is to invoke the given subprogram, passing it the
18729 list of parameters that is supplied. The parameters can be expressions and
18730 can include variables from the program being debugged. The
18731 subprogram must be defined
18732 at the library level within your program, and @code{GDB} will call the
18733 subprogram within the environment of your program execution (which
18734 means that the subprogram is free to access or even modify variables
18735 within your program).
18737 The most important use of this facility is in allowing the inclusion of
18738 debugging routines that are tailored to particular data structures
18739 in your program. Such debugging routines can be written to provide a suitably
18740 high-level description of an abstract type, rather than a low-level dump
18741 of its physical layout. After all, the standard
18742 @code{GDB print} command only knows the physical layout of your
18743 types, not their abstract meaning. Debugging routines can provide information
18744 at the desired semantic level and are thus enormously useful.
18746 For example, when debugging GNAT itself, it is crucial to have access to
18747 the contents of the tree nodes used to represent the program internally.
18748 But tree nodes are represented simply by an integer value (which in turn
18749 is an index into a table of nodes).
18750 Using the @code{print} command on a tree node would simply print this integer
18751 value, which is not very useful. But the PN routine (defined in file
18752 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18753 a useful high level representation of the tree node, which includes the
18754 syntactic category of the node, its position in the source, the integers
18755 that denote descendant nodes and parent node, as well as varied
18756 semantic information. To study this example in more detail, you might want to
18757 look at the body of the PN procedure in the stated file.
18759 @node Using the Next Command in a Function
18760 @section Using the Next Command in a Function
18763 When you use the @code{next} command in a function, the current source
18764 location will advance to the next statement as usual. A special case
18765 arises in the case of a @code{return} statement.
18767 Part of the code for a return statement is the ``epilog'' of the function.
18768 This is the code that returns to the caller. There is only one copy of
18769 this epilog code, and it is typically associated with the last return
18770 statement in the function if there is more than one return. In some
18771 implementations, this epilog is associated with the first statement
18774 The result is that if you use the @code{next} command from a return
18775 statement that is not the last return statement of the function you
18776 may see a strange apparent jump to the last return statement or to
18777 the start of the function. You should simply ignore this odd jump.
18778 The value returned is always that from the first return statement
18779 that was stepped through.
18781 @node Ada Exceptions
18782 @section Stopping when Ada Exceptions are Raised
18786 You can set catchpoints that stop the program execution when your program
18787 raises selected exceptions.
18790 @item catch exception
18791 Set a catchpoint that stops execution whenever (any task in the) program
18792 raises any exception.
18794 @item catch exception @var{name}
18795 Set a catchpoint that stops execution whenever (any task in the) program
18796 raises the exception @var{name}.
18798 @item catch exception unhandled
18799 Set a catchpoint that stops executing whenever (any task in the) program
18800 raises an exception for which there is no handler.
18802 @item info exceptions
18803 @itemx info exceptions @var{regexp}
18804 The @code{info exceptions} command permits the user to examine all defined
18805 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18806 argument, prints out only those exceptions whose name matches @var{regexp}.
18814 @code{GDB} allows the following task-related commands:
18818 This command shows a list of current Ada tasks, as in the following example:
18825 ID TID P-ID Thread Pri State Name
18826 1 8088000 0 807e000 15 Child Activation Wait main_task
18827 2 80a4000 1 80ae000 15 Accept/Select Wait b
18828 3 809a800 1 80a4800 15 Child Activation Wait a
18829 * 4 80ae800 3 80b8000 15 Running c
18833 In this listing, the asterisk before the first task indicates it to be the
18834 currently running task. The first column lists the task ID that is used
18835 to refer to tasks in the following commands.
18837 @item break @var{linespec} task @var{taskid}
18838 @itemx break @var{linespec} task @var{taskid} if @dots{}
18839 @cindex Breakpoints and tasks
18840 These commands are like the @code{break @dots{} thread @dots{}}.
18841 @var{linespec} specifies source lines.
18843 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18844 to specify that you only want @code{GDB} to stop the program when a
18845 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18846 numeric task identifiers assigned by @code{GDB}, shown in the first
18847 column of the @samp{info tasks} display.
18849 If you do not specify @samp{task @var{taskid}} when you set a
18850 breakpoint, the breakpoint applies to @emph{all} tasks of your
18853 You can use the @code{task} qualifier on conditional breakpoints as
18854 well; in this case, place @samp{task @var{taskid}} before the
18855 breakpoint condition (before the @code{if}).
18857 @item task @var{taskno}
18858 @cindex Task switching
18860 This command allows to switch to the task referred by @var{taskno}. In
18861 particular, This allows to browse the backtrace of the specified
18862 task. It is advised to switch back to the original task before
18863 continuing execution otherwise the scheduling of the program may be
18868 For more detailed information on the tasking support,
18869 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
18871 @node Debugging Generic Units
18872 @section Debugging Generic Units
18873 @cindex Debugging Generic Units
18877 GNAT always uses code expansion for generic instantiation. This means that
18878 each time an instantiation occurs, a complete copy of the original code is
18879 made, with appropriate substitutions of formals by actuals.
18881 It is not possible to refer to the original generic entities in
18882 @code{GDB}, but it is always possible to debug a particular instance of
18883 a generic, by using the appropriate expanded names. For example, if we have
18885 @smallexample @c ada
18890 generic package k is
18891 procedure kp (v1 : in out integer);
18895 procedure kp (v1 : in out integer) is
18901 package k1 is new k;
18902 package k2 is new k;
18904 var : integer := 1;
18917 Then to break on a call to procedure kp in the k2 instance, simply
18921 (gdb) break g.k2.kp
18925 When the breakpoint occurs, you can step through the code of the
18926 instance in the normal manner and examine the values of local variables, as for
18929 @node Remote Debugging using gdbserver
18930 @section Remote Debugging using gdbserver
18931 @cindex Remote Debugging using gdbserver
18934 On platforms where gdbserver is supported, it is possible to use this tool
18935 to debug your application remotely. This can be useful in situations
18936 where the program needs to be run on a target host that is different
18937 from the host used for development, particularly when the target has
18938 a limited amount of resources (either CPU and/or memory).
18940 To do so, start your program using gdbserver on the target machine.
18941 gdbserver then automatically suspends the execution of your program
18942 at its entry point, waiting for a debugger to connect to it. The
18943 following commands starts an application and tells gdbserver to
18944 wait for a connection with the debugger on localhost port 4444.
18947 $ gdbserver localhost:4444 program
18948 Process program created; pid = 5685
18949 Listening on port 4444
18952 Once gdbserver has started listening, we can tell the debugger to establish
18953 a connection with this gdbserver, and then start the same debugging session
18954 as if the program was being debugged on the same host, directly under
18955 the control of GDB.
18959 (gdb) target remote targethost:4444
18960 Remote debugging using targethost:4444
18961 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18963 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18967 Breakpoint 1, foo () at foo.adb:4
18971 It is also possible to use gdbserver to attach to an already running
18972 program, in which case the execution of that program is simply suspended
18973 until the connection between the debugger and gdbserver is established.
18975 For more information on how to use gdbserver, @ref{Top, Server, Using
18976 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
18977 for gdbserver on x86-linux, x86-windows and x86_64-linux.
18979 @node GNAT Abnormal Termination or Failure to Terminate
18980 @section GNAT Abnormal Termination or Failure to Terminate
18981 @cindex GNAT Abnormal Termination or Failure to Terminate
18984 When presented with programs that contain serious errors in syntax
18986 GNAT may on rare occasions experience problems in operation, such
18988 segmentation fault or illegal memory access, raising an internal
18989 exception, terminating abnormally, or failing to terminate at all.
18990 In such cases, you can activate
18991 various features of GNAT that can help you pinpoint the construct in your
18992 program that is the likely source of the problem.
18994 The following strategies are presented in increasing order of
18995 difficulty, corresponding to your experience in using GNAT and your
18996 familiarity with compiler internals.
19000 Run @command{gcc} with the @option{-gnatf}. This first
19001 switch causes all errors on a given line to be reported. In its absence,
19002 only the first error on a line is displayed.
19004 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19005 are encountered, rather than after compilation is terminated. If GNAT
19006 terminates prematurely or goes into an infinite loop, the last error
19007 message displayed may help to pinpoint the culprit.
19010 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19011 mode, @command{gcc} produces ongoing information about the progress of the
19012 compilation and provides the name of each procedure as code is
19013 generated. This switch allows you to find which Ada procedure was being
19014 compiled when it encountered a code generation problem.
19017 @cindex @option{-gnatdc} switch
19018 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19019 switch that does for the front-end what @option{^-v^VERBOSE^} does
19020 for the back end. The system prints the name of each unit,
19021 either a compilation unit or nested unit, as it is being analyzed.
19023 Finally, you can start
19024 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19025 front-end of GNAT, and can be run independently (normally it is just
19026 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19027 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19028 @code{where} command is the first line of attack; the variable
19029 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19030 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19031 which the execution stopped, and @code{input_file name} indicates the name of
19035 @node Naming Conventions for GNAT Source Files
19036 @section Naming Conventions for GNAT Source Files
19039 In order to examine the workings of the GNAT system, the following
19040 brief description of its organization may be helpful:
19044 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19047 All files prefixed with @file{^par^PAR^} are components of the parser. The
19048 numbers correspond to chapters of the Ada Reference Manual. For example,
19049 parsing of select statements can be found in @file{par-ch9.adb}.
19052 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19053 numbers correspond to chapters of the Ada standard. For example, all
19054 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19055 addition, some features of the language require sufficient special processing
19056 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19057 dynamic dispatching, etc.
19060 All files prefixed with @file{^exp^EXP^} perform normalization and
19061 expansion of the intermediate representation (abstract syntax tree, or AST).
19062 these files use the same numbering scheme as the parser and semantics files.
19063 For example, the construction of record initialization procedures is done in
19064 @file{exp_ch3.adb}.
19067 The files prefixed with @file{^bind^BIND^} implement the binder, which
19068 verifies the consistency of the compilation, determines an order of
19069 elaboration, and generates the bind file.
19072 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19073 data structures used by the front-end.
19076 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19077 the abstract syntax tree as produced by the parser.
19080 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19081 all entities, computed during semantic analysis.
19084 Library management issues are dealt with in files with prefix
19090 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19091 defined in Annex A.
19096 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19097 defined in Annex B.
19101 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19102 both language-defined children and GNAT run-time routines.
19106 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19107 general-purpose packages, fully documented in their specs. All
19108 the other @file{.c} files are modifications of common @command{gcc} files.
19111 @node Getting Internal Debugging Information
19112 @section Getting Internal Debugging Information
19115 Most compilers have internal debugging switches and modes. GNAT
19116 does also, except GNAT internal debugging switches and modes are not
19117 secret. A summary and full description of all the compiler and binder
19118 debug flags are in the file @file{debug.adb}. You must obtain the
19119 sources of the compiler to see the full detailed effects of these flags.
19121 The switches that print the source of the program (reconstructed from
19122 the internal tree) are of general interest for user programs, as are the
19124 the full internal tree, and the entity table (the symbol table
19125 information). The reconstructed source provides a readable version of the
19126 program after the front-end has completed analysis and expansion,
19127 and is useful when studying the performance of specific constructs.
19128 For example, constraint checks are indicated, complex aggregates
19129 are replaced with loops and assignments, and tasking primitives
19130 are replaced with run-time calls.
19132 @node Stack Traceback
19133 @section Stack Traceback
19135 @cindex stack traceback
19136 @cindex stack unwinding
19139 Traceback is a mechanism to display the sequence of subprogram calls that
19140 leads to a specified execution point in a program. Often (but not always)
19141 the execution point is an instruction at which an exception has been raised.
19142 This mechanism is also known as @i{stack unwinding} because it obtains
19143 its information by scanning the run-time stack and recovering the activation
19144 records of all active subprograms. Stack unwinding is one of the most
19145 important tools for program debugging.
19147 The first entry stored in traceback corresponds to the deepest calling level,
19148 that is to say the subprogram currently executing the instruction
19149 from which we want to obtain the traceback.
19151 Note that there is no runtime performance penalty when stack traceback
19152 is enabled, and no exception is raised during program execution.
19155 * Non-Symbolic Traceback::
19156 * Symbolic Traceback::
19159 @node Non-Symbolic Traceback
19160 @subsection Non-Symbolic Traceback
19161 @cindex traceback, non-symbolic
19164 Note: this feature is not supported on all platforms. See
19165 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19169 * Tracebacks From an Unhandled Exception::
19170 * Tracebacks From Exception Occurrences (non-symbolic)::
19171 * Tracebacks From Anywhere in a Program (non-symbolic)::
19174 @node Tracebacks From an Unhandled Exception
19175 @subsubsection Tracebacks From an Unhandled Exception
19178 A runtime non-symbolic traceback is a list of addresses of call instructions.
19179 To enable this feature you must use the @option{-E}
19180 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19181 of exception information. You can retrieve this information using the
19182 @code{addr2line} tool.
19184 Here is a simple example:
19186 @smallexample @c ada
19192 raise Constraint_Error;
19207 $ gnatmake stb -bargs -E
19210 Execution terminated by unhandled exception
19211 Exception name: CONSTRAINT_ERROR
19213 Call stack traceback locations:
19214 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19218 As we see the traceback lists a sequence of addresses for the unhandled
19219 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19220 guess that this exception come from procedure P1. To translate these
19221 addresses into the source lines where the calls appear, the
19222 @code{addr2line} tool, described below, is invaluable. The use of this tool
19223 requires the program to be compiled with debug information.
19226 $ gnatmake -g stb -bargs -E
19229 Execution terminated by unhandled exception
19230 Exception name: CONSTRAINT_ERROR
19232 Call stack traceback locations:
19233 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19235 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19236 0x4011f1 0x77e892a4
19238 00401373 at d:/stb/stb.adb:5
19239 0040138B at d:/stb/stb.adb:10
19240 0040139C at d:/stb/stb.adb:14
19241 00401335 at d:/stb/b~stb.adb:104
19242 004011C4 at /build/@dots{}/crt1.c:200
19243 004011F1 at /build/@dots{}/crt1.c:222
19244 77E892A4 in ?? at ??:0
19248 The @code{addr2line} tool has several other useful options:
19252 to get the function name corresponding to any location
19254 @item --demangle=gnat
19255 to use the gnat decoding mode for the function names. Note that
19256 for binutils version 2.9.x the option is simply @option{--demangle}.
19260 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19261 0x40139c 0x401335 0x4011c4 0x4011f1
19263 00401373 in stb.p1 at d:/stb/stb.adb:5
19264 0040138B in stb.p2 at d:/stb/stb.adb:10
19265 0040139C in stb at d:/stb/stb.adb:14
19266 00401335 in main at d:/stb/b~stb.adb:104
19267 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19268 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19272 From this traceback we can see that the exception was raised in
19273 @file{stb.adb} at line 5, which was reached from a procedure call in
19274 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19275 which contains the call to the main program.
19276 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19277 and the output will vary from platform to platform.
19279 It is also possible to use @code{GDB} with these traceback addresses to debug
19280 the program. For example, we can break at a given code location, as reported
19281 in the stack traceback:
19287 Furthermore, this feature is not implemented inside Windows DLL. Only
19288 the non-symbolic traceback is reported in this case.
19291 (gdb) break *0x401373
19292 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19296 It is important to note that the stack traceback addresses
19297 do not change when debug information is included. This is particularly useful
19298 because it makes it possible to release software without debug information (to
19299 minimize object size), get a field report that includes a stack traceback
19300 whenever an internal bug occurs, and then be able to retrieve the sequence
19301 of calls with the same program compiled with debug information.
19303 @node Tracebacks From Exception Occurrences (non-symbolic)
19304 @subsubsection Tracebacks From Exception Occurrences
19307 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19308 The stack traceback is attached to the exception information string, and can
19309 be retrieved in an exception handler within the Ada program, by means of the
19310 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19312 @smallexample @c ada
19314 with Ada.Exceptions;
19319 use Ada.Exceptions;
19327 Text_IO.Put_Line (Exception_Information (E));
19341 This program will output:
19346 Exception name: CONSTRAINT_ERROR
19347 Message: stb.adb:12
19348 Call stack traceback locations:
19349 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19352 @node Tracebacks From Anywhere in a Program (non-symbolic)
19353 @subsubsection Tracebacks From Anywhere in a Program
19356 It is also possible to retrieve a stack traceback from anywhere in a
19357 program. For this you need to
19358 use the @code{GNAT.Traceback} API. This package includes a procedure called
19359 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19360 display procedures described below. It is not necessary to use the
19361 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19362 is invoked explicitly.
19365 In the following example we compute a traceback at a specific location in
19366 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19367 convert addresses to strings:
19369 @smallexample @c ada
19371 with GNAT.Traceback;
19372 with GNAT.Debug_Utilities;
19378 use GNAT.Traceback;
19381 TB : Tracebacks_Array (1 .. 10);
19382 -- We are asking for a maximum of 10 stack frames.
19384 -- Len will receive the actual number of stack frames returned.
19386 Call_Chain (TB, Len);
19388 Text_IO.Put ("In STB.P1 : ");
19390 for K in 1 .. Len loop
19391 Text_IO.Put (Debug_Utilities.Image (TB (K)));
19412 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19413 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19417 You can then get further information by invoking the @code{addr2line}
19418 tool as described earlier (note that the hexadecimal addresses
19419 need to be specified in C format, with a leading ``0x'').
19421 @node Symbolic Traceback
19422 @subsection Symbolic Traceback
19423 @cindex traceback, symbolic
19426 A symbolic traceback is a stack traceback in which procedure names are
19427 associated with each code location.
19430 Note that this feature is not supported on all platforms. See
19431 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19432 list of currently supported platforms.
19435 Note that the symbolic traceback requires that the program be compiled
19436 with debug information. If it is not compiled with debug information
19437 only the non-symbolic information will be valid.
19440 * Tracebacks From Exception Occurrences (symbolic)::
19441 * Tracebacks From Anywhere in a Program (symbolic)::
19444 @node Tracebacks From Exception Occurrences (symbolic)
19445 @subsubsection Tracebacks From Exception Occurrences
19447 @smallexample @c ada
19449 with GNAT.Traceback.Symbolic;
19455 raise Constraint_Error;
19472 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19477 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19480 0040149F in stb.p1 at stb.adb:8
19481 004014B7 in stb.p2 at stb.adb:13
19482 004014CF in stb.p3 at stb.adb:18
19483 004015DD in ada.stb at stb.adb:22
19484 00401461 in main at b~stb.adb:168
19485 004011C4 in __mingw_CRTStartup at crt1.c:200
19486 004011F1 in mainCRTStartup at crt1.c:222
19487 77E892A4 in ?? at ??:0
19491 In the above example the ``.\'' syntax in the @command{gnatmake} command
19492 is currently required by @command{addr2line} for files that are in
19493 the current working directory.
19494 Moreover, the exact sequence of linker options may vary from platform
19496 The above @option{-largs} section is for Windows platforms. By contrast,
19497 under Unix there is no need for the @option{-largs} section.
19498 Differences across platforms are due to details of linker implementation.
19500 @node Tracebacks From Anywhere in a Program (symbolic)
19501 @subsubsection Tracebacks From Anywhere in a Program
19504 It is possible to get a symbolic stack traceback
19505 from anywhere in a program, just as for non-symbolic tracebacks.
19506 The first step is to obtain a non-symbolic
19507 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19508 information. Here is an example:
19510 @smallexample @c ada
19512 with GNAT.Traceback;
19513 with GNAT.Traceback.Symbolic;
19518 use GNAT.Traceback;
19519 use GNAT.Traceback.Symbolic;
19522 TB : Tracebacks_Array (1 .. 10);
19523 -- We are asking for a maximum of 10 stack frames.
19525 -- Len will receive the actual number of stack frames returned.
19527 Call_Chain (TB, Len);
19528 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19541 @c ******************************
19543 @node Compatibility with HP Ada
19544 @chapter Compatibility with HP Ada
19545 @cindex Compatibility
19550 @cindex Compatibility between GNAT and HP Ada
19551 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19552 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19553 GNAT is highly compatible
19554 with HP Ada, and it should generally be straightforward to port code
19555 from the HP Ada environment to GNAT. However, there are a few language
19556 and implementation differences of which the user must be aware. These
19557 differences are discussed in this chapter. In
19558 addition, the operating environment and command structure for the
19559 compiler are different, and these differences are also discussed.
19561 For further details on these and other compatibility issues,
19562 see Appendix E of the HP publication
19563 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19565 Except where otherwise indicated, the description of GNAT for OpenVMS
19566 applies to both the Alpha and I64 platforms.
19568 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19569 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19571 The discussion in this chapter addresses specifically the implementation
19572 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19573 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19574 GNAT always follows the Alpha implementation.
19576 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19577 attributes are recognized, although only a subset of them can sensibly
19578 be implemented. The description of pragmas in
19579 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19580 indicates whether or not they are applicable to non-VMS systems.
19583 * Ada Language Compatibility::
19584 * Differences in the Definition of Package System::
19585 * Language-Related Features::
19586 * The Package STANDARD::
19587 * The Package SYSTEM::
19588 * Tasking and Task-Related Features::
19589 * Pragmas and Pragma-Related Features::
19590 * Library of Predefined Units::
19592 * Main Program Definition::
19593 * Implementation-Defined Attributes::
19594 * Compiler and Run-Time Interfacing::
19595 * Program Compilation and Library Management::
19597 * Implementation Limits::
19598 * Tools and Utilities::
19601 @node Ada Language Compatibility
19602 @section Ada Language Compatibility
19605 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19606 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19607 with Ada 83, and therefore Ada 83 programs will compile
19608 and run under GNAT with
19609 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
19610 provides details on specific incompatibilities.
19612 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
19613 as well as the pragma @code{ADA_83}, to force the compiler to
19614 operate in Ada 83 mode. This mode does not guarantee complete
19615 conformance to Ada 83, but in practice is sufficient to
19616 eliminate most sources of incompatibilities.
19617 In particular, it eliminates the recognition of the
19618 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
19619 in Ada 83 programs is legal, and handles the cases of packages
19620 with optional bodies, and generics that instantiate unconstrained
19621 types without the use of @code{(<>)}.
19623 @node Differences in the Definition of Package System
19624 @section Differences in the Definition of Package @code{System}
19627 An Ada compiler is allowed to add
19628 implementation-dependent declarations to package @code{System}.
19630 GNAT does not take advantage of this permission, and the version of
19631 @code{System} provided by GNAT exactly matches that defined in the Ada
19634 However, HP Ada adds an extensive set of declarations to package
19636 as fully documented in the HP Ada manuals. To minimize changes required
19637 for programs that make use of these extensions, GNAT provides the pragma
19638 @code{Extend_System} for extending the definition of package System. By using:
19639 @cindex pragma @code{Extend_System}
19640 @cindex @code{Extend_System} pragma
19642 @smallexample @c ada
19645 pragma Extend_System (Aux_DEC);
19651 the set of definitions in @code{System} is extended to include those in
19652 package @code{System.Aux_DEC}.
19653 @cindex @code{System.Aux_DEC} package
19654 @cindex @code{Aux_DEC} package (child of @code{System})
19655 These definitions are incorporated directly into package @code{System},
19656 as though they had been declared there. For a
19657 list of the declarations added, see the spec of this package,
19658 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
19659 @cindex @file{s-auxdec.ads} file
19660 The pragma @code{Extend_System} is a configuration pragma, which means that
19661 it can be placed in the file @file{gnat.adc}, so that it will automatically
19662 apply to all subsequent compilations. See @ref{Configuration Pragmas},
19663 for further details.
19665 An alternative approach that avoids the use of the non-standard
19666 @code{Extend_System} pragma is to add a context clause to the unit that
19667 references these facilities:
19669 @smallexample @c ada
19671 with System.Aux_DEC;
19672 use System.Aux_DEC;
19677 The effect is not quite semantically identical to incorporating
19678 the declarations directly into package @code{System},
19679 but most programs will not notice a difference
19680 unless they use prefix notation (e.g.@: @code{System.Integer_8})
19681 to reference the entities directly in package @code{System}.
19682 For units containing such references,
19683 the prefixes must either be removed, or the pragma @code{Extend_System}
19686 @node Language-Related Features
19687 @section Language-Related Features
19690 The following sections highlight differences in types,
19691 representations of types, operations, alignment, and
19695 * Integer Types and Representations::
19696 * Floating-Point Types and Representations::
19697 * Pragmas Float_Representation and Long_Float::
19698 * Fixed-Point Types and Representations::
19699 * Record and Array Component Alignment::
19700 * Address Clauses::
19701 * Other Representation Clauses::
19704 @node Integer Types and Representations
19705 @subsection Integer Types and Representations
19708 The set of predefined integer types is identical in HP Ada and GNAT.
19709 Furthermore the representation of these integer types is also identical,
19710 including the capability of size clauses forcing biased representation.
19713 HP Ada for OpenVMS Alpha systems has defined the
19714 following additional integer types in package @code{System}:
19731 @code{LARGEST_INTEGER}
19735 In GNAT, the first four of these types may be obtained from the
19736 standard Ada package @code{Interfaces}.
19737 Alternatively, by use of the pragma @code{Extend_System}, identical
19738 declarations can be referenced directly in package @code{System}.
19739 On both GNAT and HP Ada, the maximum integer size is 64 bits.
19741 @node Floating-Point Types and Representations
19742 @subsection Floating-Point Types and Representations
19743 @cindex Floating-Point types
19746 The set of predefined floating-point types is identical in HP Ada and GNAT.
19747 Furthermore the representation of these floating-point
19748 types is also identical. One important difference is that the default
19749 representation for HP Ada is @code{VAX_Float}, but the default representation
19752 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
19753 pragma @code{Float_Representation} as described in the HP Ada
19755 For example, the declarations:
19757 @smallexample @c ada
19759 type F_Float is digits 6;
19760 pragma Float_Representation (VAX_Float, F_Float);
19765 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
19767 This set of declarations actually appears in @code{System.Aux_DEC},
19769 the full set of additional floating-point declarations provided in
19770 the HP Ada version of package @code{System}.
19771 This and similar declarations may be accessed in a user program
19772 by using pragma @code{Extend_System}. The use of this
19773 pragma, and the related pragma @code{Long_Float} is described in further
19774 detail in the following section.
19776 @node Pragmas Float_Representation and Long_Float
19777 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
19780 HP Ada provides the pragma @code{Float_Representation}, which
19781 acts as a program library switch to allow control over
19782 the internal representation chosen for the predefined
19783 floating-point types declared in the package @code{Standard}.
19784 The format of this pragma is as follows:
19786 @smallexample @c ada
19788 pragma Float_Representation(VAX_Float | IEEE_Float);
19793 This pragma controls the representation of floating-point
19798 @code{VAX_Float} specifies that floating-point
19799 types are represented by default with the VAX system hardware types
19800 @code{F-floating}, @code{D-floating}, @code{G-floating}.
19801 Note that the @code{H-floating}
19802 type was available only on VAX systems, and is not available
19803 in either HP Ada or GNAT.
19806 @code{IEEE_Float} specifies that floating-point
19807 types are represented by default with the IEEE single and
19808 double floating-point types.
19812 GNAT provides an identical implementation of the pragma
19813 @code{Float_Representation}, except that it functions as a
19814 configuration pragma. Note that the
19815 notion of configuration pragma corresponds closely to the
19816 HP Ada notion of a program library switch.
19818 When no pragma is used in GNAT, the default is @code{IEEE_Float},
19820 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
19821 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
19822 advisable to change the format of numbers passed to standard library
19823 routines, and if necessary explicit type conversions may be needed.
19825 The use of @code{IEEE_Float} is recommended in GNAT since it is more
19826 efficient, and (given that it conforms to an international standard)
19827 potentially more portable.
19828 The situation in which @code{VAX_Float} may be useful is in interfacing
19829 to existing code and data that expect the use of @code{VAX_Float}.
19830 In such a situation use the predefined @code{VAX_Float}
19831 types in package @code{System}, as extended by
19832 @code{Extend_System}. For example, use @code{System.F_Float}
19833 to specify the 32-bit @code{F-Float} format.
19836 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
19837 to allow control over the internal representation chosen
19838 for the predefined type @code{Long_Float} and for floating-point
19839 type declarations with digits specified in the range 7 .. 15.
19840 The format of this pragma is as follows:
19842 @smallexample @c ada
19844 pragma Long_Float (D_FLOAT | G_FLOAT);
19848 @node Fixed-Point Types and Representations
19849 @subsection Fixed-Point Types and Representations
19852 On HP Ada for OpenVMS Alpha systems, rounding is
19853 away from zero for both positive and negative numbers.
19854 Therefore, @code{+0.5} rounds to @code{1},
19855 and @code{-0.5} rounds to @code{-1}.
19857 On GNAT the results of operations
19858 on fixed-point types are in accordance with the Ada
19859 rules. In particular, results of operations on decimal
19860 fixed-point types are truncated.
19862 @node Record and Array Component Alignment
19863 @subsection Record and Array Component Alignment
19866 On HP Ada for OpenVMS Alpha, all non-composite components
19867 are aligned on natural boundaries. For example, 1-byte
19868 components are aligned on byte boundaries, 2-byte
19869 components on 2-byte boundaries, 4-byte components on 4-byte
19870 byte boundaries, and so on. The OpenVMS Alpha hardware
19871 runs more efficiently with naturally aligned data.
19873 On GNAT, alignment rules are compatible
19874 with HP Ada for OpenVMS Alpha.
19876 @node Address Clauses
19877 @subsection Address Clauses
19880 In HP Ada and GNAT, address clauses are supported for
19881 objects and imported subprograms.
19882 The predefined type @code{System.Address} is a private type
19883 in both compilers on Alpha OpenVMS, with the same representation
19884 (it is simply a machine pointer). Addition, subtraction, and comparison
19885 operations are available in the standard Ada package
19886 @code{System.Storage_Elements}, or in package @code{System}
19887 if it is extended to include @code{System.Aux_DEC} using a
19888 pragma @code{Extend_System} as previously described.
19890 Note that code that @code{with}'s both this extended package @code{System}
19891 and the package @code{System.Storage_Elements} should not @code{use}
19892 both packages, or ambiguities will result. In general it is better
19893 not to mix these two sets of facilities. The Ada package was
19894 designed specifically to provide the kind of features that HP Ada
19895 adds directly to package @code{System}.
19897 The type @code{System.Address} is a 64-bit integer type in GNAT for
19898 I64 OpenVMS. For more information,
19899 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19901 GNAT is compatible with HP Ada in its handling of address
19902 clauses, except for some limitations in
19903 the form of address clauses for composite objects with
19904 initialization. Such address clauses are easily replaced
19905 by the use of an explicitly-defined constant as described
19906 in the Ada Reference Manual (13.1(22)). For example, the sequence
19909 @smallexample @c ada
19911 X, Y : Integer := Init_Func;
19912 Q : String (X .. Y) := "abc";
19914 for Q'Address use Compute_Address;
19919 will be rejected by GNAT, since the address cannot be computed at the time
19920 that @code{Q} is declared. To achieve the intended effect, write instead:
19922 @smallexample @c ada
19925 X, Y : Integer := Init_Func;
19926 Q_Address : constant Address := Compute_Address;
19927 Q : String (X .. Y) := "abc";
19929 for Q'Address use Q_Address;
19935 which will be accepted by GNAT (and other Ada compilers), and is also
19936 compatible with Ada 83. A fuller description of the restrictions
19937 on address specifications is found in @ref{Top, GNAT Reference Manual,
19938 About This Guide, gnat_rm, GNAT Reference Manual}.
19940 @node Other Representation Clauses
19941 @subsection Other Representation Clauses
19944 GNAT implements in a compatible manner all the representation
19945 clauses supported by HP Ada. In addition, GNAT
19946 implements the representation clause forms that were introduced in Ada 95,
19947 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
19949 @node The Package STANDARD
19950 @section The Package @code{STANDARD}
19953 The package @code{STANDARD}, as implemented by HP Ada, is fully
19954 described in the @cite{Ada Reference Manual} and in the
19955 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
19956 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
19958 In addition, HP Ada supports the Latin-1 character set in
19959 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
19960 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
19961 the type @code{WIDE_CHARACTER}.
19963 The floating-point types supported by GNAT are those
19964 supported by HP Ada, but the defaults are different, and are controlled by
19965 pragmas. See @ref{Floating-Point Types and Representations}, for details.
19967 @node The Package SYSTEM
19968 @section The Package @code{SYSTEM}
19971 HP Ada provides a specific version of the package
19972 @code{SYSTEM} for each platform on which the language is implemented.
19973 For the complete spec of the package @code{SYSTEM}, see
19974 Appendix F of the @cite{HP Ada Language Reference Manual}.
19976 On HP Ada, the package @code{SYSTEM} includes the following conversion
19979 @item @code{TO_ADDRESS(INTEGER)}
19981 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
19983 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
19985 @item @code{TO_INTEGER(ADDRESS)}
19987 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
19989 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
19990 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
19994 By default, GNAT supplies a version of @code{SYSTEM} that matches
19995 the definition given in the @cite{Ada Reference Manual}.
19997 is a subset of the HP system definitions, which is as
19998 close as possible to the original definitions. The only difference
19999 is that the definition of @code{SYSTEM_NAME} is different:
20001 @smallexample @c ada
20003 type Name is (SYSTEM_NAME_GNAT);
20004 System_Name : constant Name := SYSTEM_NAME_GNAT;
20009 Also, GNAT adds the Ada declarations for
20010 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20012 However, the use of the following pragma causes GNAT
20013 to extend the definition of package @code{SYSTEM} so that it
20014 encompasses the full set of HP-specific extensions,
20015 including the functions listed above:
20017 @smallexample @c ada
20019 pragma Extend_System (Aux_DEC);
20024 The pragma @code{Extend_System} is a configuration pragma that
20025 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20026 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20028 HP Ada does not allow the recompilation of the package
20029 @code{SYSTEM}. Instead HP Ada provides several pragmas
20030 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20031 to modify values in the package @code{SYSTEM}.
20032 On OpenVMS Alpha systems, the pragma
20033 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20034 its single argument.
20036 GNAT does permit the recompilation of package @code{SYSTEM} using
20037 the special switch @option{-gnatg}, and this switch can be used if
20038 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20039 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20040 or @code{MEMORY_SIZE} by any other means.
20042 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20043 enumeration literal @code{SYSTEM_NAME_GNAT}.
20045 The definitions provided by the use of
20047 @smallexample @c ada
20048 pragma Extend_System (AUX_Dec);
20052 are virtually identical to those provided by the HP Ada 83 package
20053 @code{SYSTEM}. One important difference is that the name of the
20055 function for type @code{UNSIGNED_LONGWORD} is changed to
20056 @code{TO_ADDRESS_LONG}.
20057 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20058 discussion of why this change was necessary.
20061 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20063 an extension to Ada 83 not strictly compatible with the reference manual.
20064 GNAT, in order to be exactly compatible with the standard,
20065 does not provide this capability. In HP Ada 83, the
20066 point of this definition is to deal with a call like:
20068 @smallexample @c ada
20069 TO_ADDRESS (16#12777#);
20073 Normally, according to Ada 83 semantics, one would expect this to be
20074 ambiguous, since it matches both the @code{INTEGER} and
20075 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20076 However, in HP Ada 83, there is no ambiguity, since the
20077 definition using @i{universal_integer} takes precedence.
20079 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20081 not possible to be 100% compatible. Since there are many programs using
20082 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20084 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20085 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20087 @smallexample @c ada
20088 function To_Address (X : Integer) return Address;
20089 pragma Pure_Function (To_Address);
20091 function To_Address_Long (X : Unsigned_Longword) return Address;
20092 pragma Pure_Function (To_Address_Long);
20096 This means that programs using @code{TO_ADDRESS} for
20097 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20099 @node Tasking and Task-Related Features
20100 @section Tasking and Task-Related Features
20103 This section compares the treatment of tasking in GNAT
20104 and in HP Ada for OpenVMS Alpha.
20105 The GNAT description applies to both Alpha and I64 OpenVMS.
20106 For detailed information on tasking in
20107 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20108 relevant run-time reference manual.
20111 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20112 * Assigning Task IDs::
20113 * Task IDs and Delays::
20114 * Task-Related Pragmas::
20115 * Scheduling and Task Priority::
20117 * External Interrupts::
20120 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20121 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20124 On OpenVMS Alpha systems, each Ada task (except a passive
20125 task) is implemented as a single stream of execution
20126 that is created and managed by the kernel. On these
20127 systems, HP Ada tasking support is based on DECthreads,
20128 an implementation of the POSIX standard for threads.
20130 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20131 code that calls DECthreads routines can be used together.
20132 The interaction between Ada tasks and DECthreads routines
20133 can have some benefits. For example when on OpenVMS Alpha,
20134 HP Ada can call C code that is already threaded.
20136 GNAT uses the facilities of DECthreads,
20137 and Ada tasks are mapped to threads.
20139 @node Assigning Task IDs
20140 @subsection Assigning Task IDs
20143 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20144 the environment task that executes the main program. On
20145 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20146 that have been created but are not yet activated.
20148 On OpenVMS Alpha systems, task IDs are assigned at
20149 activation. On GNAT systems, task IDs are also assigned at
20150 task creation but do not have the same form or values as
20151 task ID values in HP Ada. There is no null task, and the
20152 environment task does not have a specific task ID value.
20154 @node Task IDs and Delays
20155 @subsection Task IDs and Delays
20158 On OpenVMS Alpha systems, tasking delays are implemented
20159 using Timer System Services. The Task ID is used for the
20160 identification of the timer request (the @code{REQIDT} parameter).
20161 If Timers are used in the application take care not to use
20162 @code{0} for the identification, because cancelling such a timer
20163 will cancel all timers and may lead to unpredictable results.
20165 @node Task-Related Pragmas
20166 @subsection Task-Related Pragmas
20169 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20170 specification of the size of the guard area for a task
20171 stack. (The guard area forms an area of memory that has no
20172 read or write access and thus helps in the detection of
20173 stack overflow.) On OpenVMS Alpha systems, if the pragma
20174 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20175 area is created. In the absence of a pragma @code{TASK_STORAGE},
20176 a default guard area is created.
20178 GNAT supplies the following task-related pragmas:
20181 @item @code{TASK_INFO}
20183 This pragma appears within a task definition and
20184 applies to the task in which it appears. The argument
20185 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20187 @item @code{TASK_STORAGE}
20189 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20190 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20191 @code{SUPPRESS}, and @code{VOLATILE}.
20193 @node Scheduling and Task Priority
20194 @subsection Scheduling and Task Priority
20197 HP Ada implements the Ada language requirement that
20198 when two tasks are eligible for execution and they have
20199 different priorities, the lower priority task does not
20200 execute while the higher priority task is waiting. The HP
20201 Ada Run-Time Library keeps a task running until either the
20202 task is suspended or a higher priority task becomes ready.
20204 On OpenVMS Alpha systems, the default strategy is round-
20205 robin with preemption. Tasks of equal priority take turns
20206 at the processor. A task is run for a certain period of
20207 time and then placed at the tail of the ready queue for
20208 its priority level.
20210 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20211 which can be used to enable or disable round-robin
20212 scheduling of tasks with the same priority.
20213 See the relevant HP Ada run-time reference manual for
20214 information on using the pragmas to control HP Ada task
20217 GNAT follows the scheduling rules of Annex D (Real-Time
20218 Annex) of the @cite{Ada Reference Manual}. In general, this
20219 scheduling strategy is fully compatible with HP Ada
20220 although it provides some additional constraints (as
20221 fully documented in Annex D).
20222 GNAT implements time slicing control in a manner compatible with
20223 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20224 are identical to the HP Ada 83 pragma of the same name.
20225 Note that it is not possible to mix GNAT tasking and
20226 HP Ada 83 tasking in the same program, since the two run-time
20227 libraries are not compatible.
20229 @node The Task Stack
20230 @subsection The Task Stack
20233 In HP Ada, a task stack is allocated each time a
20234 non-passive task is activated. As soon as the task is
20235 terminated, the storage for the task stack is deallocated.
20236 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20237 a default stack size is used. Also, regardless of the size
20238 specified, some additional space is allocated for task
20239 management purposes. On OpenVMS Alpha systems, at least
20240 one page is allocated.
20242 GNAT handles task stacks in a similar manner. In accordance with
20243 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20244 an alternative method for controlling the task stack size.
20245 The specification of the attribute @code{T'STORAGE_SIZE} is also
20246 supported in a manner compatible with HP Ada.
20248 @node External Interrupts
20249 @subsection External Interrupts
20252 On HP Ada, external interrupts can be associated with task entries.
20253 GNAT is compatible with HP Ada in its handling of external interrupts.
20255 @node Pragmas and Pragma-Related Features
20256 @section Pragmas and Pragma-Related Features
20259 Both HP Ada and GNAT supply all language-defined pragmas
20260 as specified by the Ada 83 standard. GNAT also supplies all
20261 language-defined pragmas introduced by Ada 95 and Ada 2005.
20262 In addition, GNAT implements the implementation-defined pragmas
20266 @item @code{AST_ENTRY}
20268 @item @code{COMMON_OBJECT}
20270 @item @code{COMPONENT_ALIGNMENT}
20272 @item @code{EXPORT_EXCEPTION}
20274 @item @code{EXPORT_FUNCTION}
20276 @item @code{EXPORT_OBJECT}
20278 @item @code{EXPORT_PROCEDURE}
20280 @item @code{EXPORT_VALUED_PROCEDURE}
20282 @item @code{FLOAT_REPRESENTATION}
20286 @item @code{IMPORT_EXCEPTION}
20288 @item @code{IMPORT_FUNCTION}
20290 @item @code{IMPORT_OBJECT}
20292 @item @code{IMPORT_PROCEDURE}
20294 @item @code{IMPORT_VALUED_PROCEDURE}
20296 @item @code{INLINE_GENERIC}
20298 @item @code{INTERFACE_NAME}
20300 @item @code{LONG_FLOAT}
20302 @item @code{MAIN_STORAGE}
20304 @item @code{PASSIVE}
20306 @item @code{PSECT_OBJECT}
20308 @item @code{SHARE_GENERIC}
20310 @item @code{SUPPRESS_ALL}
20312 @item @code{TASK_STORAGE}
20314 @item @code{TIME_SLICE}
20320 These pragmas are all fully implemented, with the exception of @code{TITLE},
20321 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20322 recognized, but which have no
20323 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20324 use of Ada protected objects. In GNAT, all generics are inlined.
20326 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20327 a separate subprogram specification which must appear before the
20330 GNAT also supplies a number of implementation-defined pragmas including the
20334 @item @code{ABORT_DEFER}
20336 @item @code{ADA_83}
20338 @item @code{ADA_95}
20340 @item @code{ADA_05}
20342 @item @code{Ada_2005}
20344 @item @code{Ada_12}
20346 @item @code{Ada_2012}
20348 @item @code{ANNOTATE}
20350 @item @code{ASSERT}
20352 @item @code{C_PASS_BY_COPY}
20354 @item @code{CPP_CLASS}
20356 @item @code{CPP_CONSTRUCTOR}
20358 @item @code{CPP_DESTRUCTOR}
20362 @item @code{EXTEND_SYSTEM}
20364 @item @code{LINKER_ALIAS}
20366 @item @code{LINKER_SECTION}
20368 @item @code{MACHINE_ATTRIBUTE}
20370 @item @code{NO_RETURN}
20372 @item @code{PURE_FUNCTION}
20374 @item @code{SOURCE_FILE_NAME}
20376 @item @code{SOURCE_REFERENCE}
20378 @item @code{TASK_INFO}
20380 @item @code{UNCHECKED_UNION}
20382 @item @code{UNIMPLEMENTED_UNIT}
20384 @item @code{UNIVERSAL_DATA}
20386 @item @code{UNSUPPRESS}
20388 @item @code{WARNINGS}
20390 @item @code{WEAK_EXTERNAL}
20394 For full details on these and other GNAT implementation-defined pragmas,
20395 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20399 * Restrictions on the Pragma INLINE::
20400 * Restrictions on the Pragma INTERFACE::
20401 * Restrictions on the Pragma SYSTEM_NAME::
20404 @node Restrictions on the Pragma INLINE
20405 @subsection Restrictions on Pragma @code{INLINE}
20408 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20410 @item Parameters cannot have a task type.
20412 @item Function results cannot be task types, unconstrained
20413 array types, or unconstrained types with discriminants.
20415 @item Bodies cannot declare the following:
20417 @item Subprogram body or stub (imported subprogram is allowed)
20421 @item Generic declarations
20423 @item Instantiations
20427 @item Access types (types derived from access types allowed)
20429 @item Array or record types
20431 @item Dependent tasks
20433 @item Direct recursive calls of subprogram or containing
20434 subprogram, directly or via a renaming
20440 In GNAT, the only restriction on pragma @code{INLINE} is that the
20441 body must occur before the call if both are in the same
20442 unit, and the size must be appropriately small. There are
20443 no other specific restrictions which cause subprograms to
20444 be incapable of being inlined.
20446 @node Restrictions on the Pragma INTERFACE
20447 @subsection Restrictions on Pragma @code{INTERFACE}
20450 The following restrictions on pragma @code{INTERFACE}
20451 are enforced by both HP Ada and GNAT:
20453 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
20454 Default is the default on OpenVMS Alpha systems.
20456 @item Parameter passing: Language specifies default
20457 mechanisms but can be overridden with an @code{EXPORT} pragma.
20460 @item Ada: Use internal Ada rules.
20462 @item Bliss, C: Parameters must be mode @code{in}; cannot be
20463 record or task type. Result cannot be a string, an
20464 array, or a record.
20466 @item Fortran: Parameters cannot have a task type. Result cannot
20467 be a string, an array, or a record.
20472 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20473 record parameters for all languages.
20475 @node Restrictions on the Pragma SYSTEM_NAME
20476 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
20479 For HP Ada for OpenVMS Alpha, the enumeration literal
20480 for the type @code{NAME} is @code{OPENVMS_AXP}.
20481 In GNAT, the enumeration
20482 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20484 @node Library of Predefined Units
20485 @section Library of Predefined Units
20488 A library of predefined units is provided as part of the
20489 HP Ada and GNAT implementations. HP Ada does not provide
20490 the package @code{MACHINE_CODE} but instead recommends importing
20493 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20494 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20496 The HP Ada Predefined Library units are modified to remove post-Ada 83
20497 incompatibilities and to make them interoperable with GNAT
20498 (@pxref{Changes to DECLIB}, for details).
20499 The units are located in the @file{DECLIB} directory.
20501 The GNAT RTL is contained in
20502 the @file{ADALIB} directory, and
20503 the default search path is set up to find @code{DECLIB} units in preference
20504 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20505 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20508 * Changes to DECLIB::
20511 @node Changes to DECLIB
20512 @subsection Changes to @code{DECLIB}
20515 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20516 compatibility are minor and include the following:
20519 @item Adjusting the location of pragmas and record representation
20520 clauses to obey Ada 95 (and thus Ada 2005) rules
20522 @item Adding the proper notation to generic formal parameters
20523 that take unconstrained types in instantiation
20525 @item Adding pragma @code{ELABORATE_BODY} to package specs
20526 that have package bodies not otherwise allowed
20528 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20529 ``@code{PROTECTD}''.
20530 Currently these are found only in the @code{STARLET} package spec.
20532 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20533 where the address size is constrained to 32 bits.
20537 None of the above changes is visible to users.
20543 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20546 @item Command Language Interpreter (CLI interface)
20548 @item DECtalk Run-Time Library (DTK interface)
20550 @item Librarian utility routines (LBR interface)
20552 @item General Purpose Run-Time Library (LIB interface)
20554 @item Math Run-Time Library (MTH interface)
20556 @item National Character Set Run-Time Library (NCS interface)
20558 @item Compiled Code Support Run-Time Library (OTS interface)
20560 @item Parallel Processing Run-Time Library (PPL interface)
20562 @item Screen Management Run-Time Library (SMG interface)
20564 @item Sort Run-Time Library (SOR interface)
20566 @item String Run-Time Library (STR interface)
20568 @item STARLET System Library
20571 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
20573 @item X Windows Toolkit (XT interface)
20575 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
20579 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20580 directory, on both the Alpha and I64 OpenVMS platforms.
20582 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20584 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20585 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20586 @code{Xt}, and @code{X_Lib}
20587 causing the default X/Motif sharable image libraries to be linked in. This
20588 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20589 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20591 It may be necessary to edit these options files to update or correct the
20592 library names if, for example, the newer X/Motif bindings from
20593 @file{ADA$EXAMPLES}
20594 had been (previous to installing GNAT) copied and renamed to supersede the
20595 default @file{ADA$PREDEFINED} versions.
20598 * Shared Libraries and Options Files::
20599 * Interfaces to C::
20602 @node Shared Libraries and Options Files
20603 @subsection Shared Libraries and Options Files
20606 When using the HP Ada
20607 predefined X and Motif bindings, the linking with their sharable images is
20608 done automatically by @command{GNAT LINK}.
20609 When using other X and Motif bindings, you need
20610 to add the corresponding sharable images to the command line for
20611 @code{GNAT LINK}. When linking with shared libraries, or with
20612 @file{.OPT} files, you must
20613 also add them to the command line for @command{GNAT LINK}.
20615 A shared library to be used with GNAT is built in the same way as other
20616 libraries under VMS. The VMS Link command can be used in standard fashion.
20618 @node Interfaces to C
20619 @subsection Interfaces to C
20623 provides the following Ada types and operations:
20626 @item C types package (@code{C_TYPES})
20628 @item C strings (@code{C_TYPES.NULL_TERMINATED})
20630 @item Other_types (@code{SHORT_INT})
20634 Interfacing to C with GNAT, you can use the above approach
20635 described for HP Ada or the facilities of Annex B of
20636 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
20637 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
20638 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
20640 The @option{-gnatF} qualifier forces default and explicit
20641 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
20642 to be uppercased for compatibility with the default behavior
20643 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
20645 @node Main Program Definition
20646 @section Main Program Definition
20649 The following section discusses differences in the
20650 definition of main programs on HP Ada and GNAT.
20651 On HP Ada, main programs are defined to meet the
20652 following conditions:
20654 @item Procedure with no formal parameters (returns @code{0} upon
20657 @item Procedure with no formal parameters (returns @code{42} when
20658 an unhandled exception is raised)
20660 @item Function with no formal parameters whose returned value
20661 is of a discrete type
20663 @item Procedure with one @code{out} formal of a discrete type for
20664 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
20669 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
20670 a main function or main procedure returns a discrete
20671 value whose size is less than 64 bits (32 on VAX systems),
20672 the value is zero- or sign-extended as appropriate.
20673 On GNAT, main programs are defined as follows:
20675 @item Must be a non-generic, parameterless subprogram that
20676 is either a procedure or function returning an Ada
20677 @code{STANDARD.INTEGER} (the predefined type)
20679 @item Cannot be a generic subprogram or an instantiation of a
20683 @node Implementation-Defined Attributes
20684 @section Implementation-Defined Attributes
20687 GNAT provides all HP Ada implementation-defined
20690 @node Compiler and Run-Time Interfacing
20691 @section Compiler and Run-Time Interfacing
20694 HP Ada provides the following qualifiers to pass options to the linker
20697 @item @option{/WAIT} and @option{/SUBMIT}
20699 @item @option{/COMMAND}
20701 @item @option{/@r{[}NO@r{]}MAP}
20703 @item @option{/OUTPUT=@var{file-spec}}
20705 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20709 To pass options to the linker, GNAT provides the following
20713 @item @option{/EXECUTABLE=@var{exec-name}}
20715 @item @option{/VERBOSE}
20717 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20721 For more information on these switches, see
20722 @ref{Switches for gnatlink}.
20723 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
20724 to control optimization. HP Ada also supplies the
20727 @item @code{OPTIMIZE}
20729 @item @code{INLINE}
20731 @item @code{INLINE_GENERIC}
20733 @item @code{SUPPRESS_ALL}
20735 @item @code{PASSIVE}
20739 In GNAT, optimization is controlled strictly by command
20740 line parameters, as described in the corresponding section of this guide.
20741 The HP pragmas for control of optimization are
20742 recognized but ignored.
20744 Note that in GNAT, the default is optimization off, whereas in HP Ada
20745 the default is that optimization is turned on.
20747 @node Program Compilation and Library Management
20748 @section Program Compilation and Library Management
20751 HP Ada and GNAT provide a comparable set of commands to
20752 build programs. HP Ada also provides a program library,
20753 which is a concept that does not exist on GNAT. Instead,
20754 GNAT provides directories of sources that are compiled as
20757 The following table summarizes
20758 the HP Ada commands and provides
20759 equivalent GNAT commands. In this table, some GNAT
20760 equivalents reflect the fact that GNAT does not use the
20761 concept of a program library. Instead, it uses a model
20762 in which collections of source and object files are used
20763 in a manner consistent with other languages like C and
20764 Fortran. Therefore, standard system file commands are used
20765 to manipulate these elements. Those GNAT commands are marked with
20767 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
20770 @multitable @columnfractions .35 .65
20772 @item @emph{HP Ada Command}
20773 @tab @emph{GNAT Equivalent / Description}
20775 @item @command{ADA}
20776 @tab @command{GNAT COMPILE}@*
20777 Invokes the compiler to compile one or more Ada source files.
20779 @item @command{ACS ATTACH}@*
20780 @tab [No equivalent]@*
20781 Switches control of terminal from current process running the program
20784 @item @command{ACS CHECK}
20785 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20786 Forms the execution closure of one
20787 or more compiled units and checks completeness and currency.
20789 @item @command{ACS COMPILE}
20790 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20791 Forms the execution closure of one or
20792 more specified units, checks completeness and currency,
20793 identifies units that have revised source files, compiles same,
20794 and recompiles units that are or will become obsolete.
20795 Also completes incomplete generic instantiations.
20797 @item @command{ACS COPY FOREIGN}
20799 Copies a foreign object file into the program library as a
20802 @item @command{ACS COPY UNIT}
20804 Copies a compiled unit from one program library to another.
20806 @item @command{ACS CREATE LIBRARY}
20807 @tab Create /directory (*)@*
20808 Creates a program library.
20810 @item @command{ACS CREATE SUBLIBRARY}
20811 @tab Create /directory (*)@*
20812 Creates a program sublibrary.
20814 @item @command{ACS DELETE LIBRARY}
20816 Deletes a program library and its contents.
20818 @item @command{ACS DELETE SUBLIBRARY}
20820 Deletes a program sublibrary and its contents.
20822 @item @command{ACS DELETE UNIT}
20823 @tab Delete file (*)@*
20824 On OpenVMS systems, deletes one or more compiled units from
20825 the current program library.
20827 @item @command{ACS DIRECTORY}
20828 @tab Directory (*)@*
20829 On OpenVMS systems, lists units contained in the current
20832 @item @command{ACS ENTER FOREIGN}
20834 Allows the import of a foreign body as an Ada library
20835 spec and enters a reference to a pointer.
20837 @item @command{ACS ENTER UNIT}
20839 Enters a reference (pointer) from the current program library to
20840 a unit compiled into another program library.
20842 @item @command{ACS EXIT}
20843 @tab [No equivalent]@*
20844 Exits from the program library manager.
20846 @item @command{ACS EXPORT}
20848 Creates an object file that contains system-specific object code
20849 for one or more units. With GNAT, object files can simply be copied
20850 into the desired directory.
20852 @item @command{ACS EXTRACT SOURCE}
20854 Allows access to the copied source file for each Ada compilation unit
20856 @item @command{ACS HELP}
20857 @tab @command{HELP GNAT}@*
20858 Provides online help.
20860 @item @command{ACS LINK}
20861 @tab @command{GNAT LINK}@*
20862 Links an object file containing Ada units into an executable file.
20864 @item @command{ACS LOAD}
20866 Loads (partially compiles) Ada units into the program library.
20867 Allows loading a program from a collection of files into a library
20868 without knowing the relationship among units.
20870 @item @command{ACS MERGE}
20872 Merges into the current program library, one or more units from
20873 another library where they were modified.
20875 @item @command{ACS RECOMPILE}
20876 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20877 Recompiles from external or copied source files any obsolete
20878 unit in the closure. Also, completes any incomplete generic
20881 @item @command{ACS REENTER}
20882 @tab @command{GNAT MAKE}@*
20883 Reenters current references to units compiled after last entered
20884 with the @command{ACS ENTER UNIT} command.
20886 @item @command{ACS SET LIBRARY}
20887 @tab Set default (*)@*
20888 Defines a program library to be the compilation context as well
20889 as the target library for compiler output and commands in general.
20891 @item @command{ACS SET PRAGMA}
20892 @tab Edit @file{gnat.adc} (*)@*
20893 Redefines specified values of the library characteristics
20894 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20895 and @code{Float_Representation}.
20897 @item @command{ACS SET SOURCE}
20898 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20899 Defines the source file search list for the @command{ACS COMPILE} command.
20901 @item @command{ACS SHOW LIBRARY}
20902 @tab Directory (*)@*
20903 Lists information about one or more program libraries.
20905 @item @command{ACS SHOW PROGRAM}
20906 @tab [No equivalent]@*
20907 Lists information about the execution closure of one or
20908 more units in the program library.
20910 @item @command{ACS SHOW SOURCE}
20911 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20912 Shows the source file search used when compiling units.
20914 @item @command{ACS SHOW VERSION}
20915 @tab Compile with @option{VERBOSE} option
20916 Displays the version number of the compiler and program library
20919 @item @command{ACS SPAWN}
20920 @tab [No equivalent]@*
20921 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20924 @item @command{ACS VERIFY}
20925 @tab [No equivalent]@*
20926 Performs a series of consistency checks on a program library to
20927 determine whether the library structure and library files are in
20934 @section Input-Output
20937 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
20938 Management Services (RMS) to perform operations on
20942 HP Ada and GNAT predefine an identical set of input-
20943 output packages. To make the use of the
20944 generic @code{TEXT_IO} operations more convenient, HP Ada
20945 provides predefined library packages that instantiate the
20946 integer and floating-point operations for the predefined
20947 integer and floating-point types as shown in the following table.
20949 @multitable @columnfractions .45 .55
20950 @item @emph{Package Name} @tab Instantiation
20952 @item @code{INTEGER_TEXT_IO}
20953 @tab @code{INTEGER_IO(INTEGER)}
20955 @item @code{SHORT_INTEGER_TEXT_IO}
20956 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20958 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20959 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20961 @item @code{FLOAT_TEXT_IO}
20962 @tab @code{FLOAT_IO(FLOAT)}
20964 @item @code{LONG_FLOAT_TEXT_IO}
20965 @tab @code{FLOAT_IO(LONG_FLOAT)}
20969 The HP Ada predefined packages and their operations
20970 are implemented using OpenVMS Alpha files and input-output
20971 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
20972 Familiarity with the following is recommended:
20974 @item RMS file organizations and access methods
20976 @item OpenVMS file specifications and directories
20978 @item OpenVMS File Definition Language (FDL)
20982 GNAT provides I/O facilities that are completely
20983 compatible with HP Ada. The distribution includes the
20984 standard HP Ada versions of all I/O packages, operating
20985 in a manner compatible with HP Ada. In particular, the
20986 following packages are by default the HP Ada (Ada 83)
20987 versions of these packages rather than the renamings
20988 suggested in Annex J of the Ada Reference Manual:
20990 @item @code{TEXT_IO}
20992 @item @code{SEQUENTIAL_IO}
20994 @item @code{DIRECT_IO}
20998 The use of the standard child package syntax (for
20999 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21001 GNAT provides HP-compatible predefined instantiations
21002 of the @code{TEXT_IO} packages, and also
21003 provides the standard predefined instantiations required
21004 by the @cite{Ada Reference Manual}.
21006 For further information on how GNAT interfaces to the file
21007 system or how I/O is implemented in programs written in
21008 mixed languages, see @ref{Implementation of the Standard I/O,,,
21009 gnat_rm, GNAT Reference Manual}.
21010 This chapter covers the following:
21012 @item Standard I/O packages
21014 @item @code{FORM} strings
21016 @item @code{ADA.DIRECT_IO}
21018 @item @code{ADA.SEQUENTIAL_IO}
21020 @item @code{ADA.TEXT_IO}
21022 @item Stream pointer positioning
21024 @item Reading and writing non-regular files
21026 @item @code{GET_IMMEDIATE}
21028 @item Treating @code{TEXT_IO} files as streams
21035 @node Implementation Limits
21036 @section Implementation Limits
21039 The following table lists implementation limits for HP Ada
21041 @multitable @columnfractions .60 .20 .20
21043 @item @emph{Compilation Parameter}
21048 @item In a subprogram or entry declaration, maximum number of
21049 formal parameters that are of an unconstrained record type
21054 @item Maximum identifier length (number of characters)
21059 @item Maximum number of characters in a source line
21064 @item Maximum collection size (number of bytes)
21069 @item Maximum number of discriminants for a record type
21074 @item Maximum number of formal parameters in an entry or
21075 subprogram declaration
21080 @item Maximum number of dimensions in an array type
21085 @item Maximum number of library units and subunits in a compilation.
21090 @item Maximum number of library units and subunits in an execution.
21095 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21096 or @code{PSECT_OBJECT}
21101 @item Maximum number of enumeration literals in an enumeration type
21107 @item Maximum number of lines in a source file
21112 @item Maximum number of bits in any object
21117 @item Maximum size of the static portion of a stack frame (approximate)
21122 @node Tools and Utilities
21123 @section Tools and Utilities
21126 The following table lists some of the OpenVMS development tools
21127 available for HP Ada, and the corresponding tools for
21128 use with @value{EDITION} on Alpha and I64 platforms.
21129 Aside from the debugger, all the OpenVMS tools identified are part
21130 of the DECset package.
21133 @c Specify table in TeX since Texinfo does a poor job
21137 \settabs\+Language-Sensitive Editor\quad
21138 &Product with HP Ada\quad
21141 &\it Product with HP Ada
21142 & \it Product with @value{EDITION}\cr
21144 \+Code Management System
21148 \+Language-Sensitive Editor
21150 & emacs or HP LSE (Alpha)\cr
21160 & OpenVMS Debug (I64)\cr
21162 \+Source Code Analyzer /
21179 \+Coverage Analyzer
21183 \+Module Management
21185 & Not applicable\cr
21195 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
21196 @c the TeX version above for the printed version
21198 @c @multitable @columnfractions .3 .4 .4
21199 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
21201 @tab @i{Tool with HP Ada}
21202 @tab @i{Tool with @value{EDITION}}
21203 @item Code Management@*System
21206 @item Language-Sensitive@*Editor
21208 @tab emacs or HP LSE (Alpha)
21217 @tab OpenVMS Debug (I64)
21218 @item Source Code Analyzer /@*Cross Referencer
21222 @tab HP Digital Test@*Manager (DTM)
21224 @item Performance and@*Coverage Analyzer
21227 @item Module Management@*System
21229 @tab Not applicable
21236 @c **************************************
21237 @node Platform-Specific Information for the Run-Time Libraries
21238 @appendix Platform-Specific Information for the Run-Time Libraries
21239 @cindex Tasking and threads libraries
21240 @cindex Threads libraries and tasking
21241 @cindex Run-time libraries (platform-specific information)
21244 The GNAT run-time implementation may vary with respect to both the
21245 underlying threads library and the exception handling scheme.
21246 For threads support, one or more of the following are supplied:
21248 @item @b{native threads library}, a binding to the thread package from
21249 the underlying operating system
21251 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21252 POSIX thread package
21256 For exception handling, either or both of two models are supplied:
21258 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21259 Most programs should experience a substantial speed improvement by
21260 being compiled with a ZCX run-time.
21261 This is especially true for
21262 tasking applications or applications with many exception handlers.}
21263 @cindex Zero-Cost Exceptions
21264 @cindex ZCX (Zero-Cost Exceptions)
21265 which uses binder-generated tables that
21266 are interrogated at run time to locate a handler
21268 @item @b{setjmp / longjmp} (``SJLJ''),
21269 @cindex setjmp/longjmp Exception Model
21270 @cindex SJLJ (setjmp/longjmp Exception Model)
21271 which uses dynamically-set data to establish
21272 the set of handlers
21276 This appendix summarizes which combinations of threads and exception support
21277 are supplied on various GNAT platforms.
21278 It then shows how to select a particular library either
21279 permanently or temporarily,
21280 explains the properties of (and tradeoffs among) the various threads
21281 libraries, and provides some additional
21282 information about several specific platforms.
21285 * Summary of Run-Time Configurations::
21286 * Specifying a Run-Time Library::
21287 * Choosing the Scheduling Policy::
21288 * Solaris-Specific Considerations::
21289 * Linux-Specific Considerations::
21290 * AIX-Specific Considerations::
21291 * Irix-Specific Considerations::
21292 * RTX-Specific Considerations::
21293 * HP-UX-Specific Considerations::
21296 @node Summary of Run-Time Configurations
21297 @section Summary of Run-Time Configurations
21299 @multitable @columnfractions .30 .70
21300 @item @b{alpha-openvms}
21301 @item @code{@ @ }@i{rts-native (default)}
21302 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21303 @item @code{@ @ @ @ }Exceptions @tab ZCX
21305 @item @b{alpha-tru64}
21306 @item @code{@ @ }@i{rts-native (default)}
21307 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21308 @item @code{@ @ @ @ }Exceptions @tab ZCX
21310 @item @code{@ @ }@i{rts-sjlj}
21311 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
21312 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21314 @item @b{ia64-hp_linux}
21315 @item @code{@ @ }@i{rts-native (default)}
21316 @item @code{@ @ @ @ }Tasking @tab pthread library
21317 @item @code{@ @ @ @ }Exceptions @tab ZCX
21319 @item @b{ia64-hpux}
21320 @item @code{@ @ }@i{rts-native (default)}
21321 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21322 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21324 @item @b{ia64-openvms}
21325 @item @code{@ @ }@i{rts-native (default)}
21326 @item @code{@ @ @ @ }Tasking @tab native VMS threads
21327 @item @code{@ @ @ @ }Exceptions @tab ZCX
21329 @item @b{ia64-sgi_linux}
21330 @item @code{@ @ }@i{rts-native (default)}
21331 @item @code{@ @ @ @ }Tasking @tab pthread library
21332 @item @code{@ @ @ @ }Exceptions @tab ZCX
21334 @item @b{mips-irix}
21335 @item @code{@ @ }@i{rts-native (default)}
21336 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
21337 @item @code{@ @ @ @ }Exceptions @tab ZCX
21340 @item @code{@ @ }@i{rts-native (default)}
21341 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21342 @item @code{@ @ @ @ }Exceptions @tab ZCX
21344 @item @code{@ @ }@i{rts-sjlj}
21345 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
21346 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21349 @item @code{@ @ }@i{rts-native (default)}
21350 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21351 @item @code{@ @ @ @ }Exceptions @tab ZCX
21353 @item @code{@ @ }@i{rts-sjlj}
21354 @item @code{@ @ @ @ }Tasking @tab native AIX threads
21355 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21357 @item @b{ppc-darwin}
21358 @item @code{@ @ }@i{rts-native (default)}
21359 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
21360 @item @code{@ @ @ @ }Exceptions @tab ZCX
21362 @item @b{sparc-solaris} @tab
21363 @item @code{@ @ }@i{rts-native (default)}
21364 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21365 @item @code{@ @ @ @ }Exceptions @tab ZCX
21367 @item @code{@ @ }@i{rts-pthread}
21368 @item @code{@ @ @ @ }Tasking @tab pthread library
21369 @item @code{@ @ @ @ }Exceptions @tab ZCX
21371 @item @code{@ @ }@i{rts-sjlj}
21372 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21373 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21375 @item @b{sparc64-solaris} @tab
21376 @item @code{@ @ }@i{rts-native (default)}
21377 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21378 @item @code{@ @ @ @ }Exceptions @tab ZCX
21380 @item @b{x86-linux}
21381 @item @code{@ @ }@i{rts-native (default)}
21382 @item @code{@ @ @ @ }Tasking @tab pthread library
21383 @item @code{@ @ @ @ }Exceptions @tab ZCX
21385 @item @code{@ @ }@i{rts-sjlj}
21386 @item @code{@ @ @ @ }Tasking @tab pthread library
21387 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21390 @item @code{@ @ }@i{rts-native (default)}
21391 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
21392 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21394 @item @b{x86-solaris}
21395 @item @code{@ @ }@i{rts-native (default)}
21396 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
21397 @item @code{@ @ @ @ }Exceptions @tab ZCX
21399 @item @code{@ @ }@i{rts-sjlj}
21400 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
21401 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21403 @item @b{x86-windows}
21404 @item @code{@ @ }@i{rts-native (default)}
21405 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21406 @item @code{@ @ @ @ }Exceptions @tab ZCX
21408 @item @code{@ @ }@i{rts-sjlj}
21409 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
21410 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21412 @item @b{x86-windows-rtx}
21413 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21414 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
21415 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21417 @item @code{@ @ }@i{rts-rtx-w32}
21418 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
21419 @item @code{@ @ @ @ }Exceptions @tab ZCX
21421 @item @b{x86_64-linux}
21422 @item @code{@ @ }@i{rts-native (default)}
21423 @item @code{@ @ @ @ }Tasking @tab pthread library
21424 @item @code{@ @ @ @ }Exceptions @tab ZCX
21426 @item @code{@ @ }@i{rts-sjlj}
21427 @item @code{@ @ @ @ }Tasking @tab pthread library
21428 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21432 @node Specifying a Run-Time Library
21433 @section Specifying a Run-Time Library
21436 The @file{adainclude} subdirectory containing the sources of the GNAT
21437 run-time library, and the @file{adalib} subdirectory containing the
21438 @file{ALI} files and the static and/or shared GNAT library, are located
21439 in the gcc target-dependent area:
21442 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21446 As indicated above, on some platforms several run-time libraries are supplied.
21447 These libraries are installed in the target dependent area and
21448 contain a complete source and binary subdirectory. The detailed description
21449 below explains the differences between the different libraries in terms of
21450 their thread support.
21452 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21453 This default run time is selected by the means of soft links.
21454 For example on x86-linux:
21460 +--- adainclude----------+
21462 +--- adalib-----------+ |
21464 +--- rts-native | |
21466 | +--- adainclude <---+
21468 | +--- adalib <----+
21479 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21480 these soft links can be modified with the following commands:
21484 $ rm -f adainclude adalib
21485 $ ln -s rts-sjlj/adainclude adainclude
21486 $ ln -s rts-sjlj/adalib adalib
21490 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21491 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21492 @file{$target/ada_object_path}.
21494 Selecting another run-time library temporarily can be
21495 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21496 @cindex @option{--RTS} option
21498 @node Choosing the Scheduling Policy
21499 @section Choosing the Scheduling Policy
21502 When using a POSIX threads implementation, you have a choice of several
21503 scheduling policies: @code{SCHED_FIFO},
21504 @cindex @code{SCHED_FIFO} scheduling policy
21506 @cindex @code{SCHED_RR} scheduling policy
21507 and @code{SCHED_OTHER}.
21508 @cindex @code{SCHED_OTHER} scheduling policy
21509 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21510 or @code{SCHED_RR} requires special (e.g., root) privileges.
21512 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21514 @cindex @code{SCHED_FIFO} scheduling policy
21515 you can use one of the following:
21519 @code{pragma Time_Slice (0.0)}
21520 @cindex pragma Time_Slice
21522 the corresponding binder option @option{-T0}
21523 @cindex @option{-T0} option
21525 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21526 @cindex pragma Task_Dispatching_Policy
21530 To specify @code{SCHED_RR},
21531 @cindex @code{SCHED_RR} scheduling policy
21532 you should use @code{pragma Time_Slice} with a
21533 value greater than @code{0.0}, or else use the corresponding @option{-T}
21536 @node Solaris-Specific Considerations
21537 @section Solaris-Specific Considerations
21538 @cindex Solaris Sparc threads libraries
21541 This section addresses some topics related to the various threads libraries
21545 * Solaris Threads Issues::
21548 @node Solaris Threads Issues
21549 @subsection Solaris Threads Issues
21552 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21553 library based on POSIX threads --- @emph{rts-pthread}.
21554 @cindex rts-pthread threads library
21555 This run-time library has the advantage of being mostly shared across all
21556 POSIX-compliant thread implementations, and it also provides under
21557 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21558 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21559 and @code{PTHREAD_PRIO_PROTECT}
21560 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21561 semantics that can be selected using the predefined pragma
21562 @code{Locking_Policy}
21563 @cindex pragma Locking_Policy (under rts-pthread)
21565 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21566 @cindex @code{Inheritance_Locking} (under rts-pthread)
21567 @cindex @code{Ceiling_Locking} (under rts-pthread)
21569 As explained above, the native run-time library is based on the Solaris thread
21570 library (@code{libthread}) and is the default library.
21572 When the Solaris threads library is used (this is the default), programs
21573 compiled with GNAT can automatically take advantage of
21574 and can thus execute on multiple processors.
21575 The user can alternatively specify a processor on which the program should run
21576 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21578 setting the environment variable @env{GNAT_PROCESSOR}
21579 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21580 to one of the following:
21584 Use the default configuration (run the program on all
21585 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21589 Let the run-time implementation choose one processor and run the program on
21592 @item 0 .. Last_Proc
21593 Run the program on the specified processor.
21594 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21595 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21598 @node Linux-Specific Considerations
21599 @section Linux-Specific Considerations
21600 @cindex Linux threads libraries
21603 On GNU/Linux without NPTL support (usually system with GNU C Library
21604 older than 2.3), the signal model is not POSIX compliant, which means
21605 that to send a signal to the process, you need to send the signal to all
21606 threads, e.g.@: by using @code{killpg()}.
21608 @node AIX-Specific Considerations
21609 @section AIX-Specific Considerations
21610 @cindex AIX resolver library
21613 On AIX, the resolver library initializes some internal structure on
21614 the first call to @code{get*by*} functions, which are used to implement
21615 @code{GNAT.Sockets.Get_Host_By_Name} and
21616 @code{GNAT.Sockets.Get_Host_By_Address}.
21617 If such initialization occurs within an Ada task, and the stack size for
21618 the task is the default size, a stack overflow may occur.
21620 To avoid this overflow, the user should either ensure that the first call
21621 to @code{GNAT.Sockets.Get_Host_By_Name} or
21622 @code{GNAT.Sockets.Get_Host_By_Addrss}
21623 occurs in the environment task, or use @code{pragma Storage_Size} to
21624 specify a sufficiently large size for the stack of the task that contains
21627 @node Irix-Specific Considerations
21628 @section Irix-Specific Considerations
21629 @cindex Irix libraries
21632 The GCC support libraries coming with the Irix compiler have moved to
21633 their canonical place with respect to the general Irix ABI related
21634 conventions. Running applications built with the default shared GNAT
21635 run-time now requires the LD_LIBRARY_PATH environment variable to
21636 include this location. A possible way to achieve this is to issue the
21637 following command line on a bash prompt:
21641 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
21645 @node RTX-Specific Considerations
21646 @section RTX-Specific Considerations
21647 @cindex RTX libraries
21650 The Real-time Extension (RTX) to Windows is based on the Windows Win32
21651 API. Applications can be built to work in two different modes:
21655 Windows executables that run in Ring 3 to utilize memory protection
21656 (@emph{rts-rtx-w32}).
21659 Real-time subsystem (RTSS) executables that run in Ring 0, where
21660 performance can be optimized with RTSS applications taking precedent
21661 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
21662 the Microsoft linker to handle RTSS libraries.
21666 @node HP-UX-Specific Considerations
21667 @section HP-UX-Specific Considerations
21668 @cindex HP-UX Scheduling
21671 On HP-UX, appropriate privileges are required to change the scheduling
21672 parameters of a task. The calling process must have appropriate
21673 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
21674 successfully change the scheduling parameters.
21676 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
21677 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
21678 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
21680 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
21681 one of the following:
21685 @code{pragma Time_Slice (0.0)}
21686 @cindex pragma Time_Slice
21688 the corresponding binder option @option{-T0}
21689 @cindex @option{-T0} option
21691 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21692 @cindex pragma Task_Dispatching_Policy
21696 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
21697 you should use @code{pragma Time_Slice} with a
21698 value greater than @code{0.0}, or use the corresponding @option{-T}
21699 binder option, or set the @code{pragma Task_Dispatching_Policy
21700 (Round_Robin_Within_Priorities)}.
21702 @c *******************************
21703 @node Example of Binder Output File
21704 @appendix Example of Binder Output File
21707 This Appendix displays the source code for @command{gnatbind}'s output
21708 file generated for a simple ``Hello World'' program.
21709 Comments have been added for clarification purposes.
21711 @smallexample @c adanocomment
21715 -- The package is called Ada_Main unless this name is actually used
21716 -- as a unit name in the partition, in which case some other unique
21720 package ada_main is
21722 Elab_Final_Code : Integer;
21723 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21725 -- The main program saves the parameters (argument count,
21726 -- argument values, environment pointer) in global variables
21727 -- for later access by other units including
21728 -- Ada.Command_Line.
21730 gnat_argc : Integer;
21731 gnat_argv : System.Address;
21732 gnat_envp : System.Address;
21734 -- The actual variables are stored in a library routine. This
21735 -- is useful for some shared library situations, where there
21736 -- are problems if variables are not in the library.
21738 pragma Import (C, gnat_argc);
21739 pragma Import (C, gnat_argv);
21740 pragma Import (C, gnat_envp);
21742 -- The exit status is similarly an external location
21744 gnat_exit_status : Integer;
21745 pragma Import (C, gnat_exit_status);
21747 GNAT_Version : constant String :=
21748 "GNAT Version: 6.0.0w (20061115)";
21749 pragma Export (C, GNAT_Version, "__gnat_version");
21751 -- This is the generated adafinal routine that performs
21752 -- finalization at the end of execution. In the case where
21753 -- Ada is the main program, this main program makes a call
21754 -- to adafinal at program termination.
21756 procedure adafinal;
21757 pragma Export (C, adafinal, "adafinal");
21759 -- This is the generated adainit routine that performs
21760 -- initialization at the start of execution. In the case
21761 -- where Ada is the main program, this main program makes
21762 -- a call to adainit at program startup.
21765 pragma Export (C, adainit, "adainit");
21767 -- This routine is called at the start of execution. It is
21768 -- a dummy routine that is used by the debugger to breakpoint
21769 -- at the start of execution.
21771 procedure Break_Start;
21772 pragma Import (C, Break_Start, "__gnat_break_start");
21774 -- This is the actual generated main program (it would be
21775 -- suppressed if the no main program switch were used). As
21776 -- required by standard system conventions, this program has
21777 -- the external name main.
21781 argv : System.Address;
21782 envp : System.Address)
21784 pragma Export (C, main, "main");
21786 -- The following set of constants give the version
21787 -- identification values for every unit in the bound
21788 -- partition. This identification is computed from all
21789 -- dependent semantic units, and corresponds to the
21790 -- string that would be returned by use of the
21791 -- Body_Version or Version attributes.
21793 type Version_32 is mod 2 ** 32;
21794 u00001 : constant Version_32 := 16#7880BEB3#;
21795 u00002 : constant Version_32 := 16#0D24CBD0#;
21796 u00003 : constant Version_32 := 16#3283DBEB#;
21797 u00004 : constant Version_32 := 16#2359F9ED#;
21798 u00005 : constant Version_32 := 16#664FB847#;
21799 u00006 : constant Version_32 := 16#68E803DF#;
21800 u00007 : constant Version_32 := 16#5572E604#;
21801 u00008 : constant Version_32 := 16#46B173D8#;
21802 u00009 : constant Version_32 := 16#156A40CF#;
21803 u00010 : constant Version_32 := 16#033DABE0#;
21804 u00011 : constant Version_32 := 16#6AB38FEA#;
21805 u00012 : constant Version_32 := 16#22B6217D#;
21806 u00013 : constant Version_32 := 16#68A22947#;
21807 u00014 : constant Version_32 := 16#18CC4A56#;
21808 u00015 : constant Version_32 := 16#08258E1B#;
21809 u00016 : constant Version_32 := 16#367D5222#;
21810 u00017 : constant Version_32 := 16#20C9ECA4#;
21811 u00018 : constant Version_32 := 16#50D32CB6#;
21812 u00019 : constant Version_32 := 16#39A8BB77#;
21813 u00020 : constant Version_32 := 16#5CF8FA2B#;
21814 u00021 : constant Version_32 := 16#2F1EB794#;
21815 u00022 : constant Version_32 := 16#31AB6444#;
21816 u00023 : constant Version_32 := 16#1574B6E9#;
21817 u00024 : constant Version_32 := 16#5109C189#;
21818 u00025 : constant Version_32 := 16#56D770CD#;
21819 u00026 : constant Version_32 := 16#02F9DE3D#;
21820 u00027 : constant Version_32 := 16#08AB6B2C#;
21821 u00028 : constant Version_32 := 16#3FA37670#;
21822 u00029 : constant Version_32 := 16#476457A0#;
21823 u00030 : constant Version_32 := 16#731E1B6E#;
21824 u00031 : constant Version_32 := 16#23C2E789#;
21825 u00032 : constant Version_32 := 16#0F1BD6A1#;
21826 u00033 : constant Version_32 := 16#7C25DE96#;
21827 u00034 : constant Version_32 := 16#39ADFFA2#;
21828 u00035 : constant Version_32 := 16#571DE3E7#;
21829 u00036 : constant Version_32 := 16#5EB646AB#;
21830 u00037 : constant Version_32 := 16#4249379B#;
21831 u00038 : constant Version_32 := 16#0357E00A#;
21832 u00039 : constant Version_32 := 16#3784FB72#;
21833 u00040 : constant Version_32 := 16#2E723019#;
21834 u00041 : constant Version_32 := 16#623358EA#;
21835 u00042 : constant Version_32 := 16#107F9465#;
21836 u00043 : constant Version_32 := 16#6843F68A#;
21837 u00044 : constant Version_32 := 16#63305874#;
21838 u00045 : constant Version_32 := 16#31E56CE1#;
21839 u00046 : constant Version_32 := 16#02917970#;
21840 u00047 : constant Version_32 := 16#6CCBA70E#;
21841 u00048 : constant Version_32 := 16#41CD4204#;
21842 u00049 : constant Version_32 := 16#572E3F58#;
21843 u00050 : constant Version_32 := 16#20729FF5#;
21844 u00051 : constant Version_32 := 16#1D4F93E8#;
21845 u00052 : constant Version_32 := 16#30B2EC3D#;
21846 u00053 : constant Version_32 := 16#34054F96#;
21847 u00054 : constant Version_32 := 16#5A199860#;
21848 u00055 : constant Version_32 := 16#0E7F912B#;
21849 u00056 : constant Version_32 := 16#5760634A#;
21850 u00057 : constant Version_32 := 16#5D851835#;
21852 -- The following Export pragmas export the version numbers
21853 -- with symbolic names ending in B (for body) or S
21854 -- (for spec) so that they can be located in a link. The
21855 -- information provided here is sufficient to track down
21856 -- the exact versions of units used in a given build.
21858 pragma Export (C, u00001, "helloB");
21859 pragma Export (C, u00002, "system__standard_libraryB");
21860 pragma Export (C, u00003, "system__standard_libraryS");
21861 pragma Export (C, u00004, "adaS");
21862 pragma Export (C, u00005, "ada__text_ioB");
21863 pragma Export (C, u00006, "ada__text_ioS");
21864 pragma Export (C, u00007, "ada__exceptionsB");
21865 pragma Export (C, u00008, "ada__exceptionsS");
21866 pragma Export (C, u00009, "gnatS");
21867 pragma Export (C, u00010, "gnat__heap_sort_aB");
21868 pragma Export (C, u00011, "gnat__heap_sort_aS");
21869 pragma Export (C, u00012, "systemS");
21870 pragma Export (C, u00013, "system__exception_tableB");
21871 pragma Export (C, u00014, "system__exception_tableS");
21872 pragma Export (C, u00015, "gnat__htableB");
21873 pragma Export (C, u00016, "gnat__htableS");
21874 pragma Export (C, u00017, "system__exceptionsS");
21875 pragma Export (C, u00018, "system__machine_state_operationsB");
21876 pragma Export (C, u00019, "system__machine_state_operationsS");
21877 pragma Export (C, u00020, "system__machine_codeS");
21878 pragma Export (C, u00021, "system__storage_elementsB");
21879 pragma Export (C, u00022, "system__storage_elementsS");
21880 pragma Export (C, u00023, "system__secondary_stackB");
21881 pragma Export (C, u00024, "system__secondary_stackS");
21882 pragma Export (C, u00025, "system__parametersB");
21883 pragma Export (C, u00026, "system__parametersS");
21884 pragma Export (C, u00027, "system__soft_linksB");
21885 pragma Export (C, u00028, "system__soft_linksS");
21886 pragma Export (C, u00029, "system__stack_checkingB");
21887 pragma Export (C, u00030, "system__stack_checkingS");
21888 pragma Export (C, u00031, "system__tracebackB");
21889 pragma Export (C, u00032, "system__tracebackS");
21890 pragma Export (C, u00033, "ada__streamsS");
21891 pragma Export (C, u00034, "ada__tagsB");
21892 pragma Export (C, u00035, "ada__tagsS");
21893 pragma Export (C, u00036, "system__string_opsB");
21894 pragma Export (C, u00037, "system__string_opsS");
21895 pragma Export (C, u00038, "interfacesS");
21896 pragma Export (C, u00039, "interfaces__c_streamsB");
21897 pragma Export (C, u00040, "interfaces__c_streamsS");
21898 pragma Export (C, u00041, "system__file_ioB");
21899 pragma Export (C, u00042, "system__file_ioS");
21900 pragma Export (C, u00043, "ada__finalizationB");
21901 pragma Export (C, u00044, "ada__finalizationS");
21902 pragma Export (C, u00045, "system__finalization_rootB");
21903 pragma Export (C, u00046, "system__finalization_rootS");
21904 pragma Export (C, u00047, "system__finalization_implementationB");
21905 pragma Export (C, u00048, "system__finalization_implementationS");
21906 pragma Export (C, u00049, "system__string_ops_concat_3B");
21907 pragma Export (C, u00050, "system__string_ops_concat_3S");
21908 pragma Export (C, u00051, "system__stream_attributesB");
21909 pragma Export (C, u00052, "system__stream_attributesS");
21910 pragma Export (C, u00053, "ada__io_exceptionsS");
21911 pragma Export (C, u00054, "system__unsigned_typesS");
21912 pragma Export (C, u00055, "system__file_control_blockS");
21913 pragma Export (C, u00056, "ada__finalization__list_controllerB");
21914 pragma Export (C, u00057, "ada__finalization__list_controllerS");
21916 -- BEGIN ELABORATION ORDER
21919 -- gnat.heap_sort_a (spec)
21920 -- gnat.heap_sort_a (body)
21921 -- gnat.htable (spec)
21922 -- gnat.htable (body)
21923 -- interfaces (spec)
21925 -- system.machine_code (spec)
21926 -- system.parameters (spec)
21927 -- system.parameters (body)
21928 -- interfaces.c_streams (spec)
21929 -- interfaces.c_streams (body)
21930 -- system.standard_library (spec)
21931 -- ada.exceptions (spec)
21932 -- system.exception_table (spec)
21933 -- system.exception_table (body)
21934 -- ada.io_exceptions (spec)
21935 -- system.exceptions (spec)
21936 -- system.storage_elements (spec)
21937 -- system.storage_elements (body)
21938 -- system.machine_state_operations (spec)
21939 -- system.machine_state_operations (body)
21940 -- system.secondary_stack (spec)
21941 -- system.stack_checking (spec)
21942 -- system.soft_links (spec)
21943 -- system.soft_links (body)
21944 -- system.stack_checking (body)
21945 -- system.secondary_stack (body)
21946 -- system.standard_library (body)
21947 -- system.string_ops (spec)
21948 -- system.string_ops (body)
21951 -- ada.streams (spec)
21952 -- system.finalization_root (spec)
21953 -- system.finalization_root (body)
21954 -- system.string_ops_concat_3 (spec)
21955 -- system.string_ops_concat_3 (body)
21956 -- system.traceback (spec)
21957 -- system.traceback (body)
21958 -- ada.exceptions (body)
21959 -- system.unsigned_types (spec)
21960 -- system.stream_attributes (spec)
21961 -- system.stream_attributes (body)
21962 -- system.finalization_implementation (spec)
21963 -- system.finalization_implementation (body)
21964 -- ada.finalization (spec)
21965 -- ada.finalization (body)
21966 -- ada.finalization.list_controller (spec)
21967 -- ada.finalization.list_controller (body)
21968 -- system.file_control_block (spec)
21969 -- system.file_io (spec)
21970 -- system.file_io (body)
21971 -- ada.text_io (spec)
21972 -- ada.text_io (body)
21974 -- END ELABORATION ORDER
21978 -- The following source file name pragmas allow the generated file
21979 -- names to be unique for different main programs. They are needed
21980 -- since the package name will always be Ada_Main.
21982 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21983 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21985 -- Generated package body for Ada_Main starts here
21987 package body ada_main is
21989 -- The actual finalization is performed by calling the
21990 -- library routine in System.Standard_Library.Adafinal
21992 procedure Do_Finalize;
21993 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22000 procedure adainit is
22002 -- These booleans are set to True once the associated unit has
22003 -- been elaborated. It is also used to avoid elaborating the
22004 -- same unit twice.
22007 pragma Import (Ada, E040, "interfaces__c_streams_E");
22010 pragma Import (Ada, E008, "ada__exceptions_E");
22013 pragma Import (Ada, E014, "system__exception_table_E");
22016 pragma Import (Ada, E053, "ada__io_exceptions_E");
22019 pragma Import (Ada, E017, "system__exceptions_E");
22022 pragma Import (Ada, E024, "system__secondary_stack_E");
22025 pragma Import (Ada, E030, "system__stack_checking_E");
22028 pragma Import (Ada, E028, "system__soft_links_E");
22031 pragma Import (Ada, E035, "ada__tags_E");
22034 pragma Import (Ada, E033, "ada__streams_E");
22037 pragma Import (Ada, E046, "system__finalization_root_E");
22040 pragma Import (Ada, E048, "system__finalization_implementation_E");
22043 pragma Import (Ada, E044, "ada__finalization_E");
22046 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22049 pragma Import (Ada, E055, "system__file_control_block_E");
22052 pragma Import (Ada, E042, "system__file_io_E");
22055 pragma Import (Ada, E006, "ada__text_io_E");
22057 -- Set_Globals is a library routine that stores away the
22058 -- value of the indicated set of global values in global
22059 -- variables within the library.
22061 procedure Set_Globals
22062 (Main_Priority : Integer;
22063 Time_Slice_Value : Integer;
22064 WC_Encoding : Character;
22065 Locking_Policy : Character;
22066 Queuing_Policy : Character;
22067 Task_Dispatching_Policy : Character;
22068 Adafinal : System.Address;
22069 Unreserve_All_Interrupts : Integer;
22070 Exception_Tracebacks : Integer);
22071 @findex __gnat_set_globals
22072 pragma Import (C, Set_Globals, "__gnat_set_globals");
22074 -- SDP_Table_Build is a library routine used to build the
22075 -- exception tables. See unit Ada.Exceptions in files
22076 -- a-except.ads/adb for full details of how zero cost
22077 -- exception handling works. This procedure, the call to
22078 -- it, and the two following tables are all omitted if the
22079 -- build is in longjmp/setjmp exception mode.
22081 @findex SDP_Table_Build
22082 @findex Zero Cost Exceptions
22083 procedure SDP_Table_Build
22084 (SDP_Addresses : System.Address;
22085 SDP_Count : Natural;
22086 Elab_Addresses : System.Address;
22087 Elab_Addr_Count : Natural);
22088 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22090 -- Table of Unit_Exception_Table addresses. Used for zero
22091 -- cost exception handling to build the top level table.
22093 ST : aliased constant array (1 .. 23) of System.Address := (
22095 Ada.Text_Io'UET_Address,
22096 Ada.Exceptions'UET_Address,
22097 Gnat.Heap_Sort_A'UET_Address,
22098 System.Exception_Table'UET_Address,
22099 System.Machine_State_Operations'UET_Address,
22100 System.Secondary_Stack'UET_Address,
22101 System.Parameters'UET_Address,
22102 System.Soft_Links'UET_Address,
22103 System.Stack_Checking'UET_Address,
22104 System.Traceback'UET_Address,
22105 Ada.Streams'UET_Address,
22106 Ada.Tags'UET_Address,
22107 System.String_Ops'UET_Address,
22108 Interfaces.C_Streams'UET_Address,
22109 System.File_Io'UET_Address,
22110 Ada.Finalization'UET_Address,
22111 System.Finalization_Root'UET_Address,
22112 System.Finalization_Implementation'UET_Address,
22113 System.String_Ops_Concat_3'UET_Address,
22114 System.Stream_Attributes'UET_Address,
22115 System.File_Control_Block'UET_Address,
22116 Ada.Finalization.List_Controller'UET_Address);
22118 -- Table of addresses of elaboration routines. Used for
22119 -- zero cost exception handling to make sure these
22120 -- addresses are included in the top level procedure
22123 EA : aliased constant array (1 .. 23) of System.Address := (
22124 adainit'Code_Address,
22125 Do_Finalize'Code_Address,
22126 Ada.Exceptions'Elab_Spec'Address,
22127 System.Exceptions'Elab_Spec'Address,
22128 Interfaces.C_Streams'Elab_Spec'Address,
22129 System.Exception_Table'Elab_Body'Address,
22130 Ada.Io_Exceptions'Elab_Spec'Address,
22131 System.Stack_Checking'Elab_Spec'Address,
22132 System.Soft_Links'Elab_Body'Address,
22133 System.Secondary_Stack'Elab_Body'Address,
22134 Ada.Tags'Elab_Spec'Address,
22135 Ada.Tags'Elab_Body'Address,
22136 Ada.Streams'Elab_Spec'Address,
22137 System.Finalization_Root'Elab_Spec'Address,
22138 Ada.Exceptions'Elab_Body'Address,
22139 System.Finalization_Implementation'Elab_Spec'Address,
22140 System.Finalization_Implementation'Elab_Body'Address,
22141 Ada.Finalization'Elab_Spec'Address,
22142 Ada.Finalization.List_Controller'Elab_Spec'Address,
22143 System.File_Control_Block'Elab_Spec'Address,
22144 System.File_Io'Elab_Body'Address,
22145 Ada.Text_Io'Elab_Spec'Address,
22146 Ada.Text_Io'Elab_Body'Address);
22148 -- Start of processing for adainit
22152 -- Call SDP_Table_Build to build the top level procedure
22153 -- table for zero cost exception handling (omitted in
22154 -- longjmp/setjmp mode).
22156 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22158 -- Call Set_Globals to record various information for
22159 -- this partition. The values are derived by the binder
22160 -- from information stored in the ali files by the compiler.
22162 @findex __gnat_set_globals
22164 (Main_Priority => -1,
22165 -- Priority of main program, -1 if no pragma Priority used
22167 Time_Slice_Value => -1,
22168 -- Time slice from Time_Slice pragma, -1 if none used
22170 WC_Encoding => 'b',
22171 -- Wide_Character encoding used, default is brackets
22173 Locking_Policy => ' ',
22174 -- Locking_Policy used, default of space means not
22175 -- specified, otherwise it is the first character of
22176 -- the policy name.
22178 Queuing_Policy => ' ',
22179 -- Queuing_Policy used, default of space means not
22180 -- specified, otherwise it is the first character of
22181 -- the policy name.
22183 Task_Dispatching_Policy => ' ',
22184 -- Task_Dispatching_Policy used, default of space means
22185 -- not specified, otherwise first character of the
22188 Adafinal => System.Null_Address,
22189 -- Address of Adafinal routine, not used anymore
22191 Unreserve_All_Interrupts => 0,
22192 -- Set true if pragma Unreserve_All_Interrupts was used
22194 Exception_Tracebacks => 0);
22195 -- Indicates if exception tracebacks are enabled
22197 Elab_Final_Code := 1;
22199 -- Now we have the elaboration calls for all units in the partition.
22200 -- The Elab_Spec and Elab_Body attributes generate references to the
22201 -- implicit elaboration procedures generated by the compiler for
22202 -- each unit that requires elaboration.
22205 Interfaces.C_Streams'Elab_Spec;
22209 Ada.Exceptions'Elab_Spec;
22212 System.Exception_Table'Elab_Body;
22216 Ada.Io_Exceptions'Elab_Spec;
22220 System.Exceptions'Elab_Spec;
22224 System.Stack_Checking'Elab_Spec;
22227 System.Soft_Links'Elab_Body;
22232 System.Secondary_Stack'Elab_Body;
22236 Ada.Tags'Elab_Spec;
22239 Ada.Tags'Elab_Body;
22243 Ada.Streams'Elab_Spec;
22247 System.Finalization_Root'Elab_Spec;
22251 Ada.Exceptions'Elab_Body;
22255 System.Finalization_Implementation'Elab_Spec;
22258 System.Finalization_Implementation'Elab_Body;
22262 Ada.Finalization'Elab_Spec;
22266 Ada.Finalization.List_Controller'Elab_Spec;
22270 System.File_Control_Block'Elab_Spec;
22274 System.File_Io'Elab_Body;
22278 Ada.Text_Io'Elab_Spec;
22281 Ada.Text_Io'Elab_Body;
22285 Elab_Final_Code := 0;
22293 procedure adafinal is
22302 -- main is actually a function, as in the ANSI C standard,
22303 -- defined to return the exit status. The three parameters
22304 -- are the argument count, argument values and environment
22307 @findex Main Program
22310 argv : System.Address;
22311 envp : System.Address)
22314 -- The initialize routine performs low level system
22315 -- initialization using a standard library routine which
22316 -- sets up signal handling and performs any other
22317 -- required setup. The routine can be found in file
22320 @findex __gnat_initialize
22321 procedure initialize;
22322 pragma Import (C, initialize, "__gnat_initialize");
22324 -- The finalize routine performs low level system
22325 -- finalization using a standard library routine. The
22326 -- routine is found in file a-final.c and in the standard
22327 -- distribution is a dummy routine that does nothing, so
22328 -- really this is a hook for special user finalization.
22330 @findex __gnat_finalize
22331 procedure finalize;
22332 pragma Import (C, finalize, "__gnat_finalize");
22334 -- We get to the main program of the partition by using
22335 -- pragma Import because if we try to with the unit and
22336 -- call it Ada style, then not only do we waste time
22337 -- recompiling it, but also, we don't really know the right
22338 -- switches (e.g.@: identifier character set) to be used
22341 procedure Ada_Main_Program;
22342 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22344 -- Start of processing for main
22347 -- Save global variables
22353 -- Call low level system initialization
22357 -- Call our generated Ada initialization routine
22361 -- This is the point at which we want the debugger to get
22366 -- Now we call the main program of the partition
22370 -- Perform Ada finalization
22374 -- Perform low level system finalization
22378 -- Return the proper exit status
22379 return (gnat_exit_status);
22382 -- This section is entirely comments, so it has no effect on the
22383 -- compilation of the Ada_Main package. It provides the list of
22384 -- object files and linker options, as well as some standard
22385 -- libraries needed for the link. The gnatlink utility parses
22386 -- this b~hello.adb file to read these comment lines to generate
22387 -- the appropriate command line arguments for the call to the
22388 -- system linker. The BEGIN/END lines are used for sentinels for
22389 -- this parsing operation.
22391 -- The exact file names will of course depend on the environment,
22392 -- host/target and location of files on the host system.
22394 @findex Object file list
22395 -- BEGIN Object file/option list
22398 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22399 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22400 -- END Object file/option list
22406 The Ada code in the above example is exactly what is generated by the
22407 binder. We have added comments to more clearly indicate the function
22408 of each part of the generated @code{Ada_Main} package.
22410 The code is standard Ada in all respects, and can be processed by any
22411 tools that handle Ada. In particular, it is possible to use the debugger
22412 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22413 suppose that for reasons that you do not understand, your program is crashing
22414 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22415 you can place a breakpoint on the call:
22417 @smallexample @c ada
22418 Ada.Text_Io'Elab_Body;
22422 and trace the elaboration routine for this package to find out where
22423 the problem might be (more usually of course you would be debugging
22424 elaboration code in your own application).
22426 @node Elaboration Order Handling in GNAT
22427 @appendix Elaboration Order Handling in GNAT
22428 @cindex Order of elaboration
22429 @cindex Elaboration control
22432 * Elaboration Code::
22433 * Checking the Elaboration Order::
22434 * Controlling the Elaboration Order::
22435 * Controlling Elaboration in GNAT - Internal Calls::
22436 * Controlling Elaboration in GNAT - External Calls::
22437 * Default Behavior in GNAT - Ensuring Safety::
22438 * Treatment of Pragma Elaborate::
22439 * Elaboration Issues for Library Tasks::
22440 * Mixing Elaboration Models::
22441 * What to Do If the Default Elaboration Behavior Fails::
22442 * Elaboration for Access-to-Subprogram Values::
22443 * Summary of Procedures for Elaboration Control::
22444 * Other Elaboration Order Considerations::
22448 This chapter describes the handling of elaboration code in Ada and
22449 in GNAT, and discusses how the order of elaboration of program units can
22450 be controlled in GNAT, either automatically or with explicit programming
22453 @node Elaboration Code
22454 @section Elaboration Code
22457 Ada provides rather general mechanisms for executing code at elaboration
22458 time, that is to say before the main program starts executing. Such code arises
22462 @item Initializers for variables.
22463 Variables declared at the library level, in package specs or bodies, can
22464 require initialization that is performed at elaboration time, as in:
22465 @smallexample @c ada
22467 Sqrt_Half : Float := Sqrt (0.5);
22471 @item Package initialization code
22472 Code in a @code{BEGIN-END} section at the outer level of a package body is
22473 executed as part of the package body elaboration code.
22475 @item Library level task allocators
22476 Tasks that are declared using task allocators at the library level
22477 start executing immediately and hence can execute at elaboration time.
22481 Subprogram calls are possible in any of these contexts, which means that
22482 any arbitrary part of the program may be executed as part of the elaboration
22483 code. It is even possible to write a program which does all its work at
22484 elaboration time, with a null main program, although stylistically this
22485 would usually be considered an inappropriate way to structure
22488 An important concern arises in the context of elaboration code:
22489 we have to be sure that it is executed in an appropriate order. What we
22490 have is a series of elaboration code sections, potentially one section
22491 for each unit in the program. It is important that these execute
22492 in the correct order. Correctness here means that, taking the above
22493 example of the declaration of @code{Sqrt_Half},
22494 if some other piece of
22495 elaboration code references @code{Sqrt_Half},
22496 then it must run after the
22497 section of elaboration code that contains the declaration of
22500 There would never be any order of elaboration problem if we made a rule
22501 that whenever you @code{with} a unit, you must elaborate both the spec and body
22502 of that unit before elaborating the unit doing the @code{with}'ing:
22504 @smallexample @c ada
22508 package Unit_2 is @dots{}
22514 would require that both the body and spec of @code{Unit_1} be elaborated
22515 before the spec of @code{Unit_2}. However, a rule like that would be far too
22516 restrictive. In particular, it would make it impossible to have routines
22517 in separate packages that were mutually recursive.
22519 You might think that a clever enough compiler could look at the actual
22520 elaboration code and determine an appropriate correct order of elaboration,
22521 but in the general case, this is not possible. Consider the following
22524 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22526 the variable @code{Sqrt_1}, which is declared in the elaboration code
22527 of the body of @code{Unit_1}:
22529 @smallexample @c ada
22531 Sqrt_1 : Float := Sqrt (0.1);
22536 The elaboration code of the body of @code{Unit_1} also contains:
22538 @smallexample @c ada
22541 if expression_1 = 1 then
22542 Q := Unit_2.Func_2;
22549 @code{Unit_2} is exactly parallel,
22550 it has a procedure @code{Func_2} that references
22551 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22552 the body @code{Unit_2}:
22554 @smallexample @c ada
22556 Sqrt_2 : Float := Sqrt (0.1);
22561 The elaboration code of the body of @code{Unit_2} also contains:
22563 @smallexample @c ada
22566 if expression_2 = 2 then
22567 Q := Unit_1.Func_1;
22574 Now the question is, which of the following orders of elaboration is
22599 If you carefully analyze the flow here, you will see that you cannot tell
22600 at compile time the answer to this question.
22601 If @code{expression_1} is not equal to 1,
22602 and @code{expression_2} is not equal to 2,
22603 then either order is acceptable, because neither of the function calls is
22604 executed. If both tests evaluate to true, then neither order is acceptable
22605 and in fact there is no correct order.
22607 If one of the two expressions is true, and the other is false, then one
22608 of the above orders is correct, and the other is incorrect. For example,
22609 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22610 then the call to @code{Func_1}
22611 will occur, but not the call to @code{Func_2.}
22612 This means that it is essential
22613 to elaborate the body of @code{Unit_1} before
22614 the body of @code{Unit_2}, so the first
22615 order of elaboration is correct and the second is wrong.
22617 By making @code{expression_1} and @code{expression_2}
22618 depend on input data, or perhaps
22619 the time of day, we can make it impossible for the compiler or binder
22620 to figure out which of these expressions will be true, and hence it
22621 is impossible to guarantee a safe order of elaboration at run time.
22623 @node Checking the Elaboration Order
22624 @section Checking the Elaboration Order
22627 In some languages that involve the same kind of elaboration problems,
22628 e.g.@: Java and C++, the programmer is expected to worry about these
22629 ordering problems himself, and it is common to
22630 write a program in which an incorrect elaboration order gives
22631 surprising results, because it references variables before they
22633 Ada is designed to be a safe language, and a programmer-beware approach is
22634 clearly not sufficient. Consequently, the language provides three lines
22638 @item Standard rules
22639 Some standard rules restrict the possible choice of elaboration
22640 order. In particular, if you @code{with} a unit, then its spec is always
22641 elaborated before the unit doing the @code{with}. Similarly, a parent
22642 spec is always elaborated before the child spec, and finally
22643 a spec is always elaborated before its corresponding body.
22645 @item Dynamic elaboration checks
22646 @cindex Elaboration checks
22647 @cindex Checks, elaboration
22648 Dynamic checks are made at run time, so that if some entity is accessed
22649 before it is elaborated (typically by means of a subprogram call)
22650 then the exception (@code{Program_Error}) is raised.
22652 @item Elaboration control
22653 Facilities are provided for the programmer to specify the desired order
22657 Let's look at these facilities in more detail. First, the rules for
22658 dynamic checking. One possible rule would be simply to say that the
22659 exception is raised if you access a variable which has not yet been
22660 elaborated. The trouble with this approach is that it could require
22661 expensive checks on every variable reference. Instead Ada has two
22662 rules which are a little more restrictive, but easier to check, and
22666 @item Restrictions on calls
22667 A subprogram can only be called at elaboration time if its body
22668 has been elaborated. The rules for elaboration given above guarantee
22669 that the spec of the subprogram has been elaborated before the
22670 call, but not the body. If this rule is violated, then the
22671 exception @code{Program_Error} is raised.
22673 @item Restrictions on instantiations
22674 A generic unit can only be instantiated if the body of the generic
22675 unit has been elaborated. Again, the rules for elaboration given above
22676 guarantee that the spec of the generic unit has been elaborated
22677 before the instantiation, but not the body. If this rule is
22678 violated, then the exception @code{Program_Error} is raised.
22682 The idea is that if the body has been elaborated, then any variables
22683 it references must have been elaborated; by checking for the body being
22684 elaborated we guarantee that none of its references causes any
22685 trouble. As we noted above, this is a little too restrictive, because a
22686 subprogram that has no non-local references in its body may in fact be safe
22687 to call. However, it really would be unsafe to rely on this, because
22688 it would mean that the caller was aware of details of the implementation
22689 in the body. This goes against the basic tenets of Ada.
22691 A plausible implementation can be described as follows.
22692 A Boolean variable is associated with each subprogram
22693 and each generic unit. This variable is initialized to False, and is set to
22694 True at the point body is elaborated. Every call or instantiation checks the
22695 variable, and raises @code{Program_Error} if the variable is False.
22697 Note that one might think that it would be good enough to have one Boolean
22698 variable for each package, but that would not deal with cases of trying
22699 to call a body in the same package as the call
22700 that has not been elaborated yet.
22701 Of course a compiler may be able to do enough analysis to optimize away
22702 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22703 does such optimizations, but still the easiest conceptual model is to
22704 think of there being one variable per subprogram.
22706 @node Controlling the Elaboration Order
22707 @section Controlling the Elaboration Order
22710 In the previous section we discussed the rules in Ada which ensure
22711 that @code{Program_Error} is raised if an incorrect elaboration order is
22712 chosen. This prevents erroneous executions, but we need mechanisms to
22713 specify a correct execution and avoid the exception altogether.
22714 To achieve this, Ada provides a number of features for controlling
22715 the order of elaboration. We discuss these features in this section.
22717 First, there are several ways of indicating to the compiler that a given
22718 unit has no elaboration problems:
22721 @item packages that do not require a body
22722 A library package that does not require a body does not permit
22723 a body (this rule was introduced in Ada 95).
22724 Thus if we have a such a package, as in:
22726 @smallexample @c ada
22729 package Definitions is
22731 type m is new integer;
22733 type a is array (1 .. 10) of m;
22734 type b is array (1 .. 20) of m;
22742 A package that @code{with}'s @code{Definitions} may safely instantiate
22743 @code{Definitions.Subp} because the compiler can determine that there
22744 definitely is no package body to worry about in this case
22747 @cindex pragma Pure
22749 Places sufficient restrictions on a unit to guarantee that
22750 no call to any subprogram in the unit can result in an
22751 elaboration problem. This means that the compiler does not need
22752 to worry about the point of elaboration of such units, and in
22753 particular, does not need to check any calls to any subprograms
22756 @item pragma Preelaborate
22757 @findex Preelaborate
22758 @cindex pragma Preelaborate
22759 This pragma places slightly less stringent restrictions on a unit than
22761 but these restrictions are still sufficient to ensure that there
22762 are no elaboration problems with any calls to the unit.
22764 @item pragma Elaborate_Body
22765 @findex Elaborate_Body
22766 @cindex pragma Elaborate_Body
22767 This pragma requires that the body of a unit be elaborated immediately
22768 after its spec. Suppose a unit @code{A} has such a pragma,
22769 and unit @code{B} does
22770 a @code{with} of unit @code{A}. Recall that the standard rules require
22771 the spec of unit @code{A}
22772 to be elaborated before the @code{with}'ing unit; given the pragma in
22773 @code{A}, we also know that the body of @code{A}
22774 will be elaborated before @code{B}, so
22775 that calls to @code{A} are safe and do not need a check.
22780 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22782 @code{Elaborate_Body} does not guarantee that the program is
22783 free of elaboration problems, because it may not be possible
22784 to satisfy the requested elaboration order.
22785 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22787 marks @code{Unit_1} as @code{Elaborate_Body},
22788 and not @code{Unit_2,} then the order of
22789 elaboration will be:
22801 Now that means that the call to @code{Func_1} in @code{Unit_2}
22802 need not be checked,
22803 it must be safe. But the call to @code{Func_2} in
22804 @code{Unit_1} may still fail if
22805 @code{Expression_1} is equal to 1,
22806 and the programmer must still take
22807 responsibility for this not being the case.
22809 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22810 eliminated, except for calls entirely within a body, which are
22811 in any case fully under programmer control. However, using the pragma
22812 everywhere is not always possible.
22813 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22814 we marked both of them as having pragma @code{Elaborate_Body}, then
22815 clearly there would be no possible elaboration order.
22817 The above pragmas allow a server to guarantee safe use by clients, and
22818 clearly this is the preferable approach. Consequently a good rule
22819 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22820 and if this is not possible,
22821 mark them as @code{Elaborate_Body} if possible.
22822 As we have seen, there are situations where neither of these
22823 three pragmas can be used.
22824 So we also provide methods for clients to control the
22825 order of elaboration of the servers on which they depend:
22828 @item pragma Elaborate (unit)
22830 @cindex pragma Elaborate
22831 This pragma is placed in the context clause, after a @code{with} clause,
22832 and it requires that the body of the named unit be elaborated before
22833 the unit in which the pragma occurs. The idea is to use this pragma
22834 if the current unit calls at elaboration time, directly or indirectly,
22835 some subprogram in the named unit.
22837 @item pragma Elaborate_All (unit)
22838 @findex Elaborate_All
22839 @cindex pragma Elaborate_All
22840 This is a stronger version of the Elaborate pragma. Consider the
22844 Unit A @code{with}'s unit B and calls B.Func in elab code
22845 Unit B @code{with}'s unit C, and B.Func calls C.Func
22849 Now if we put a pragma @code{Elaborate (B)}
22850 in unit @code{A}, this ensures that the
22851 body of @code{B} is elaborated before the call, but not the
22852 body of @code{C}, so
22853 the call to @code{C.Func} could still cause @code{Program_Error} to
22856 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22857 not only that the body of the named unit be elaborated before the
22858 unit doing the @code{with}, but also the bodies of all units that the
22859 named unit uses, following @code{with} links transitively. For example,
22860 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22862 not only that the body of @code{B} be elaborated before @code{A},
22864 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22868 We are now in a position to give a usage rule in Ada for avoiding
22869 elaboration problems, at least if dynamic dispatching and access to
22870 subprogram values are not used. We will handle these cases separately
22873 The rule is simple. If a unit has elaboration code that can directly or
22874 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22875 a generic package in a @code{with}'ed unit,
22876 then if the @code{with}'ed unit does not have
22877 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22878 a pragma @code{Elaborate_All}
22879 for the @code{with}'ed unit. By following this rule a client is
22880 assured that calls can be made without risk of an exception.
22882 For generic subprogram instantiations, the rule can be relaxed to
22883 require only a pragma @code{Elaborate} since elaborating the body
22884 of a subprogram cannot cause any transitive elaboration (we are
22885 not calling the subprogram in this case, just elaborating its
22888 If this rule is not followed, then a program may be in one of four
22892 @item No order exists
22893 No order of elaboration exists which follows the rules, taking into
22894 account any @code{Elaborate}, @code{Elaborate_All},
22895 or @code{Elaborate_Body} pragmas. In
22896 this case, an Ada compiler must diagnose the situation at bind
22897 time, and refuse to build an executable program.
22899 @item One or more orders exist, all incorrect
22900 One or more acceptable elaboration orders exist, and all of them
22901 generate an elaboration order problem. In this case, the binder
22902 can build an executable program, but @code{Program_Error} will be raised
22903 when the program is run.
22905 @item Several orders exist, some right, some incorrect
22906 One or more acceptable elaboration orders exists, and some of them
22907 work, and some do not. The programmer has not controlled
22908 the order of elaboration, so the binder may or may not pick one of
22909 the correct orders, and the program may or may not raise an
22910 exception when it is run. This is the worst case, because it means
22911 that the program may fail when moved to another compiler, or even
22912 another version of the same compiler.
22914 @item One or more orders exists, all correct
22915 One ore more acceptable elaboration orders exist, and all of them
22916 work. In this case the program runs successfully. This state of
22917 affairs can be guaranteed by following the rule we gave above, but
22918 may be true even if the rule is not followed.
22922 Note that one additional advantage of following our rules on the use
22923 of @code{Elaborate} and @code{Elaborate_All}
22924 is that the program continues to stay in the ideal (all orders OK) state
22925 even if maintenance
22926 changes some bodies of some units. Conversely, if a program that does
22927 not follow this rule happens to be safe at some point, this state of affairs
22928 may deteriorate silently as a result of maintenance changes.
22930 You may have noticed that the above discussion did not mention
22931 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22932 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22933 code in the body makes calls to some other unit, so it is still necessary
22934 to use @code{Elaborate_All} on such units.
22936 @node Controlling Elaboration in GNAT - Internal Calls
22937 @section Controlling Elaboration in GNAT - Internal Calls
22940 In the case of internal calls, i.e., calls within a single package, the
22941 programmer has full control over the order of elaboration, and it is up
22942 to the programmer to elaborate declarations in an appropriate order. For
22945 @smallexample @c ada
22948 function One return Float;
22952 function One return Float is
22961 will obviously raise @code{Program_Error} at run time, because function
22962 One will be called before its body is elaborated. In this case GNAT will
22963 generate a warning that the call will raise @code{Program_Error}:
22969 2. function One return Float;
22971 4. Q : Float := One;
22973 >>> warning: cannot call "One" before body is elaborated
22974 >>> warning: Program_Error will be raised at run time
22977 6. function One return Float is
22990 Note that in this particular case, it is likely that the call is safe, because
22991 the function @code{One} does not access any global variables.
22992 Nevertheless in Ada, we do not want the validity of the check to depend on
22993 the contents of the body (think about the separate compilation case), so this
22994 is still wrong, as we discussed in the previous sections.
22996 The error is easily corrected by rearranging the declarations so that the
22997 body of @code{One} appears before the declaration containing the call
22998 (note that in Ada 95 and Ada 2005,
22999 declarations can appear in any order, so there is no restriction that
23000 would prevent this reordering, and if we write:
23002 @smallexample @c ada
23005 function One return Float;
23007 function One return Float is
23018 then all is well, no warning is generated, and no
23019 @code{Program_Error} exception
23021 Things are more complicated when a chain of subprograms is executed:
23023 @smallexample @c ada
23026 function A return Integer;
23027 function B return Integer;
23028 function C return Integer;
23030 function B return Integer is begin return A; end;
23031 function C return Integer is begin return B; end;
23035 function A return Integer is begin return 1; end;
23041 Now the call to @code{C}
23042 at elaboration time in the declaration of @code{X} is correct, because
23043 the body of @code{C} is already elaborated,
23044 and the call to @code{B} within the body of
23045 @code{C} is correct, but the call
23046 to @code{A} within the body of @code{B} is incorrect, because the body
23047 of @code{A} has not been elaborated, so @code{Program_Error}
23048 will be raised on the call to @code{A}.
23049 In this case GNAT will generate a
23050 warning that @code{Program_Error} may be
23051 raised at the point of the call. Let's look at the warning:
23057 2. function A return Integer;
23058 3. function B return Integer;
23059 4. function C return Integer;
23061 6. function B return Integer is begin return A; end;
23063 >>> warning: call to "A" before body is elaborated may
23064 raise Program_Error
23065 >>> warning: "B" called at line 7
23066 >>> warning: "C" called at line 9
23068 7. function C return Integer is begin return B; end;
23070 9. X : Integer := C;
23072 11. function A return Integer is begin return 1; end;
23082 Note that the message here says ``may raise'', instead of the direct case,
23083 where the message says ``will be raised''. That's because whether
23085 actually called depends in general on run-time flow of control.
23086 For example, if the body of @code{B} said
23088 @smallexample @c ada
23091 function B return Integer is
23093 if some-condition-depending-on-input-data then
23104 then we could not know until run time whether the incorrect call to A would
23105 actually occur, so @code{Program_Error} might
23106 or might not be raised. It is possible for a compiler to
23107 do a better job of analyzing bodies, to
23108 determine whether or not @code{Program_Error}
23109 might be raised, but it certainly
23110 couldn't do a perfect job (that would require solving the halting problem
23111 and is provably impossible), and because this is a warning anyway, it does
23112 not seem worth the effort to do the analysis. Cases in which it
23113 would be relevant are rare.
23115 In practice, warnings of either of the forms given
23116 above will usually correspond to
23117 real errors, and should be examined carefully and eliminated.
23118 In the rare case where a warning is bogus, it can be suppressed by any of
23119 the following methods:
23123 Compile with the @option{-gnatws} switch set
23126 Suppress @code{Elaboration_Check} for the called subprogram
23129 Use pragma @code{Warnings_Off} to turn warnings off for the call
23133 For the internal elaboration check case,
23134 GNAT by default generates the
23135 necessary run-time checks to ensure
23136 that @code{Program_Error} is raised if any
23137 call fails an elaboration check. Of course this can only happen if a
23138 warning has been issued as described above. The use of pragma
23139 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23140 some of these checks, meaning that it may be possible (but is not
23141 guaranteed) for a program to be able to call a subprogram whose body
23142 is not yet elaborated, without raising a @code{Program_Error} exception.
23144 @node Controlling Elaboration in GNAT - External Calls
23145 @section Controlling Elaboration in GNAT - External Calls
23148 The previous section discussed the case in which the execution of a
23149 particular thread of elaboration code occurred entirely within a
23150 single unit. This is the easy case to handle, because a programmer
23151 has direct and total control over the order of elaboration, and
23152 furthermore, checks need only be generated in cases which are rare
23153 and which the compiler can easily detect.
23154 The situation is more complex when separate compilation is taken into account.
23155 Consider the following:
23157 @smallexample @c ada
23161 function Sqrt (Arg : Float) return Float;
23164 package body Math is
23165 function Sqrt (Arg : Float) return Float is
23174 X : Float := Math.Sqrt (0.5);
23187 where @code{Main} is the main program. When this program is executed, the
23188 elaboration code must first be executed, and one of the jobs of the
23189 binder is to determine the order in which the units of a program are
23190 to be elaborated. In this case we have four units: the spec and body
23192 the spec of @code{Stuff} and the body of @code{Main}).
23193 In what order should the four separate sections of elaboration code
23196 There are some restrictions in the order of elaboration that the binder
23197 can choose. In particular, if unit U has a @code{with}
23198 for a package @code{X}, then you
23199 are assured that the spec of @code{X}
23200 is elaborated before U , but you are
23201 not assured that the body of @code{X}
23202 is elaborated before U.
23203 This means that in the above case, the binder is allowed to choose the
23214 but that's not good, because now the call to @code{Math.Sqrt}
23215 that happens during
23216 the elaboration of the @code{Stuff}
23217 spec happens before the body of @code{Math.Sqrt} is
23218 elaborated, and hence causes @code{Program_Error} exception to be raised.
23219 At first glance, one might say that the binder is misbehaving, because
23220 obviously you want to elaborate the body of something you @code{with}
23222 that is not a general rule that can be followed in all cases. Consider
23224 @smallexample @c ada
23227 package X is @dots{}
23229 package Y is @dots{}
23232 package body Y is @dots{}
23235 package body X is @dots{}
23241 This is a common arrangement, and, apart from the order of elaboration
23242 problems that might arise in connection with elaboration code, this works fine.
23243 A rule that says that you must first elaborate the body of anything you
23244 @code{with} cannot work in this case:
23245 the body of @code{X} @code{with}'s @code{Y},
23246 which means you would have to
23247 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23249 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23250 loop that cannot be broken.
23252 It is true that the binder can in many cases guess an order of elaboration
23253 that is unlikely to cause a @code{Program_Error}
23254 exception to be raised, and it tries to do so (in the
23255 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23257 elaborate the body of @code{Math} right after its spec, so all will be well).
23259 However, a program that blindly relies on the binder to be helpful can
23260 get into trouble, as we discussed in the previous sections, so
23262 provides a number of facilities for assisting the programmer in
23263 developing programs that are robust with respect to elaboration order.
23265 @node Default Behavior in GNAT - Ensuring Safety
23266 @section Default Behavior in GNAT - Ensuring Safety
23269 The default behavior in GNAT ensures elaboration safety. In its
23270 default mode GNAT implements the
23271 rule we previously described as the right approach. Let's restate it:
23275 @emph{If a unit has elaboration code that can directly or indirectly make a
23276 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23277 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23278 does not have pragma @code{Pure} or
23279 @code{Preelaborate}, then the client should have an
23280 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23282 @emph{In the case of instantiating a generic subprogram, it is always
23283 sufficient to have only an @code{Elaborate} pragma for the
23284 @code{with}'ed unit.}
23288 By following this rule a client is assured that calls and instantiations
23289 can be made without risk of an exception.
23291 In this mode GNAT traces all calls that are potentially made from
23292 elaboration code, and puts in any missing implicit @code{Elaborate}
23293 and @code{Elaborate_All} pragmas.
23294 The advantage of this approach is that no elaboration problems
23295 are possible if the binder can find an elaboration order that is
23296 consistent with these implicit @code{Elaborate} and
23297 @code{Elaborate_All} pragmas. The
23298 disadvantage of this approach is that no such order may exist.
23300 If the binder does not generate any diagnostics, then it means that it has
23301 found an elaboration order that is guaranteed to be safe. However, the binder
23302 may still be relying on implicitly generated @code{Elaborate} and
23303 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23306 If it is important to guarantee portability, then the compilations should
23309 (warn on elaboration problems) switch. This will cause warning messages
23310 to be generated indicating the missing @code{Elaborate} and
23311 @code{Elaborate_All} pragmas.
23312 Consider the following source program:
23314 @smallexample @c ada
23319 m : integer := k.r;
23326 where it is clear that there
23327 should be a pragma @code{Elaborate_All}
23328 for unit @code{k}. An implicit pragma will be generated, and it is
23329 likely that the binder will be able to honor it. However, if you want
23330 to port this program to some other Ada compiler than GNAT.
23331 it is safer to include the pragma explicitly in the source. If this
23332 unit is compiled with the
23334 switch, then the compiler outputs a warning:
23341 3. m : integer := k.r;
23343 >>> warning: call to "r" may raise Program_Error
23344 >>> warning: missing pragma Elaborate_All for "k"
23352 and these warnings can be used as a guide for supplying manually
23353 the missing pragmas. It is usually a bad idea to use this warning
23354 option during development. That's because it will warn you when
23355 you need to put in a pragma, but cannot warn you when it is time
23356 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23357 unnecessary dependencies and even false circularities.
23359 This default mode is more restrictive than the Ada Reference
23360 Manual, and it is possible to construct programs which will compile
23361 using the dynamic model described there, but will run into a
23362 circularity using the safer static model we have described.
23364 Of course any Ada compiler must be able to operate in a mode
23365 consistent with the requirements of the Ada Reference Manual,
23366 and in particular must have the capability of implementing the
23367 standard dynamic model of elaboration with run-time checks.
23369 In GNAT, this standard mode can be achieved either by the use of
23370 the @option{-gnatE} switch on the compiler (@command{gcc} or
23371 @command{gnatmake}) command, or by the use of the configuration pragma:
23373 @smallexample @c ada
23374 pragma Elaboration_Checks (DYNAMIC);
23378 Either approach will cause the unit affected to be compiled using the
23379 standard dynamic run-time elaboration checks described in the Ada
23380 Reference Manual. The static model is generally preferable, since it
23381 is clearly safer to rely on compile and link time checks rather than
23382 run-time checks. However, in the case of legacy code, it may be
23383 difficult to meet the requirements of the static model. This
23384 issue is further discussed in
23385 @ref{What to Do If the Default Elaboration Behavior Fails}.
23387 Note that the static model provides a strict subset of the allowed
23388 behavior and programs of the Ada Reference Manual, so if you do
23389 adhere to the static model and no circularities exist,
23390 then you are assured that your program will
23391 work using the dynamic model, providing that you remove any
23392 pragma Elaborate statements from the source.
23394 @node Treatment of Pragma Elaborate
23395 @section Treatment of Pragma Elaborate
23396 @cindex Pragma Elaborate
23399 The use of @code{pragma Elaborate}
23400 should generally be avoided in Ada 95 and Ada 2005 programs,
23401 since there is no guarantee that transitive calls
23402 will be properly handled. Indeed at one point, this pragma was placed
23403 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23405 Now that's a bit restrictive. In practice, the case in which
23406 @code{pragma Elaborate} is useful is when the caller knows that there
23407 are no transitive calls, or that the called unit contains all necessary
23408 transitive @code{pragma Elaborate} statements, and legacy code often
23409 contains such uses.
23411 Strictly speaking the static mode in GNAT should ignore such pragmas,
23412 since there is no assurance at compile time that the necessary safety
23413 conditions are met. In practice, this would cause GNAT to be incompatible
23414 with correctly written Ada 83 code that had all necessary
23415 @code{pragma Elaborate} statements in place. Consequently, we made the
23416 decision that GNAT in its default mode will believe that if it encounters
23417 a @code{pragma Elaborate} then the programmer knows what they are doing,
23418 and it will trust that no elaboration errors can occur.
23420 The result of this decision is two-fold. First to be safe using the
23421 static mode, you should remove all @code{pragma Elaborate} statements.
23422 Second, when fixing circularities in existing code, you can selectively
23423 use @code{pragma Elaborate} statements to convince the static mode of
23424 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23427 When using the static mode with @option{-gnatwl}, any use of
23428 @code{pragma Elaborate} will generate a warning about possible
23431 @node Elaboration Issues for Library Tasks
23432 @section Elaboration Issues for Library Tasks
23433 @cindex Library tasks, elaboration issues
23434 @cindex Elaboration of library tasks
23437 In this section we examine special elaboration issues that arise for
23438 programs that declare library level tasks.
23440 Generally the model of execution of an Ada program is that all units are
23441 elaborated, and then execution of the program starts. However, the
23442 declaration of library tasks definitely does not fit this model. The
23443 reason for this is that library tasks start as soon as they are declared
23444 (more precisely, as soon as the statement part of the enclosing package
23445 body is reached), that is to say before elaboration
23446 of the program is complete. This means that if such a task calls a
23447 subprogram, or an entry in another task, the callee may or may not be
23448 elaborated yet, and in the standard
23449 Reference Manual model of dynamic elaboration checks, you can even
23450 get timing dependent Program_Error exceptions, since there can be
23451 a race between the elaboration code and the task code.
23453 The static model of elaboration in GNAT seeks to avoid all such
23454 dynamic behavior, by being conservative, and the conservative
23455 approach in this particular case is to assume that all the code
23456 in a task body is potentially executed at elaboration time if
23457 a task is declared at the library level.
23459 This can definitely result in unexpected circularities. Consider
23460 the following example
23462 @smallexample @c ada
23468 type My_Int is new Integer;
23470 function Ident (M : My_Int) return My_Int;
23474 package body Decls is
23475 task body Lib_Task is
23481 function Ident (M : My_Int) return My_Int is
23489 procedure Put_Val (Arg : Decls.My_Int);
23493 package body Utils is
23494 procedure Put_Val (Arg : Decls.My_Int) is
23496 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23503 Decls.Lib_Task.Start;
23508 If the above example is compiled in the default static elaboration
23509 mode, then a circularity occurs. The circularity comes from the call
23510 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23511 this call occurs in elaboration code, we need an implicit pragma
23512 @code{Elaborate_All} for @code{Utils}. This means that not only must
23513 the spec and body of @code{Utils} be elaborated before the body
23514 of @code{Decls}, but also the spec and body of any unit that is
23515 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23516 the body of @code{Decls}. This is the transitive implication of
23517 pragma @code{Elaborate_All} and it makes sense, because in general
23518 the body of @code{Put_Val} might have a call to something in a
23519 @code{with'ed} unit.
23521 In this case, the body of Utils (actually its spec) @code{with's}
23522 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23523 must be elaborated before itself, in case there is a call from the
23524 body of @code{Utils}.
23526 Here is the exact chain of events we are worrying about:
23530 In the body of @code{Decls} a call is made from within the body of a library
23531 task to a subprogram in the package @code{Utils}. Since this call may
23532 occur at elaboration time (given that the task is activated at elaboration
23533 time), we have to assume the worst, i.e., that the
23534 call does happen at elaboration time.
23537 This means that the body and spec of @code{Util} must be elaborated before
23538 the body of @code{Decls} so that this call does not cause an access before
23542 Within the body of @code{Util}, specifically within the body of
23543 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23547 One such @code{with}'ed package is package @code{Decls}, so there
23548 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23549 In fact there is such a call in this example, but we would have to
23550 assume that there was such a call even if it were not there, since
23551 we are not supposed to write the body of @code{Decls} knowing what
23552 is in the body of @code{Utils}; certainly in the case of the
23553 static elaboration model, the compiler does not know what is in
23554 other bodies and must assume the worst.
23557 This means that the spec and body of @code{Decls} must also be
23558 elaborated before we elaborate the unit containing the call, but
23559 that unit is @code{Decls}! This means that the body of @code{Decls}
23560 must be elaborated before itself, and that's a circularity.
23564 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23565 the body of @code{Decls} you will get a true Ada Reference Manual
23566 circularity that makes the program illegal.
23568 In practice, we have found that problems with the static model of
23569 elaboration in existing code often arise from library tasks, so
23570 we must address this particular situation.
23572 Note that if we compile and run the program above, using the dynamic model of
23573 elaboration (that is to say use the @option{-gnatE} switch),
23574 then it compiles, binds,
23575 links, and runs, printing the expected result of 2. Therefore in some sense
23576 the circularity here is only apparent, and we need to capture
23577 the properties of this program that distinguish it from other library-level
23578 tasks that have real elaboration problems.
23580 We have four possible answers to this question:
23585 Use the dynamic model of elaboration.
23587 If we use the @option{-gnatE} switch, then as noted above, the program works.
23588 Why is this? If we examine the task body, it is apparent that the task cannot
23590 @code{accept} statement until after elaboration has been completed, because
23591 the corresponding entry call comes from the main program, not earlier.
23592 This is why the dynamic model works here. But that's really giving
23593 up on a precise analysis, and we prefer to take this approach only if we cannot
23595 problem in any other manner. So let us examine two ways to reorganize
23596 the program to avoid the potential elaboration problem.
23599 Split library tasks into separate packages.
23601 Write separate packages, so that library tasks are isolated from
23602 other declarations as much as possible. Let us look at a variation on
23605 @smallexample @c ada
23613 package body Decls1 is
23614 task body Lib_Task is
23622 type My_Int is new Integer;
23623 function Ident (M : My_Int) return My_Int;
23627 package body Decls2 is
23628 function Ident (M : My_Int) return My_Int is
23636 procedure Put_Val (Arg : Decls2.My_Int);
23640 package body Utils is
23641 procedure Put_Val (Arg : Decls2.My_Int) is
23643 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23650 Decls1.Lib_Task.Start;
23655 All we have done is to split @code{Decls} into two packages, one
23656 containing the library task, and one containing everything else. Now
23657 there is no cycle, and the program compiles, binds, links and executes
23658 using the default static model of elaboration.
23661 Declare separate task types.
23663 A significant part of the problem arises because of the use of the
23664 single task declaration form. This means that the elaboration of
23665 the task type, and the elaboration of the task itself (i.e.@: the
23666 creation of the task) happen at the same time. A good rule
23667 of style in Ada is to always create explicit task types. By
23668 following the additional step of placing task objects in separate
23669 packages from the task type declaration, many elaboration problems
23670 are avoided. Here is another modified example of the example program:
23672 @smallexample @c ada
23674 task type Lib_Task_Type is
23678 type My_Int is new Integer;
23680 function Ident (M : My_Int) return My_Int;
23684 package body Decls is
23685 task body Lib_Task_Type is
23691 function Ident (M : My_Int) return My_Int is
23699 procedure Put_Val (Arg : Decls.My_Int);
23703 package body Utils is
23704 procedure Put_Val (Arg : Decls.My_Int) is
23706 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23712 Lib_Task : Decls.Lib_Task_Type;
23718 Declst.Lib_Task.Start;
23723 What we have done here is to replace the @code{task} declaration in
23724 package @code{Decls} with a @code{task type} declaration. Then we
23725 introduce a separate package @code{Declst} to contain the actual
23726 task object. This separates the elaboration issues for
23727 the @code{task type}
23728 declaration, which causes no trouble, from the elaboration issues
23729 of the task object, which is also unproblematic, since it is now independent
23730 of the elaboration of @code{Utils}.
23731 This separation of concerns also corresponds to
23732 a generally sound engineering principle of separating declarations
23733 from instances. This version of the program also compiles, binds, links,
23734 and executes, generating the expected output.
23737 Use No_Entry_Calls_In_Elaboration_Code restriction.
23738 @cindex No_Entry_Calls_In_Elaboration_Code
23740 The previous two approaches described how a program can be restructured
23741 to avoid the special problems caused by library task bodies. in practice,
23742 however, such restructuring may be difficult to apply to existing legacy code,
23743 so we must consider solutions that do not require massive rewriting.
23745 Let us consider more carefully why our original sample program works
23746 under the dynamic model of elaboration. The reason is that the code
23747 in the task body blocks immediately on the @code{accept}
23748 statement. Now of course there is nothing to prohibit elaboration
23749 code from making entry calls (for example from another library level task),
23750 so we cannot tell in isolation that
23751 the task will not execute the accept statement during elaboration.
23753 However, in practice it is very unusual to see elaboration code
23754 make any entry calls, and the pattern of tasks starting
23755 at elaboration time and then immediately blocking on @code{accept} or
23756 @code{select} statements is very common. What this means is that
23757 the compiler is being too pessimistic when it analyzes the
23758 whole package body as though it might be executed at elaboration
23761 If we know that the elaboration code contains no entry calls, (a very safe
23762 assumption most of the time, that could almost be made the default
23763 behavior), then we can compile all units of the program under control
23764 of the following configuration pragma:
23767 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23771 This pragma can be placed in the @file{gnat.adc} file in the usual
23772 manner. If we take our original unmodified program and compile it
23773 in the presence of a @file{gnat.adc} containing the above pragma,
23774 then once again, we can compile, bind, link, and execute, obtaining
23775 the expected result. In the presence of this pragma, the compiler does
23776 not trace calls in a task body, that appear after the first @code{accept}
23777 or @code{select} statement, and therefore does not report a potential
23778 circularity in the original program.
23780 The compiler will check to the extent it can that the above
23781 restriction is not violated, but it is not always possible to do a
23782 complete check at compile time, so it is important to use this
23783 pragma only if the stated restriction is in fact met, that is to say
23784 no task receives an entry call before elaboration of all units is completed.
23788 @node Mixing Elaboration Models
23789 @section Mixing Elaboration Models
23791 So far, we have assumed that the entire program is either compiled
23792 using the dynamic model or static model, ensuring consistency. It
23793 is possible to mix the two models, but rules have to be followed
23794 if this mixing is done to ensure that elaboration checks are not
23797 The basic rule is that @emph{a unit compiled with the static model cannot
23798 be @code{with'ed} by a unit compiled with the dynamic model}. The
23799 reason for this is that in the static model, a unit assumes that
23800 its clients guarantee to use (the equivalent of) pragma
23801 @code{Elaborate_All} so that no elaboration checks are required
23802 in inner subprograms, and this assumption is violated if the
23803 client is compiled with dynamic checks.
23805 The precise rule is as follows. A unit that is compiled with dynamic
23806 checks can only @code{with} a unit that meets at least one of the
23807 following criteria:
23812 The @code{with'ed} unit is itself compiled with dynamic elaboration
23813 checks (that is with the @option{-gnatE} switch.
23816 The @code{with'ed} unit is an internal GNAT implementation unit from
23817 the System, Interfaces, Ada, or GNAT hierarchies.
23820 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23823 The @code{with'ing} unit (that is the client) has an explicit pragma
23824 @code{Elaborate_All} for the @code{with'ed} unit.
23829 If this rule is violated, that is if a unit with dynamic elaboration
23830 checks @code{with's} a unit that does not meet one of the above four
23831 criteria, then the binder (@code{gnatbind}) will issue a warning
23832 similar to that in the following example:
23835 warning: "x.ads" has dynamic elaboration checks and with's
23836 warning: "y.ads" which has static elaboration checks
23840 These warnings indicate that the rule has been violated, and that as a result
23841 elaboration checks may be missed in the resulting executable file.
23842 This warning may be suppressed using the @option{-ws} binder switch
23843 in the usual manner.
23845 One useful application of this mixing rule is in the case of a subsystem
23846 which does not itself @code{with} units from the remainder of the
23847 application. In this case, the entire subsystem can be compiled with
23848 dynamic checks to resolve a circularity in the subsystem, while
23849 allowing the main application that uses this subsystem to be compiled
23850 using the more reliable default static model.
23852 @node What to Do If the Default Elaboration Behavior Fails
23853 @section What to Do If the Default Elaboration Behavior Fails
23856 If the binder cannot find an acceptable order, it outputs detailed
23857 diagnostics. For example:
23863 error: elaboration circularity detected
23864 info: "proc (body)" must be elaborated before "pack (body)"
23865 info: reason: Elaborate_All probably needed in unit "pack (body)"
23866 info: recompile "pack (body)" with -gnatwl
23867 info: for full details
23868 info: "proc (body)"
23869 info: is needed by its spec:
23870 info: "proc (spec)"
23871 info: which is withed by:
23872 info: "pack (body)"
23873 info: "pack (body)" must be elaborated before "proc (body)"
23874 info: reason: pragma Elaborate in unit "proc (body)"
23880 In this case we have a cycle that the binder cannot break. On the one
23881 hand, there is an explicit pragma Elaborate in @code{proc} for
23882 @code{pack}. This means that the body of @code{pack} must be elaborated
23883 before the body of @code{proc}. On the other hand, there is elaboration
23884 code in @code{pack} that calls a subprogram in @code{proc}. This means
23885 that for maximum safety, there should really be a pragma
23886 Elaborate_All in @code{pack} for @code{proc} which would require that
23887 the body of @code{proc} be elaborated before the body of
23888 @code{pack}. Clearly both requirements cannot be satisfied.
23889 Faced with a circularity of this kind, you have three different options.
23892 @item Fix the program
23893 The most desirable option from the point of view of long-term maintenance
23894 is to rearrange the program so that the elaboration problems are avoided.
23895 One useful technique is to place the elaboration code into separate
23896 child packages. Another is to move some of the initialization code to
23897 explicitly called subprograms, where the program controls the order
23898 of initialization explicitly. Although this is the most desirable option,
23899 it may be impractical and involve too much modification, especially in
23900 the case of complex legacy code.
23902 @item Perform dynamic checks
23903 If the compilations are done using the
23905 (dynamic elaboration check) switch, then GNAT behaves in a quite different
23906 manner. Dynamic checks are generated for all calls that could possibly result
23907 in raising an exception. With this switch, the compiler does not generate
23908 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
23909 exactly as specified in the @cite{Ada Reference Manual}.
23910 The binder will generate
23911 an executable program that may or may not raise @code{Program_Error}, and then
23912 it is the programmer's job to ensure that it does not raise an exception. Note
23913 that it is important to compile all units with the switch, it cannot be used
23916 @item Suppress checks
23917 The drawback of dynamic checks is that they generate a
23918 significant overhead at run time, both in space and time. If you
23919 are absolutely sure that your program cannot raise any elaboration
23920 exceptions, and you still want to use the dynamic elaboration model,
23921 then you can use the configuration pragma
23922 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23923 example this pragma could be placed in the @file{gnat.adc} file.
23925 @item Suppress checks selectively
23926 When you know that certain calls or instantiations in elaboration code cannot
23927 possibly lead to an elaboration error, and the binder nevertheless complains
23928 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
23929 elaboration circularities, it is possible to remove those warnings locally and
23930 obtain a program that will bind. Clearly this can be unsafe, and it is the
23931 responsibility of the programmer to make sure that the resulting program has no
23932 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
23933 used with different granularity to suppress warnings and break elaboration
23938 Place the pragma that names the called subprogram in the declarative part
23939 that contains the call.
23942 Place the pragma in the declarative part, without naming an entity. This
23943 disables warnings on all calls in the corresponding declarative region.
23946 Place the pragma in the package spec that declares the called subprogram,
23947 and name the subprogram. This disables warnings on all elaboration calls to
23951 Place the pragma in the package spec that declares the called subprogram,
23952 without naming any entity. This disables warnings on all elaboration calls to
23953 all subprograms declared in this spec.
23955 @item Use Pragma Elaborate
23956 As previously described in section @xref{Treatment of Pragma Elaborate},
23957 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23958 that no elaboration checks are required on calls to the designated unit.
23959 There may be cases in which the caller knows that no transitive calls
23960 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23961 case where @code{pragma Elaborate_All} would cause a circularity.
23965 These five cases are listed in order of decreasing safety, and therefore
23966 require increasing programmer care in their application. Consider the
23969 @smallexample @c adanocomment
23971 function F1 return Integer;
23976 function F2 return Integer;
23977 function Pure (x : integer) return integer;
23978 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
23979 -- pragma Suppress (Elaboration_Check); -- (4)
23983 package body Pack1 is
23984 function F1 return Integer is
23988 Val : integer := Pack2.Pure (11); -- Elab. call (1)
23991 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
23992 -- pragma Suppress(Elaboration_Check); -- (2)
23994 X1 := Pack2.F2 + 1; -- Elab. call (2)
23999 package body Pack2 is
24000 function F2 return Integer is
24004 function Pure (x : integer) return integer is
24006 return x ** 3 - 3 * x;
24010 with Pack1, Ada.Text_IO;
24013 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24016 In the absence of any pragmas, an attempt to bind this program produces
24017 the following diagnostics:
24023 error: elaboration circularity detected
24024 info: "pack1 (body)" must be elaborated before "pack1 (body)"
24025 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
24026 info: recompile "pack1 (body)" with -gnatwl for full details
24027 info: "pack1 (body)"
24028 info: must be elaborated along with its spec:
24029 info: "pack1 (spec)"
24030 info: which is withed by:
24031 info: "pack2 (body)"
24032 info: which must be elaborated along with its spec:
24033 info: "pack2 (spec)"
24034 info: which is withed by:
24035 info: "pack1 (body)"
24038 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24039 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24040 F2 is safe, even though F2 calls F1, because the call appears after the
24041 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24042 remove the warning on the call. It is also possible to use pragma (2)
24043 because there are no other potentially unsafe calls in the block.
24046 The call to @code{Pure} is safe because this function does not depend on the
24047 state of @code{Pack2}. Therefore any call to this function is safe, and it
24048 is correct to place pragma (3) in the corresponding package spec.
24051 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24052 warnings on all calls to functions declared therein. Note that this is not
24053 necessarily safe, and requires more detailed examination of the subprogram
24054 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24055 be already elaborated.
24059 It is hard to generalize on which of these four approaches should be
24060 taken. Obviously if it is possible to fix the program so that the default
24061 treatment works, this is preferable, but this may not always be practical.
24062 It is certainly simple enough to use
24064 but the danger in this case is that, even if the GNAT binder
24065 finds a correct elaboration order, it may not always do so,
24066 and certainly a binder from another Ada compiler might not. A
24067 combination of testing and analysis (for which the warnings generated
24070 switch can be useful) must be used to ensure that the program is free
24071 of errors. One switch that is useful in this testing is the
24072 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24075 Normally the binder tries to find an order that has the best chance
24076 of avoiding elaboration problems. However, if this switch is used, the binder
24077 plays a devil's advocate role, and tries to choose the order that
24078 has the best chance of failing. If your program works even with this
24079 switch, then it has a better chance of being error free, but this is still
24082 For an example of this approach in action, consider the C-tests (executable
24083 tests) from the ACVC suite. If these are compiled and run with the default
24084 treatment, then all but one of them succeed without generating any error
24085 diagnostics from the binder. However, there is one test that fails, and
24086 this is not surprising, because the whole point of this test is to ensure
24087 that the compiler can handle cases where it is impossible to determine
24088 a correct order statically, and it checks that an exception is indeed
24089 raised at run time.
24091 This one test must be compiled and run using the
24093 switch, and then it passes. Alternatively, the entire suite can
24094 be run using this switch. It is never wrong to run with the dynamic
24095 elaboration switch if your code is correct, and we assume that the
24096 C-tests are indeed correct (it is less efficient, but efficiency is
24097 not a factor in running the ACVC tests.)
24099 @node Elaboration for Access-to-Subprogram Values
24100 @section Elaboration for Access-to-Subprogram Values
24101 @cindex Access-to-subprogram
24104 Access-to-subprogram types (introduced in Ada 95) complicate
24105 the handling of elaboration. The trouble is that it becomes
24106 impossible to tell at compile time which procedure
24107 is being called. This means that it is not possible for the binder
24108 to analyze the elaboration requirements in this case.
24110 If at the point at which the access value is created
24111 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24112 the body of the subprogram is
24113 known to have been elaborated, then the access value is safe, and its use
24114 does not require a check. This may be achieved by appropriate arrangement
24115 of the order of declarations if the subprogram is in the current unit,
24116 or, if the subprogram is in another unit, by using pragma
24117 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24118 on the referenced unit.
24120 If the referenced body is not known to have been elaborated at the point
24121 the access value is created, then any use of the access value must do a
24122 dynamic check, and this dynamic check will fail and raise a
24123 @code{Program_Error} exception if the body has not been elaborated yet.
24124 GNAT will generate the necessary checks, and in addition, if the
24126 switch is set, will generate warnings that such checks are required.
24128 The use of dynamic dispatching for tagged types similarly generates
24129 a requirement for dynamic checks, and premature calls to any primitive
24130 operation of a tagged type before the body of the operation has been
24131 elaborated, will result in the raising of @code{Program_Error}.
24133 @node Summary of Procedures for Elaboration Control
24134 @section Summary of Procedures for Elaboration Control
24135 @cindex Elaboration control
24138 First, compile your program with the default options, using none of
24139 the special elaboration control switches. If the binder successfully
24140 binds your program, then you can be confident that, apart from issues
24141 raised by the use of access-to-subprogram types and dynamic dispatching,
24142 the program is free of elaboration errors. If it is important that the
24143 program be portable, then use the
24145 switch to generate warnings about missing @code{Elaborate} or
24146 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24148 If the program fails to bind using the default static elaboration
24149 handling, then you can fix the program to eliminate the binder
24150 message, or recompile the entire program with the
24151 @option{-gnatE} switch to generate dynamic elaboration checks,
24152 and, if you are sure there really are no elaboration problems,
24153 use a global pragma @code{Suppress (Elaboration_Check)}.
24155 @node Other Elaboration Order Considerations
24156 @section Other Elaboration Order Considerations
24158 This section has been entirely concerned with the issue of finding a valid
24159 elaboration order, as defined by the Ada Reference Manual. In a case
24160 where several elaboration orders are valid, the task is to find one
24161 of the possible valid elaboration orders (and the static model in GNAT
24162 will ensure that this is achieved).
24164 The purpose of the elaboration rules in the Ada Reference Manual is to
24165 make sure that no entity is accessed before it has been elaborated. For
24166 a subprogram, this means that the spec and body must have been elaborated
24167 before the subprogram is called. For an object, this means that the object
24168 must have been elaborated before its value is read or written. A violation
24169 of either of these two requirements is an access before elaboration order,
24170 and this section has been all about avoiding such errors.
24172 In the case where more than one order of elaboration is possible, in the
24173 sense that access before elaboration errors are avoided, then any one of
24174 the orders is ``correct'' in the sense that it meets the requirements of
24175 the Ada Reference Manual, and no such error occurs.
24177 However, it may be the case for a given program, that there are
24178 constraints on the order of elaboration that come not from consideration
24179 of avoiding elaboration errors, but rather from extra-lingual logic
24180 requirements. Consider this example:
24182 @smallexample @c ada
24183 with Init_Constants;
24184 package Constants is
24189 package Init_Constants is
24190 procedure P; -- require a body
24191 end Init_Constants;
24194 package body Init_Constants is
24195 procedure P is begin null; end;
24199 end Init_Constants;
24203 Z : Integer := Constants.X + Constants.Y;
24207 with Text_IO; use Text_IO;
24210 Put_Line (Calc.Z'Img);
24215 In this example, there is more than one valid order of elaboration. For
24216 example both the following are correct orders:
24219 Init_Constants spec
24222 Init_Constants body
24227 Init_Constants spec
24228 Init_Constants body
24235 There is no language rule to prefer one or the other, both are correct
24236 from an order of elaboration point of view. But the programmatic effects
24237 of the two orders are very different. In the first, the elaboration routine
24238 of @code{Calc} initializes @code{Z} to zero, and then the main program
24239 runs with this value of zero. But in the second order, the elaboration
24240 routine of @code{Calc} runs after the body of Init_Constants has set
24241 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24244 One could perhaps by applying pretty clever non-artificial intelligence
24245 to the situation guess that it is more likely that the second order of
24246 elaboration is the one desired, but there is no formal linguistic reason
24247 to prefer one over the other. In fact in this particular case, GNAT will
24248 prefer the second order, because of the rule that bodies are elaborated
24249 as soon as possible, but it's just luck that this is what was wanted
24250 (if indeed the second order was preferred).
24252 If the program cares about the order of elaboration routines in a case like
24253 this, it is important to specify the order required. In this particular
24254 case, that could have been achieved by adding to the spec of Calc:
24256 @smallexample @c ada
24257 pragma Elaborate_All (Constants);
24261 which requires that the body (if any) and spec of @code{Constants},
24262 as well as the body and spec of any unit @code{with}'ed by
24263 @code{Constants} be elaborated before @code{Calc} is elaborated.
24265 Clearly no automatic method can always guess which alternative you require,
24266 and if you are working with legacy code that had constraints of this kind
24267 which were not properly specified by adding @code{Elaborate} or
24268 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24269 compilers can choose different orders.
24271 However, GNAT does attempt to diagnose the common situation where there
24272 are uninitialized variables in the visible part of a package spec, and the
24273 corresponding package body has an elaboration block that directly or
24274 indirectly initialized one or more of these variables. This is the situation
24275 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24276 a warning that suggests this addition if it detects this situation.
24278 The @code{gnatbind}
24279 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24280 out problems. This switch causes bodies to be elaborated as late as possible
24281 instead of as early as possible. In the example above, it would have forced
24282 the choice of the first elaboration order. If you get different results
24283 when using this switch, and particularly if one set of results is right,
24284 and one is wrong as far as you are concerned, it shows that you have some
24285 missing @code{Elaborate} pragmas. For the example above, we have the
24289 gnatmake -f -q main
24292 gnatmake -f -q main -bargs -p
24298 It is of course quite unlikely that both these results are correct, so
24299 it is up to you in a case like this to investigate the source of the
24300 difference, by looking at the two elaboration orders that are chosen,
24301 and figuring out which is correct, and then adding the necessary
24302 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24306 @c *******************************
24307 @node Conditional Compilation
24308 @appendix Conditional Compilation
24309 @c *******************************
24310 @cindex Conditional compilation
24313 It is often necessary to arrange for a single source program
24314 to serve multiple purposes, where it is compiled in different
24315 ways to achieve these different goals. Some examples of the
24316 need for this feature are
24319 @item Adapting a program to a different hardware environment
24320 @item Adapting a program to a different target architecture
24321 @item Turning debugging features on and off
24322 @item Arranging for a program to compile with different compilers
24326 In C, or C++, the typical approach would be to use the preprocessor
24327 that is defined as part of the language. The Ada language does not
24328 contain such a feature. This is not an oversight, but rather a very
24329 deliberate design decision, based on the experience that overuse of
24330 the preprocessing features in C and C++ can result in programs that
24331 are extremely difficult to maintain. For example, if we have ten
24332 switches that can be on or off, this means that there are a thousand
24333 separate programs, any one of which might not even be syntactically
24334 correct, and even if syntactically correct, the resulting program
24335 might not work correctly. Testing all combinations can quickly become
24338 Nevertheless, the need to tailor programs certainly exists, and in
24339 this Appendix we will discuss how this can
24340 be achieved using Ada in general, and GNAT in particular.
24343 * Use of Boolean Constants::
24344 * Debugging - A Special Case::
24345 * Conditionalizing Declarations::
24346 * Use of Alternative Implementations::
24350 @node Use of Boolean Constants
24351 @section Use of Boolean Constants
24354 In the case where the difference is simply which code
24355 sequence is executed, the cleanest solution is to use Boolean
24356 constants to control which code is executed.
24358 @smallexample @c ada
24360 FP_Initialize_Required : constant Boolean := True;
24362 if FP_Initialize_Required then
24369 Not only will the code inside the @code{if} statement not be executed if
24370 the constant Boolean is @code{False}, but it will also be completely
24371 deleted from the program.
24372 However, the code is only deleted after the @code{if} statement
24373 has been checked for syntactic and semantic correctness.
24374 (In contrast, with preprocessors the code is deleted before the
24375 compiler ever gets to see it, so it is not checked until the switch
24377 @cindex Preprocessors (contrasted with conditional compilation)
24379 Typically the Boolean constants will be in a separate package,
24382 @smallexample @c ada
24385 FP_Initialize_Required : constant Boolean := True;
24386 Reset_Available : constant Boolean := False;
24393 The @code{Config} package exists in multiple forms for the various targets,
24394 with an appropriate script selecting the version of @code{Config} needed.
24395 Then any other unit requiring conditional compilation can do a @code{with}
24396 of @code{Config} to make the constants visible.
24399 @node Debugging - A Special Case
24400 @section Debugging - A Special Case
24403 A common use of conditional code is to execute statements (for example
24404 dynamic checks, or output of intermediate results) under control of a
24405 debug switch, so that the debugging behavior can be turned on and off.
24406 This can be done using a Boolean constant to control whether the code
24409 @smallexample @c ada
24412 Put_Line ("got to the first stage!");
24420 @smallexample @c ada
24422 if Debugging and then Temperature > 999.0 then
24423 raise Temperature_Crazy;
24429 Since this is a common case, there are special features to deal with
24430 this in a convenient manner. For the case of tests, Ada 2005 has added
24431 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24432 @cindex pragma @code{Assert}
24433 on the @code{Assert} pragma that has always been available in GNAT, so this
24434 feature may be used with GNAT even if you are not using Ada 2005 features.
24435 The use of pragma @code{Assert} is described in
24436 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24437 example, the last test could be written:
24439 @smallexample @c ada
24440 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24446 @smallexample @c ada
24447 pragma Assert (Temperature <= 999.0);
24451 In both cases, if assertions are active and the temperature is excessive,
24452 the exception @code{Assert_Failure} will be raised, with the given string in
24453 the first case or a string indicating the location of the pragma in the second
24454 case used as the exception message.
24456 You can turn assertions on and off by using the @code{Assertion_Policy}
24458 @cindex pragma @code{Assertion_Policy}
24459 This is an Ada 2005 pragma which is implemented in all modes by
24460 GNAT, but only in the latest versions of GNAT which include Ada 2005
24461 capability. Alternatively, you can use the @option{-gnata} switch
24462 @cindex @option{-gnata} switch
24463 to enable assertions from the command line (this is recognized by all versions
24466 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24467 @code{Debug} can be used:
24468 @cindex pragma @code{Debug}
24470 @smallexample @c ada
24471 pragma Debug (Put_Line ("got to the first stage!"));
24475 If debug pragmas are enabled, the argument, which must be of the form of
24476 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24477 Only one call can be present, but of course a special debugging procedure
24478 containing any code you like can be included in the program and then
24479 called in a pragma @code{Debug} argument as needed.
24481 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24482 construct is that pragma @code{Debug} can appear in declarative contexts,
24483 such as at the very beginning of a procedure, before local declarations have
24486 Debug pragmas are enabled using either the @option{-gnata} switch that also
24487 controls assertions, or with a separate Debug_Policy pragma.
24488 @cindex pragma @code{Debug_Policy}
24489 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24490 in Ada 95 and Ada 83 programs as well), and is analogous to
24491 pragma @code{Assertion_Policy} to control assertions.
24493 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24494 and thus they can appear in @file{gnat.adc} if you are not using a
24495 project file, or in the file designated to contain configuration pragmas
24497 They then apply to all subsequent compilations. In practice the use of
24498 the @option{-gnata} switch is often the most convenient method of controlling
24499 the status of these pragmas.
24501 Note that a pragma is not a statement, so in contexts where a statement
24502 sequence is required, you can't just write a pragma on its own. You have
24503 to add a @code{null} statement.
24505 @smallexample @c ada
24508 @dots{} -- some statements
24510 pragma Assert (Num_Cases < 10);
24517 @node Conditionalizing Declarations
24518 @section Conditionalizing Declarations
24521 In some cases, it may be necessary to conditionalize declarations to meet
24522 different requirements. For example we might want a bit string whose length
24523 is set to meet some hardware message requirement.
24525 In some cases, it may be possible to do this using declare blocks controlled
24526 by conditional constants:
24528 @smallexample @c ada
24530 if Small_Machine then
24532 X : Bit_String (1 .. 10);
24538 X : Large_Bit_String (1 .. 1000);
24547 Note that in this approach, both declarations are analyzed by the
24548 compiler so this can only be used where both declarations are legal,
24549 even though one of them will not be used.
24551 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
24552 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24553 that are parameterized by these constants. For example
24555 @smallexample @c ada
24558 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24564 If @code{Bits_Per_Word} is set to 32, this generates either
24566 @smallexample @c ada
24569 Field1 at 0 range 0 .. 32;
24575 for the big endian case, or
24577 @smallexample @c ada
24580 Field1 at 0 range 10 .. 32;
24586 for the little endian case. Since a powerful subset of Ada expression
24587 notation is usable for creating static constants, clever use of this
24588 feature can often solve quite difficult problems in conditionalizing
24589 compilation (note incidentally that in Ada 95, the little endian
24590 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24591 need to define this one yourself).
24594 @node Use of Alternative Implementations
24595 @section Use of Alternative Implementations
24598 In some cases, none of the approaches described above are adequate. This
24599 can occur for example if the set of declarations required is radically
24600 different for two different configurations.
24602 In this situation, the official Ada way of dealing with conditionalizing
24603 such code is to write separate units for the different cases. As long as
24604 this does not result in excessive duplication of code, this can be done
24605 without creating maintenance problems. The approach is to share common
24606 code as far as possible, and then isolate the code and declarations
24607 that are different. Subunits are often a convenient method for breaking
24608 out a piece of a unit that is to be conditionalized, with separate files
24609 for different versions of the subunit for different targets, where the
24610 build script selects the right one to give to the compiler.
24611 @cindex Subunits (and conditional compilation)
24613 As an example, consider a situation where a new feature in Ada 2005
24614 allows something to be done in a really nice way. But your code must be able
24615 to compile with an Ada 95 compiler. Conceptually you want to say:
24617 @smallexample @c ada
24620 @dots{} neat Ada 2005 code
24622 @dots{} not quite as neat Ada 95 code
24628 where @code{Ada_2005} is a Boolean constant.
24630 But this won't work when @code{Ada_2005} is set to @code{False},
24631 since the @code{then} clause will be illegal for an Ada 95 compiler.
24632 (Recall that although such unreachable code would eventually be deleted
24633 by the compiler, it still needs to be legal. If it uses features
24634 introduced in Ada 2005, it will be illegal in Ada 95.)
24636 So instead we write
24638 @smallexample @c ada
24639 procedure Insert is separate;
24643 Then we have two files for the subunit @code{Insert}, with the two sets of
24645 If the package containing this is called @code{File_Queries}, then we might
24649 @item @file{file_queries-insert-2005.adb}
24650 @item @file{file_queries-insert-95.adb}
24654 and the build script renames the appropriate file to
24657 file_queries-insert.adb
24661 and then carries out the compilation.
24663 This can also be done with project files' naming schemes. For example:
24665 @smallexample @c project
24666 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
24670 Note also that with project files it is desirable to use a different extension
24671 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
24672 conflict may arise through another commonly used feature: to declare as part
24673 of the project a set of directories containing all the sources obeying the
24674 default naming scheme.
24676 The use of alternative units is certainly feasible in all situations,
24677 and for example the Ada part of the GNAT run-time is conditionalized
24678 based on the target architecture using this approach. As a specific example,
24679 consider the implementation of the AST feature in VMS. There is one
24687 which is the same for all architectures, and three bodies:
24691 used for all non-VMS operating systems
24692 @item s-asthan-vms-alpha.adb
24693 used for VMS on the Alpha
24694 @item s-asthan-vms-ia64.adb
24695 used for VMS on the ia64
24699 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
24700 this operating system feature is not available, and the two remaining
24701 versions interface with the corresponding versions of VMS to provide
24702 VMS-compatible AST handling. The GNAT build script knows the architecture
24703 and operating system, and automatically selects the right version,
24704 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
24706 Another style for arranging alternative implementations is through Ada's
24707 access-to-subprogram facility.
24708 In case some functionality is to be conditionally included,
24709 you can declare an access-to-procedure variable @code{Ref} that is initialized
24710 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
24712 In some library package, set @code{Ref} to @code{Proc'Access} for some
24713 procedure @code{Proc} that performs the relevant processing.
24714 The initialization only occurs if the library package is included in the
24716 The same idea can also be implemented using tagged types and dispatching
24720 @node Preprocessing
24721 @section Preprocessing
24722 @cindex Preprocessing
24725 Although it is quite possible to conditionalize code without the use of
24726 C-style preprocessing, as described earlier in this section, it is
24727 nevertheless convenient in some cases to use the C approach. Moreover,
24728 older Ada compilers have often provided some preprocessing capability,
24729 so legacy code may depend on this approach, even though it is not
24732 To accommodate such use, GNAT provides a preprocessor (modeled to a large
24733 extent on the various preprocessors that have been used
24734 with legacy code on other compilers, to enable easier transition).
24736 The preprocessor may be used in two separate modes. It can be used quite
24737 separately from the compiler, to generate a separate output source file
24738 that is then fed to the compiler as a separate step. This is the
24739 @code{gnatprep} utility, whose use is fully described in
24740 @ref{Preprocessing Using gnatprep}.
24741 @cindex @code{gnatprep}
24743 The preprocessing language allows such constructs as
24747 #if DEBUG or PRIORITY > 4 then
24748 bunch of declarations
24750 completely different bunch of declarations
24756 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
24757 defined either on the command line or in a separate file.
24759 The other way of running the preprocessor is even closer to the C style and
24760 often more convenient. In this approach the preprocessing is integrated into
24761 the compilation process. The compiler is fed the preprocessor input which
24762 includes @code{#if} lines etc, and then the compiler carries out the
24763 preprocessing internally and processes the resulting output.
24764 For more details on this approach, see @ref{Integrated Preprocessing}.
24767 @c *******************************
24768 @node Inline Assembler
24769 @appendix Inline Assembler
24770 @c *******************************
24773 If you need to write low-level software that interacts directly
24774 with the hardware, Ada provides two ways to incorporate assembly
24775 language code into your program. First, you can import and invoke
24776 external routines written in assembly language, an Ada feature fully
24777 supported by GNAT@. However, for small sections of code it may be simpler
24778 or more efficient to include assembly language statements directly
24779 in your Ada source program, using the facilities of the implementation-defined
24780 package @code{System.Machine_Code}, which incorporates the gcc
24781 Inline Assembler. The Inline Assembler approach offers a number of advantages,
24782 including the following:
24785 @item No need to use non-Ada tools
24786 @item Consistent interface over different targets
24787 @item Automatic usage of the proper calling conventions
24788 @item Access to Ada constants and variables
24789 @item Definition of intrinsic routines
24790 @item Possibility of inlining a subprogram comprising assembler code
24791 @item Code optimizer can take Inline Assembler code into account
24794 This chapter presents a series of examples to show you how to use
24795 the Inline Assembler. Although it focuses on the Intel x86,
24796 the general approach applies also to other processors.
24797 It is assumed that you are familiar with Ada
24798 and with assembly language programming.
24801 * Basic Assembler Syntax::
24802 * A Simple Example of Inline Assembler::
24803 * Output Variables in Inline Assembler::
24804 * Input Variables in Inline Assembler::
24805 * Inlining Inline Assembler Code::
24806 * Other Asm Functionality::
24809 @c ---------------------------------------------------------------------------
24810 @node Basic Assembler Syntax
24811 @section Basic Assembler Syntax
24814 The assembler used by GNAT and gcc is based not on the Intel assembly
24815 language, but rather on a language that descends from the AT&T Unix
24816 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24817 The following table summarizes the main features of @emph{as} syntax
24818 and points out the differences from the Intel conventions.
24819 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24820 pre-processor) documentation for further information.
24823 @item Register names
24824 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24826 Intel: No extra punctuation; for example @code{eax}
24828 @item Immediate operand
24829 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24831 Intel: No extra punctuation; for example @code{4}
24834 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24836 Intel: No extra punctuation; for example @code{loc}
24838 @item Memory contents
24839 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24841 Intel: Square brackets; for example @code{[loc]}
24843 @item Register contents
24844 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24846 Intel: Square brackets; for example @code{[eax]}
24848 @item Hexadecimal numbers
24849 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24851 Intel: Trailing ``h''; for example @code{A0h}
24854 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24857 Intel: Implicit, deduced by assembler; for example @code{mov}
24859 @item Instruction repetition
24860 gcc / @emph{as}: Split into two lines; for example
24866 Intel: Keep on one line; for example @code{rep stosl}
24868 @item Order of operands
24869 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24871 Intel: Destination first; for example @code{mov eax, 4}
24874 @c ---------------------------------------------------------------------------
24875 @node A Simple Example of Inline Assembler
24876 @section A Simple Example of Inline Assembler
24879 The following example will generate a single assembly language statement,
24880 @code{nop}, which does nothing. Despite its lack of run-time effect,
24881 the example will be useful in illustrating the basics of
24882 the Inline Assembler facility.
24884 @smallexample @c ada
24886 with System.Machine_Code; use System.Machine_Code;
24887 procedure Nothing is
24894 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24895 here it takes one parameter, a @emph{template string} that must be a static
24896 expression and that will form the generated instruction.
24897 @code{Asm} may be regarded as a compile-time procedure that parses
24898 the template string and additional parameters (none here),
24899 from which it generates a sequence of assembly language instructions.
24901 The examples in this chapter will illustrate several of the forms
24902 for invoking @code{Asm}; a complete specification of the syntax
24903 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
24906 Under the standard GNAT conventions, the @code{Nothing} procedure
24907 should be in a file named @file{nothing.adb}.
24908 You can build the executable in the usual way:
24912 However, the interesting aspect of this example is not its run-time behavior
24913 but rather the generated assembly code.
24914 To see this output, invoke the compiler as follows:
24916 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24918 where the options are:
24922 compile only (no bind or link)
24924 generate assembler listing
24925 @item -fomit-frame-pointer
24926 do not set up separate stack frames
24928 do not add runtime checks
24931 This gives a human-readable assembler version of the code. The resulting
24932 file will have the same name as the Ada source file, but with a @code{.s}
24933 extension. In our example, the file @file{nothing.s} has the following
24938 .file "nothing.adb"
24940 ___gnu_compiled_ada:
24943 .globl __ada_nothing
24955 The assembly code you included is clearly indicated by
24956 the compiler, between the @code{#APP} and @code{#NO_APP}
24957 delimiters. The character before the 'APP' and 'NOAPP'
24958 can differ on different targets. For example, GNU/Linux uses '#APP' while
24959 on NT you will see '/APP'.
24961 If you make a mistake in your assembler code (such as using the
24962 wrong size modifier, or using a wrong operand for the instruction) GNAT
24963 will report this error in a temporary file, which will be deleted when
24964 the compilation is finished. Generating an assembler file will help
24965 in such cases, since you can assemble this file separately using the
24966 @emph{as} assembler that comes with gcc.
24968 Assembling the file using the command
24971 as @file{nothing.s}
24974 will give you error messages whose lines correspond to the assembler
24975 input file, so you can easily find and correct any mistakes you made.
24976 If there are no errors, @emph{as} will generate an object file
24977 @file{nothing.out}.
24979 @c ---------------------------------------------------------------------------
24980 @node Output Variables in Inline Assembler
24981 @section Output Variables in Inline Assembler
24984 The examples in this section, showing how to access the processor flags,
24985 illustrate how to specify the destination operands for assembly language
24988 @smallexample @c ada
24990 with Interfaces; use Interfaces;
24991 with Ada.Text_IO; use Ada.Text_IO;
24992 with System.Machine_Code; use System.Machine_Code;
24993 procedure Get_Flags is
24994 Flags : Unsigned_32;
24997 Asm ("pushfl" & LF & HT & -- push flags on stack
24998 "popl %%eax" & LF & HT & -- load eax with flags
24999 "movl %%eax, %0", -- store flags in variable
25000 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25001 Put_Line ("Flags register:" & Flags'Img);
25006 In order to have a nicely aligned assembly listing, we have separated
25007 multiple assembler statements in the Asm template string with linefeed
25008 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25009 The resulting section of the assembly output file is:
25016 movl %eax, -40(%ebp)
25021 It would have been legal to write the Asm invocation as:
25024 Asm ("pushfl popl %%eax movl %%eax, %0")
25027 but in the generated assembler file, this would come out as:
25031 pushfl popl %eax movl %eax, -40(%ebp)
25035 which is not so convenient for the human reader.
25037 We use Ada comments
25038 at the end of each line to explain what the assembler instructions
25039 actually do. This is a useful convention.
25041 When writing Inline Assembler instructions, you need to precede each register
25042 and variable name with a percent sign. Since the assembler already requires
25043 a percent sign at the beginning of a register name, you need two consecutive
25044 percent signs for such names in the Asm template string, thus @code{%%eax}.
25045 In the generated assembly code, one of the percent signs will be stripped off.
25047 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25048 variables: operands you later define using @code{Input} or @code{Output}
25049 parameters to @code{Asm}.
25050 An output variable is illustrated in
25051 the third statement in the Asm template string:
25055 The intent is to store the contents of the eax register in a variable that can
25056 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
25057 necessarily work, since the compiler might optimize by using a register
25058 to hold Flags, and the expansion of the @code{movl} instruction would not be
25059 aware of this optimization. The solution is not to store the result directly
25060 but rather to advise the compiler to choose the correct operand form;
25061 that is the purpose of the @code{%0} output variable.
25063 Information about the output variable is supplied in the @code{Outputs}
25064 parameter to @code{Asm}:
25066 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25069 The output is defined by the @code{Asm_Output} attribute of the target type;
25070 the general format is
25072 Type'Asm_Output (constraint_string, variable_name)
25075 The constraint string directs the compiler how
25076 to store/access the associated variable. In the example
25078 Unsigned_32'Asm_Output ("=m", Flags);
25080 the @code{"m"} (memory) constraint tells the compiler that the variable
25081 @code{Flags} should be stored in a memory variable, thus preventing
25082 the optimizer from keeping it in a register. In contrast,
25084 Unsigned_32'Asm_Output ("=r", Flags);
25086 uses the @code{"r"} (register) constraint, telling the compiler to
25087 store the variable in a register.
25089 If the constraint is preceded by the equal character (@strong{=}), it tells
25090 the compiler that the variable will be used to store data into it.
25092 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25093 allowing the optimizer to choose whatever it deems best.
25095 There are a fairly large number of constraints, but the ones that are
25096 most useful (for the Intel x86 processor) are the following:
25102 global (i.e.@: can be stored anywhere)
25120 use one of eax, ebx, ecx or edx
25122 use one of eax, ebx, ecx, edx, esi or edi
25125 The full set of constraints is described in the gcc and @emph{as}
25126 documentation; note that it is possible to combine certain constraints
25127 in one constraint string.
25129 You specify the association of an output variable with an assembler operand
25130 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25132 @smallexample @c ada
25134 Asm ("pushfl" & LF & HT & -- push flags on stack
25135 "popl %%eax" & LF & HT & -- load eax with flags
25136 "movl %%eax, %0", -- store flags in variable
25137 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25141 @code{%0} will be replaced in the expanded code by the appropriate operand,
25143 the compiler decided for the @code{Flags} variable.
25145 In general, you may have any number of output variables:
25148 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25150 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25151 of @code{Asm_Output} attributes
25155 @smallexample @c ada
25157 Asm ("movl %%eax, %0" & LF & HT &
25158 "movl %%ebx, %1" & LF & HT &
25160 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
25161 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
25162 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
25166 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25167 in the Ada program.
25169 As a variation on the @code{Get_Flags} example, we can use the constraints
25170 string to direct the compiler to store the eax register into the @code{Flags}
25171 variable, instead of including the store instruction explicitly in the
25172 @code{Asm} template string:
25174 @smallexample @c ada
25176 with Interfaces; use Interfaces;
25177 with Ada.Text_IO; use Ada.Text_IO;
25178 with System.Machine_Code; use System.Machine_Code;
25179 procedure Get_Flags_2 is
25180 Flags : Unsigned_32;
25183 Asm ("pushfl" & LF & HT & -- push flags on stack
25184 "popl %%eax", -- save flags in eax
25185 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25186 Put_Line ("Flags register:" & Flags'Img);
25192 The @code{"a"} constraint tells the compiler that the @code{Flags}
25193 variable will come from the eax register. Here is the resulting code:
25201 movl %eax,-40(%ebp)
25206 The compiler generated the store of eax into Flags after
25207 expanding the assembler code.
25209 Actually, there was no need to pop the flags into the eax register;
25210 more simply, we could just pop the flags directly into the program variable:
25212 @smallexample @c ada
25214 with Interfaces; use Interfaces;
25215 with Ada.Text_IO; use Ada.Text_IO;
25216 with System.Machine_Code; use System.Machine_Code;
25217 procedure Get_Flags_3 is
25218 Flags : Unsigned_32;
25221 Asm ("pushfl" & LF & HT & -- push flags on stack
25222 "pop %0", -- save flags in Flags
25223 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25224 Put_Line ("Flags register:" & Flags'Img);
25229 @c ---------------------------------------------------------------------------
25230 @node Input Variables in Inline Assembler
25231 @section Input Variables in Inline Assembler
25234 The example in this section illustrates how to specify the source operands
25235 for assembly language statements.
25236 The program simply increments its input value by 1:
25238 @smallexample @c ada
25240 with Interfaces; use Interfaces;
25241 with Ada.Text_IO; use Ada.Text_IO;
25242 with System.Machine_Code; use System.Machine_Code;
25243 procedure Increment is
25245 function Incr (Value : Unsigned_32) return Unsigned_32 is
25246 Result : Unsigned_32;
25249 Inputs => Unsigned_32'Asm_Input ("a", Value),
25250 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25254 Value : Unsigned_32;
25258 Put_Line ("Value before is" & Value'Img);
25259 Value := Incr (Value);
25260 Put_Line ("Value after is" & Value'Img);
25265 The @code{Outputs} parameter to @code{Asm} specifies
25266 that the result will be in the eax register and that it is to be stored
25267 in the @code{Result} variable.
25269 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25270 but with an @code{Asm_Input} attribute.
25271 The @code{"="} constraint, indicating an output value, is not present.
25273 You can have multiple input variables, in the same way that you can have more
25274 than one output variable.
25276 The parameter count (%0, %1) etc, now starts at the first input
25277 statement, and continues with the output statements.
25278 When both parameters use the same variable, the
25279 compiler will treat them as the same %n operand, which is the case here.
25281 Just as the @code{Outputs} parameter causes the register to be stored into the
25282 target variable after execution of the assembler statements, so does the
25283 @code{Inputs} parameter cause its variable to be loaded into the register
25284 before execution of the assembler statements.
25286 Thus the effect of the @code{Asm} invocation is:
25288 @item load the 32-bit value of @code{Value} into eax
25289 @item execute the @code{incl %eax} instruction
25290 @item store the contents of eax into the @code{Result} variable
25293 The resulting assembler file (with @option{-O2} optimization) contains:
25296 _increment__incr.1:
25309 @c ---------------------------------------------------------------------------
25310 @node Inlining Inline Assembler Code
25311 @section Inlining Inline Assembler Code
25314 For a short subprogram such as the @code{Incr} function in the previous
25315 section, the overhead of the call and return (creating / deleting the stack
25316 frame) can be significant, compared to the amount of code in the subprogram
25317 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25318 which directs the compiler to expand invocations of the subprogram at the
25319 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25320 Here is the resulting program:
25322 @smallexample @c ada
25324 with Interfaces; use Interfaces;
25325 with Ada.Text_IO; use Ada.Text_IO;
25326 with System.Machine_Code; use System.Machine_Code;
25327 procedure Increment_2 is
25329 function Incr (Value : Unsigned_32) return Unsigned_32 is
25330 Result : Unsigned_32;
25333 Inputs => Unsigned_32'Asm_Input ("a", Value),
25334 Outputs => Unsigned_32'Asm_Output ("=a", Result));
25337 pragma Inline (Increment);
25339 Value : Unsigned_32;
25343 Put_Line ("Value before is" & Value'Img);
25344 Value := Increment (Value);
25345 Put_Line ("Value after is" & Value'Img);
25350 Compile the program with both optimization (@option{-O2}) and inlining
25351 (@option{-gnatn}) enabled.
25353 The @code{Incr} function is still compiled as usual, but at the
25354 point in @code{Increment} where our function used to be called:
25359 call _increment__incr.1
25364 the code for the function body directly appears:
25377 thus saving the overhead of stack frame setup and an out-of-line call.
25379 @c ---------------------------------------------------------------------------
25380 @node Other Asm Functionality
25381 @section Other @code{Asm} Functionality
25384 This section describes two important parameters to the @code{Asm}
25385 procedure: @code{Clobber}, which identifies register usage;
25386 and @code{Volatile}, which inhibits unwanted optimizations.
25389 * The Clobber Parameter::
25390 * The Volatile Parameter::
25393 @c ---------------------------------------------------------------------------
25394 @node The Clobber Parameter
25395 @subsection The @code{Clobber} Parameter
25398 One of the dangers of intermixing assembly language and a compiled language
25399 such as Ada is that the compiler needs to be aware of which registers are
25400 being used by the assembly code. In some cases, such as the earlier examples,
25401 the constraint string is sufficient to indicate register usage (e.g.,
25403 the eax register). But more generally, the compiler needs an explicit
25404 identification of the registers that are used by the Inline Assembly
25407 Using a register that the compiler doesn't know about
25408 could be a side effect of an instruction (like @code{mull}
25409 storing its result in both eax and edx).
25410 It can also arise from explicit register usage in your
25411 assembly code; for example:
25414 Asm ("movl %0, %%ebx" & LF & HT &
25416 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25417 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25421 where the compiler (since it does not analyze the @code{Asm} template string)
25422 does not know you are using the ebx register.
25424 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25425 to identify the registers that will be used by your assembly code:
25429 Asm ("movl %0, %%ebx" & LF & HT &
25431 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25432 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25437 The Clobber parameter is a static string expression specifying the
25438 register(s) you are using. Note that register names are @emph{not} prefixed
25439 by a percent sign. Also, if more than one register is used then their names
25440 are separated by commas; e.g., @code{"eax, ebx"}
25442 The @code{Clobber} parameter has several additional uses:
25444 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25445 @item Use ``register'' name @code{memory} if you changed a memory location
25448 @c ---------------------------------------------------------------------------
25449 @node The Volatile Parameter
25450 @subsection The @code{Volatile} Parameter
25451 @cindex Volatile parameter
25454 Compiler optimizations in the presence of Inline Assembler may sometimes have
25455 unwanted effects. For example, when an @code{Asm} invocation with an input
25456 variable is inside a loop, the compiler might move the loading of the input
25457 variable outside the loop, regarding it as a one-time initialization.
25459 If this effect is not desired, you can disable such optimizations by setting
25460 the @code{Volatile} parameter to @code{True}; for example:
25462 @smallexample @c ada
25464 Asm ("movl %0, %%ebx" & LF & HT &
25466 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
25467 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25473 By default, @code{Volatile} is set to @code{False} unless there is no
25474 @code{Outputs} parameter.
25476 Although setting @code{Volatile} to @code{True} prevents unwanted
25477 optimizations, it will also disable other optimizations that might be
25478 important for efficiency. In general, you should set @code{Volatile}
25479 to @code{True} only if the compiler's optimizations have created
25481 @c END OF INLINE ASSEMBLER CHAPTER
25482 @c ===============================
25484 @c ***********************************
25485 @c * Compatibility and Porting Guide *
25486 @c ***********************************
25487 @node Compatibility and Porting Guide
25488 @appendix Compatibility and Porting Guide
25491 This chapter describes the compatibility issues that may arise between
25492 GNAT and other Ada compilation systems (including those for Ada 83),
25493 and shows how GNAT can expedite porting
25494 applications developed in other Ada environments.
25497 * Compatibility with Ada 83::
25498 * Compatibility between Ada 95 and Ada 2005::
25499 * Implementation-dependent characteristics::
25500 * Compatibility with Other Ada Systems::
25501 * Representation Clauses::
25503 @c Brief section is only in non-VMS version
25504 @c Full chapter is in VMS version
25505 * Compatibility with HP Ada 83::
25508 * Transitioning to 64-Bit GNAT for OpenVMS::
25512 @node Compatibility with Ada 83
25513 @section Compatibility with Ada 83
25514 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25517 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
25518 particular, the design intention was that the difficulties associated
25519 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25520 that occur when moving from one Ada 83 system to another.
25522 However, there are a number of points at which there are minor
25523 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
25524 full details of these issues,
25525 and should be consulted for a complete treatment.
25527 following subsections treat the most likely issues to be encountered.
25530 * Legal Ada 83 programs that are illegal in Ada 95::
25531 * More deterministic semantics::
25532 * Changed semantics::
25533 * Other language compatibility issues::
25536 @node Legal Ada 83 programs that are illegal in Ada 95
25537 @subsection Legal Ada 83 programs that are illegal in Ada 95
25539 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25540 Ada 95 and thus also in Ada 2005:
25543 @item Character literals
25544 Some uses of character literals are ambiguous. Since Ada 95 has introduced
25545 @code{Wide_Character} as a new predefined character type, some uses of
25546 character literals that were legal in Ada 83 are illegal in Ada 95.
25548 @smallexample @c ada
25549 for Char in 'A' .. 'Z' loop @dots{} end loop;
25553 The problem is that @code{'A'} and @code{'Z'} could be from either
25554 @code{Character} or @code{Wide_Character}. The simplest correction
25555 is to make the type explicit; e.g.:
25556 @smallexample @c ada
25557 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25560 @item New reserved words
25561 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25562 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25563 Existing Ada 83 code using any of these identifiers must be edited to
25564 use some alternative name.
25566 @item Freezing rules
25567 The rules in Ada 95 are slightly different with regard to the point at
25568 which entities are frozen, and representation pragmas and clauses are
25569 not permitted past the freeze point. This shows up most typically in
25570 the form of an error message complaining that a representation item
25571 appears too late, and the appropriate corrective action is to move
25572 the item nearer to the declaration of the entity to which it refers.
25574 A particular case is that representation pragmas
25577 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25579 cannot be applied to a subprogram body. If necessary, a separate subprogram
25580 declaration must be introduced to which the pragma can be applied.
25582 @item Optional bodies for library packages
25583 In Ada 83, a package that did not require a package body was nevertheless
25584 allowed to have one. This lead to certain surprises in compiling large
25585 systems (situations in which the body could be unexpectedly ignored by the
25586 binder). In Ada 95, if a package does not require a body then it is not
25587 permitted to have a body. To fix this problem, simply remove a redundant
25588 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25589 into the spec that makes the body required. One approach is to add a private
25590 part to the package declaration (if necessary), and define a parameterless
25591 procedure called @code{Requires_Body}, which must then be given a dummy
25592 procedure body in the package body, which then becomes required.
25593 Another approach (assuming that this does not introduce elaboration
25594 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25595 since one effect of this pragma is to require the presence of a package body.
25597 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25598 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25599 @code{Constraint_Error}.
25600 This means that it is illegal to have separate exception handlers for
25601 the two exceptions. The fix is simply to remove the handler for the
25602 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25603 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25605 @item Indefinite subtypes in generics
25606 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25607 as the actual for a generic formal private type, but then the instantiation
25608 would be illegal if there were any instances of declarations of variables
25609 of this type in the generic body. In Ada 95, to avoid this clear violation
25610 of the methodological principle known as the ``contract model'',
25611 the generic declaration explicitly indicates whether
25612 or not such instantiations are permitted. If a generic formal parameter
25613 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25614 type name, then it can be instantiated with indefinite types, but no
25615 stand-alone variables can be declared of this type. Any attempt to declare
25616 such a variable will result in an illegality at the time the generic is
25617 declared. If the @code{(<>)} notation is not used, then it is illegal
25618 to instantiate the generic with an indefinite type.
25619 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25620 It will show up as a compile time error, and
25621 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25624 @node More deterministic semantics
25625 @subsection More deterministic semantics
25629 Conversions from real types to integer types round away from 0. In Ada 83
25630 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
25631 implementation freedom was intended to support unbiased rounding in
25632 statistical applications, but in practice it interfered with portability.
25633 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25634 is required. Numeric code may be affected by this change in semantics.
25635 Note, though, that this issue is no worse than already existed in Ada 83
25636 when porting code from one vendor to another.
25639 The Real-Time Annex introduces a set of policies that define the behavior of
25640 features that were implementation dependent in Ada 83, such as the order in
25641 which open select branches are executed.
25644 @node Changed semantics
25645 @subsection Changed semantics
25648 The worst kind of incompatibility is one where a program that is legal in
25649 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25650 possible in Ada 83. Fortunately this is extremely rare, but the one
25651 situation that you should be alert to is the change in the predefined type
25652 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25655 @item Range of type @code{Character}
25656 The range of @code{Standard.Character} is now the full 256 characters
25657 of Latin-1, whereas in most Ada 83 implementations it was restricted
25658 to 128 characters. Although some of the effects of
25659 this change will be manifest in compile-time rejection of legal
25660 Ada 83 programs it is possible for a working Ada 83 program to have
25661 a different effect in Ada 95, one that was not permitted in Ada 83.
25662 As an example, the expression
25663 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25664 delivers @code{255} as its value.
25665 In general, you should look at the logic of any
25666 character-processing Ada 83 program and see whether it needs to be adapted
25667 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
25668 character handling package that may be relevant if code needs to be adapted
25669 to account for the additional Latin-1 elements.
25670 The desirable fix is to
25671 modify the program to accommodate the full character set, but in some cases
25672 it may be convenient to define a subtype or derived type of Character that
25673 covers only the restricted range.
25677 @node Other language compatibility issues
25678 @subsection Other language compatibility issues
25681 @item @option{-gnat83} switch
25682 All implementations of GNAT provide a switch that causes GNAT to operate
25683 in Ada 83 mode. In this mode, some but not all compatibility problems
25684 of the type described above are handled automatically. For example, the
25685 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
25686 as identifiers as in Ada 83.
25688 in practice, it is usually advisable to make the necessary modifications
25689 to the program to remove the need for using this switch.
25690 See @ref{Compiling Different Versions of Ada}.
25692 @item Support for removed Ada 83 pragmas and attributes
25693 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
25694 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
25695 compilers are allowed, but not required, to implement these missing
25696 elements. In contrast with some other compilers, GNAT implements all
25697 such pragmas and attributes, eliminating this compatibility concern. These
25698 include @code{pragma Interface} and the floating point type attributes
25699 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25703 @node Compatibility between Ada 95 and Ada 2005
25704 @section Compatibility between Ada 95 and Ada 2005
25705 @cindex Compatibility between Ada 95 and Ada 2005
25708 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
25709 a number of incompatibilities. Several are enumerated below;
25710 for a complete description please see the
25711 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
25712 @cite{Rationale for Ada 2005}.
25715 @item New reserved words.
25716 The words @code{interface}, @code{overriding} and @code{synchronized} are
25717 reserved in Ada 2005.
25718 A pre-Ada 2005 program that uses any of these as an identifier will be
25721 @item New declarations in predefined packages.
25722 A number of packages in the predefined environment contain new declarations:
25723 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
25724 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
25725 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
25726 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
25727 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
25728 If an Ada 95 program does a @code{with} and @code{use} of any of these
25729 packages, the new declarations may cause name clashes.
25731 @item Access parameters.
25732 A nondispatching subprogram with an access parameter cannot be renamed
25733 as a dispatching operation. This was permitted in Ada 95.
25735 @item Access types, discriminants, and constraints.
25736 Rule changes in this area have led to some incompatibilities; for example,
25737 constrained subtypes of some access types are not permitted in Ada 2005.
25739 @item Aggregates for limited types.
25740 The allowance of aggregates for limited types in Ada 2005 raises the
25741 possibility of ambiguities in legal Ada 95 programs, since additional types
25742 now need to be considered in expression resolution.
25744 @item Fixed-point multiplication and division.
25745 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
25746 were legal in Ada 95 and invoked the predefined versions of these operations,
25748 The ambiguity may be resolved either by applying a type conversion to the
25749 expression, or by explicitly invoking the operation from package
25752 @item Return-by-reference types.
25753 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
25754 can declare a function returning a value from an anonymous access type.
25758 @node Implementation-dependent characteristics
25759 @section Implementation-dependent characteristics
25761 Although the Ada language defines the semantics of each construct as
25762 precisely as practical, in some situations (for example for reasons of
25763 efficiency, or where the effect is heavily dependent on the host or target
25764 platform) the implementation is allowed some freedom. In porting Ada 83
25765 code to GNAT, you need to be aware of whether / how the existing code
25766 exercised such implementation dependencies. Such characteristics fall into
25767 several categories, and GNAT offers specific support in assisting the
25768 transition from certain Ada 83 compilers.
25771 * Implementation-defined pragmas::
25772 * Implementation-defined attributes::
25774 * Elaboration order::
25775 * Target-specific aspects::
25778 @node Implementation-defined pragmas
25779 @subsection Implementation-defined pragmas
25782 Ada compilers are allowed to supplement the language-defined pragmas, and
25783 these are a potential source of non-portability. All GNAT-defined pragmas
25784 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
25785 Reference Manual}, and these include several that are specifically
25786 intended to correspond to other vendors' Ada 83 pragmas.
25787 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25788 For compatibility with HP Ada 83, GNAT supplies the pragmas
25789 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25790 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25791 and @code{Volatile}.
25792 Other relevant pragmas include @code{External} and @code{Link_With}.
25793 Some vendor-specific
25794 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25796 avoiding compiler rejection of units that contain such pragmas; they are not
25797 relevant in a GNAT context and hence are not otherwise implemented.
25799 @node Implementation-defined attributes
25800 @subsection Implementation-defined attributes
25802 Analogous to pragmas, the set of attributes may be extended by an
25803 implementation. All GNAT-defined attributes are described in
25804 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
25805 Manual}, and these include several that are specifically intended
25806 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
25807 the attribute @code{VADS_Size} may be useful. For compatibility with HP
25808 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25812 @subsection Libraries
25814 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
25815 code uses vendor-specific libraries then there are several ways to manage
25816 this in Ada 95 or Ada 2005:
25819 If the source code for the libraries (specs and bodies) are
25820 available, then the libraries can be migrated in the same way as the
25823 If the source code for the specs but not the bodies are
25824 available, then you can reimplement the bodies.
25826 Some features introduced by Ada 95 obviate the need for library support. For
25827 example most Ada 83 vendors supplied a package for unsigned integers. The
25828 Ada 95 modular type feature is the preferred way to handle this need, so
25829 instead of migrating or reimplementing the unsigned integer package it may
25830 be preferable to retrofit the application using modular types.
25833 @node Elaboration order
25834 @subsection Elaboration order
25836 The implementation can choose any elaboration order consistent with the unit
25837 dependency relationship. This freedom means that some orders can result in
25838 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25839 to invoke a subprogram its body has been elaborated, or to instantiate a
25840 generic before the generic body has been elaborated. By default GNAT
25841 attempts to choose a safe order (one that will not encounter access before
25842 elaboration problems) by implicitly inserting @code{Elaborate} or
25843 @code{Elaborate_All} pragmas where
25844 needed. However, this can lead to the creation of elaboration circularities
25845 and a resulting rejection of the program by gnatbind. This issue is
25846 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25847 In brief, there are several
25848 ways to deal with this situation:
25852 Modify the program to eliminate the circularities, e.g.@: by moving
25853 elaboration-time code into explicitly-invoked procedures
25855 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25856 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25857 @code{Elaborate_All}
25858 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25859 (by selectively suppressing elaboration checks via pragma
25860 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25863 @node Target-specific aspects
25864 @subsection Target-specific aspects
25866 Low-level applications need to deal with machine addresses, data
25867 representations, interfacing with assembler code, and similar issues. If
25868 such an Ada 83 application is being ported to different target hardware (for
25869 example where the byte endianness has changed) then you will need to
25870 carefully examine the program logic; the porting effort will heavily depend
25871 on the robustness of the original design. Moreover, Ada 95 (and thus
25872 Ada 2005) are sometimes
25873 incompatible with typical Ada 83 compiler practices regarding implicit
25874 packing, the meaning of the Size attribute, and the size of access values.
25875 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25877 @node Compatibility with Other Ada Systems
25878 @section Compatibility with Other Ada Systems
25881 If programs avoid the use of implementation dependent and
25882 implementation defined features, as documented in the @cite{Ada
25883 Reference Manual}, there should be a high degree of portability between
25884 GNAT and other Ada systems. The following are specific items which
25885 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
25886 compilers, but do not affect porting code to GNAT@.
25887 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
25888 the following issues may or may not arise for Ada 2005 programs
25889 when other compilers appear.)
25892 @item Ada 83 Pragmas and Attributes
25893 Ada 95 compilers are allowed, but not required, to implement the missing
25894 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25895 GNAT implements all such pragmas and attributes, eliminating this as
25896 a compatibility concern, but some other Ada 95 compilers reject these
25897 pragmas and attributes.
25899 @item Specialized Needs Annexes
25900 GNAT implements the full set of special needs annexes. At the
25901 current time, it is the only Ada 95 compiler to do so. This means that
25902 programs making use of these features may not be portable to other Ada
25903 95 compilation systems.
25905 @item Representation Clauses
25906 Some other Ada 95 compilers implement only the minimal set of
25907 representation clauses required by the Ada 95 reference manual. GNAT goes
25908 far beyond this minimal set, as described in the next section.
25911 @node Representation Clauses
25912 @section Representation Clauses
25915 The Ada 83 reference manual was quite vague in describing both the minimal
25916 required implementation of representation clauses, and also their precise
25917 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
25918 minimal set of capabilities required is still quite limited.
25920 GNAT implements the full required set of capabilities in
25921 Ada 95 and Ada 2005, but also goes much further, and in particular
25922 an effort has been made to be compatible with existing Ada 83 usage to the
25923 greatest extent possible.
25925 A few cases exist in which Ada 83 compiler behavior is incompatible with
25926 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
25927 intentional or accidental dependence on specific implementation dependent
25928 characteristics of these Ada 83 compilers. The following is a list of
25929 the cases most likely to arise in existing Ada 83 code.
25932 @item Implicit Packing
25933 Some Ada 83 compilers allowed a Size specification to cause implicit
25934 packing of an array or record. This could cause expensive implicit
25935 conversions for change of representation in the presence of derived
25936 types, and the Ada design intends to avoid this possibility.
25937 Subsequent AI's were issued to make it clear that such implicit
25938 change of representation in response to a Size clause is inadvisable,
25939 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
25940 Reference Manuals as implementation advice that is followed by GNAT@.
25941 The problem will show up as an error
25942 message rejecting the size clause. The fix is simply to provide
25943 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25944 a Component_Size clause.
25946 @item Meaning of Size Attribute
25947 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
25948 the minimal number of bits required to hold values of the type. For example,
25949 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
25950 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
25951 some 32 in this situation. This problem will usually show up as a compile
25952 time error, but not always. It is a good idea to check all uses of the
25953 'Size attribute when porting Ada 83 code. The GNAT specific attribute
25954 Object_Size can provide a useful way of duplicating the behavior of
25955 some Ada 83 compiler systems.
25957 @item Size of Access Types
25958 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25959 and that therefore it will be the same size as a System.Address value. This
25960 assumption is true for GNAT in most cases with one exception. For the case of
25961 a pointer to an unconstrained array type (where the bounds may vary from one
25962 value of the access type to another), the default is to use a ``fat pointer'',
25963 which is represented as two separate pointers, one to the bounds, and one to
25964 the array. This representation has a number of advantages, including improved
25965 efficiency. However, it may cause some difficulties in porting existing Ada 83
25966 code which makes the assumption that, for example, pointers fit in 32 bits on
25967 a machine with 32-bit addressing.
25969 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25970 access types in this case (where the designated type is an unconstrained array
25971 type). These thin pointers are indeed the same size as a System.Address value.
25972 To specify a thin pointer, use a size clause for the type, for example:
25974 @smallexample @c ada
25975 type X is access all String;
25976 for X'Size use Standard'Address_Size;
25980 which will cause the type X to be represented using a single pointer.
25981 When using this representation, the bounds are right behind the array.
25982 This representation is slightly less efficient, and does not allow quite
25983 such flexibility in the use of foreign pointers or in using the
25984 Unrestricted_Access attribute to create pointers to non-aliased objects.
25985 But for any standard portable use of the access type it will work in
25986 a functionally correct manner and allow porting of existing code.
25987 Note that another way of forcing a thin pointer representation
25988 is to use a component size clause for the element size in an array,
25989 or a record representation clause for an access field in a record.
25993 @c This brief section is only in the non-VMS version
25994 @c The complete chapter on HP Ada is in the VMS version
25995 @node Compatibility with HP Ada 83
25996 @section Compatibility with HP Ada 83
25999 The VMS version of GNAT fully implements all the pragmas and attributes
26000 provided by HP Ada 83, as well as providing the standard HP Ada 83
26001 libraries, including Starlet. In addition, data layouts and parameter
26002 passing conventions are highly compatible. This means that porting
26003 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26004 most other porting efforts. The following are some of the most
26005 significant differences between GNAT and HP Ada 83.
26008 @item Default floating-point representation
26009 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26010 it is VMS format. GNAT does implement the necessary pragmas
26011 (Long_Float, Float_Representation) for changing this default.
26014 The package System in GNAT exactly corresponds to the definition in the
26015 Ada 95 reference manual, which means that it excludes many of the
26016 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
26017 that contains the additional definitions, and a special pragma,
26018 Extend_System allows this package to be treated transparently as an
26019 extension of package System.
26022 The definitions provided by Aux_DEC are exactly compatible with those
26023 in the HP Ada 83 version of System, with one exception.
26024 HP Ada provides the following declarations:
26026 @smallexample @c ada
26027 TO_ADDRESS (INTEGER)
26028 TO_ADDRESS (UNSIGNED_LONGWORD)
26029 TO_ADDRESS (@i{universal_integer})
26033 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26034 an extension to Ada 83 not strictly compatible with the reference manual.
26035 In GNAT, we are constrained to be exactly compatible with the standard,
26036 and this means we cannot provide this capability. In HP Ada 83, the
26037 point of this definition is to deal with a call like:
26039 @smallexample @c ada
26040 TO_ADDRESS (16#12777#);
26044 Normally, according to the Ada 83 standard, one would expect this to be
26045 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26046 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
26047 definition using @i{universal_integer} takes precedence.
26049 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26050 is not possible to be 100% compatible. Since there are many programs using
26051 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26052 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26053 declarations provided in the GNAT version of AUX_Dec are:
26055 @smallexample @c ada
26056 function To_Address (X : Integer) return Address;
26057 pragma Pure_Function (To_Address);
26059 function To_Address_Long (X : Unsigned_Longword)
26061 pragma Pure_Function (To_Address_Long);
26065 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26066 change the name to TO_ADDRESS_LONG@.
26068 @item Task_Id values
26069 The Task_Id values assigned will be different in the two systems, and GNAT
26070 does not provide a specified value for the Task_Id of the environment task,
26071 which in GNAT is treated like any other declared task.
26075 For full details on these and other less significant compatibility issues,
26076 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26077 Overview and Comparison on HP Platforms}.
26079 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26080 attributes are recognized, although only a subset of them can sensibly
26081 be implemented. The description of pragmas in @ref{Implementation
26082 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26083 indicates whether or not they are applicable to non-VMS systems.
26087 @node Transitioning to 64-Bit GNAT for OpenVMS
26088 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26091 This section is meant to assist users of pre-2006 @value{EDITION}
26092 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26093 the version of the GNAT technology supplied in 2006 and later for
26094 OpenVMS on both Alpha and I64.
26097 * Introduction to transitioning::
26098 * Migration of 32 bit code::
26099 * Taking advantage of 64 bit addressing::
26100 * Technical details::
26103 @node Introduction to transitioning
26104 @subsection Introduction
26107 64-bit @value{EDITION} for Open VMS has been designed to meet
26112 Providing a full conforming implementation of Ada 95 and Ada 2005
26115 Allowing maximum backward compatibility, thus easing migration of existing
26119 Supplying a path for exploiting the full 64-bit address range
26123 Ada's strong typing semantics has made it
26124 impractical to have different 32-bit and 64-bit modes. As soon as
26125 one object could possibly be outside the 32-bit address space, this
26126 would make it necessary for the @code{System.Address} type to be 64 bits.
26127 In particular, this would cause inconsistencies if 32-bit code is
26128 called from 64-bit code that raises an exception.
26130 This issue has been resolved by always using 64-bit addressing
26131 at the system level, but allowing for automatic conversions between
26132 32-bit and 64-bit addresses where required. Thus users who
26133 do not currently require 64-bit addressing capabilities, can
26134 recompile their code with only minimal changes (and indeed
26135 if the code is written in portable Ada, with no assumptions about
26136 the size of the @code{Address} type, then no changes at all are necessary).
26138 this approach provides a simple, gradual upgrade path to future
26139 use of larger memories than available for 32-bit systems.
26140 Also, newly written applications or libraries will by default
26141 be fully compatible with future systems exploiting 64-bit
26142 addressing capabilities.
26144 @ref{Migration of 32 bit code}, will focus on porting applications
26145 that do not require more than 2 GB of
26146 addressable memory. This code will be referred to as
26147 @emph{32-bit code}.
26148 For applications intending to exploit the full 64-bit address space,
26149 @ref{Taking advantage of 64 bit addressing},
26150 will consider further changes that may be required.
26151 Such code will be referred to below as @emph{64-bit code}.
26153 @node Migration of 32 bit code
26154 @subsection Migration of 32-bit code
26158 * Access types and 32/64-bit allocation::
26159 * Unchecked conversions::
26160 * Predefined constants::
26161 * Interfacing with C::
26162 * 32/64-bit descriptors::
26163 * Experience with source compatibility::
26166 @node Address types
26167 @subsubsection Address types
26170 To solve the problem of mixing 64-bit and 32-bit addressing,
26171 while maintaining maximum backward compatibility, the following
26172 approach has been taken:
26176 @code{System.Address} always has a size of 64 bits
26177 @cindex @code{System.Address} size
26178 @cindex @code{Address} size
26181 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26182 @cindex @code{System.Short_Address} size
26183 @cindex @code{Short_Address} size
26187 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26188 a @code{Short_Address}
26189 may be used where an @code{Address} is required, and vice versa, without
26190 needing explicit type conversions.
26191 By virtue of the Open VMS parameter passing conventions,
26193 and exported subprograms that have 32-bit address parameters are
26194 compatible with those that have 64-bit address parameters.
26195 (See @ref{Making code 64 bit clean} for details.)
26197 The areas that may need attention are those where record types have
26198 been defined that contain components of the type @code{System.Address}, and
26199 where objects of this type are passed to code expecting a record layout with
26202 Different compilers on different platforms cannot be
26203 expected to represent the same type in the same way,
26204 since alignment constraints
26205 and other system-dependent properties affect the compiler's decision.
26206 For that reason, Ada code
26207 generally uses representation clauses to specify the expected
26208 layout where required.
26210 If such a representation clause uses 32 bits for a component having
26211 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26212 will detect that error and produce a specific diagnostic message.
26213 The developer should then determine whether the representation
26214 should be 64 bits or not and make either of two changes:
26215 change the size to 64 bits and leave the type as @code{System.Address}, or
26216 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26217 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26218 required in any code setting or accessing the field; the compiler will
26219 automatically perform any needed conversions between address
26222 @node Access types and 32/64-bit allocation
26223 @subsubsection Access types and 32/64-bit allocation
26224 @cindex 32-bit allocation
26225 @cindex 64-bit allocation
26228 By default, objects designated by access values are always allocated in
26229 the 64-bit address space, and access values themselves are represented
26230 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
26231 is required (for example if the address of an allocated object is assigned
26232 to a @code{Short_Address} variable), then several alternatives are available:
26236 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26237 definition is @code{access T} versus @code{access all T} or
26238 @code{access constant T}), may be declared with a @code{'Size} representation
26239 clause that establishes the size as 32 bits.
26240 In such circumstances allocations for that type will
26241 be from the 32-bit heap. Such a clause is not permitted
26242 for a general access type (declared with @code{access all} or
26243 @code{access constant}) as values of such types must be able to refer
26244 to any object of the designated type, including objects residing outside
26245 the 32-bit address range. Existing @w{Ada 83} code will not contain such
26246 type definitions, however, since general access types were introduced
26250 Switches for @command{GNAT BIND} control whether the internal GNAT
26251 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26252 @cindex @code{__gnat_malloc}
26253 The switches are respectively @option{-H64} (the default) and
26255 @cindex @option{-H32} (@command{gnatbind})
26256 @cindex @option{-H64} (@command{gnatbind})
26259 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26260 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26261 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26262 If this variable is left
26263 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26264 then the default (64-bit) allocation is used.
26265 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26266 then 32-bit allocation is used. The gnatbind qualifiers described above
26267 override this logical name.
26270 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26271 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26272 at a low level to convert explicit calls to @code{malloc} and related
26273 functions from the C run-time library so that they perform allocations
26274 in the 32-bit heap.
26275 Since all internal allocations from GNAT use @code{__gnat_malloc},
26276 this switch is not required unless the program makes explicit calls on
26277 @code{malloc} (or related functions) from interfaced C code.
26281 @node Unchecked conversions
26282 @subsubsection Unchecked conversions
26285 In the case of an @code{Unchecked_Conversion} where the source type is a
26286 64-bit access type or the type @code{System.Address}, and the target
26287 type is a 32-bit type, the compiler will generate a warning.
26288 Even though the generated code will still perform the required
26289 conversions, it is highly recommended in these cases to use
26290 respectively a 32-bit access type or @code{System.Short_Address}
26291 as the source type.
26293 @node Predefined constants
26294 @subsubsection Predefined constants
26297 The following table shows the correspondence between pre-2006 versions of
26298 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26301 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26302 @item @b{Constant} @tab @b{Old} @tab @b{New}
26303 @item @code{System.Word_Size} @tab 32 @tab 64
26304 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
26305 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
26306 @item @code{System.Address_Size} @tab 32 @tab 64
26310 If you need to refer to the specific
26311 memory size of a 32-bit implementation, instead of the
26312 actual memory size, use @code{System.Short_Memory_Size}
26313 rather than @code{System.Memory_Size}.
26314 Similarly, references to @code{System.Address_Size} may need
26315 to be replaced by @code{System.Short_Address'Size}.
26316 The program @command{gnatfind} may be useful for locating
26317 references to the above constants, so that you can verify that they
26320 @node Interfacing with C
26321 @subsubsection Interfacing with C
26324 In order to minimize the impact of the transition to 64-bit addresses on
26325 legacy programs, some fundamental types in the @code{Interfaces.C}
26326 package hierarchy continue to be represented in 32 bits.
26327 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26328 This eases integration with the default HP C layout choices, for example
26329 as found in the system routines in @code{DECC$SHR.EXE}.
26330 Because of this implementation choice, the type fully compatible with
26331 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26332 Depending on the context the compiler will issue a
26333 warning or an error when type @code{Address} is used, alerting the user to a
26334 potential problem. Otherwise 32-bit programs that use
26335 @code{Interfaces.C} should normally not require code modifications
26337 The other issue arising with C interfacing concerns pragma @code{Convention}.
26338 For VMS 64-bit systems, there is an issue of the appropriate default size
26339 of C convention pointers in the absence of an explicit size clause. The HP
26340 C compiler can choose either 32 or 64 bits depending on compiler options.
26341 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26342 clause is given. This proves a better choice for porting 32-bit legacy
26343 applications. In order to have a 64-bit representation, it is necessary to
26344 specify a size representation clause. For example:
26346 @smallexample @c ada
26347 type int_star is access Interfaces.C.int;
26348 pragma Convention(C, int_star);
26349 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
26352 @node 32/64-bit descriptors
26353 @subsubsection 32/64-bit descriptors
26356 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
26357 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26358 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26359 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26360 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26362 If the configuration pragma @code{Short_Descriptors} is supplied, then
26363 all descriptors will be 32 bits.
26364 @cindex pragma @code{Short_Descriptors}
26366 @node Experience with source compatibility
26367 @subsubsection Experience with source compatibility
26370 The Security Server and STARLET on I64 provide an interesting ``test case''
26371 for source compatibility issues, since it is in such system code
26372 where assumptions about @code{Address} size might be expected to occur.
26373 Indeed, there were a small number of occasions in the Security Server
26374 file @file{jibdef.ads}
26375 where a representation clause for a record type specified
26376 32 bits for a component of type @code{Address}.
26377 All of these errors were detected by the compiler.
26378 The repair was obvious and immediate; to simply replace @code{Address} by
26379 @code{Short_Address}.
26381 In the case of STARLET, there were several record types that should
26382 have had representation clauses but did not. In these record types
26383 there was an implicit assumption that an @code{Address} value occupied
26385 These compiled without error, but their usage resulted in run-time error
26386 returns from STARLET system calls.
26387 Future GNAT technology enhancements may include a tool that detects and flags
26388 these sorts of potential source code porting problems.
26390 @c ****************************************
26391 @node Taking advantage of 64 bit addressing
26392 @subsection Taking advantage of 64-bit addressing
26395 * Making code 64 bit clean::
26396 * Allocating memory from the 64 bit storage pool::
26397 * Restrictions on use of 64 bit objects::
26398 * STARLET and other predefined libraries::
26401 @node Making code 64 bit clean
26402 @subsubsection Making code 64-bit clean
26405 In order to prevent problems that may occur when (parts of) a
26406 system start using memory outside the 32-bit address range,
26407 we recommend some additional guidelines:
26411 For imported subprograms that take parameters of the
26412 type @code{System.Address}, ensure that these subprograms can
26413 indeed handle 64-bit addresses. If not, or when in doubt,
26414 change the subprogram declaration to specify
26415 @code{System.Short_Address} instead.
26418 Resolve all warnings related to size mismatches in
26419 unchecked conversions. Failing to do so causes
26420 erroneous execution if the source object is outside
26421 the 32-bit address space.
26424 (optional) Explicitly use the 32-bit storage pool
26425 for access types used in a 32-bit context, or use
26426 generic access types where possible
26427 (@pxref{Restrictions on use of 64 bit objects}).
26431 If these rules are followed, the compiler will automatically insert
26432 any necessary checks to ensure that no addresses or access values
26433 passed to 32-bit code ever refer to objects outside the 32-bit
26435 Any attempt to do this will raise @code{Constraint_Error}.
26437 @node Allocating memory from the 64 bit storage pool
26438 @subsubsection Allocating memory from the 64-bit storage pool
26441 By default, all allocations -- for both pool-specific and general
26442 access types -- use the 64-bit storage pool. To override
26443 this default, for an individual access type or globally, see
26444 @ref{Access types and 32/64-bit allocation}.
26446 @node Restrictions on use of 64 bit objects
26447 @subsubsection Restrictions on use of 64-bit objects
26450 Taking the address of an object allocated from a 64-bit storage pool,
26451 and then passing this address to a subprogram expecting
26452 @code{System.Short_Address},
26453 or assigning it to a variable of type @code{Short_Address}, will cause
26454 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26455 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26456 no exception is raised and execution
26457 will become erroneous.
26459 @node STARLET and other predefined libraries
26460 @subsubsection STARLET and other predefined libraries
26463 All code that comes as part of GNAT is 64-bit clean, but the
26464 restrictions given in @ref{Restrictions on use of 64 bit objects},
26465 still apply. Look at the package
26466 specs to see in which contexts objects allocated
26467 in 64-bit address space are acceptable.
26469 @node Technical details
26470 @subsection Technical details
26473 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26474 Ada standard with respect to the type of @code{System.Address}. Previous
26475 versions of @value{EDITION} have defined this type as private and implemented it as a
26478 In order to allow defining @code{System.Short_Address} as a proper subtype,
26479 and to match the implicit sign extension in parameter passing,
26480 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26481 visible (i.e., non-private) integer type.
26482 Standard operations on the type, such as the binary operators ``+'', ``-'',
26483 etc., that take @code{Address} operands and return an @code{Address} result,
26484 have been hidden by declaring these
26485 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26486 ambiguities that would otherwise result from overloading.
26487 (Note that, although @code{Address} is a visible integer type,
26488 good programming practice dictates against exploiting the type's
26489 integer properties such as literals, since this will compromise
26492 Defining @code{Address} as a visible integer type helps achieve
26493 maximum compatibility for existing Ada code,
26494 without sacrificing the capabilities of the 64-bit architecture.
26497 @c ************************************************
26499 @node Microsoft Windows Topics
26500 @appendix Microsoft Windows Topics
26506 This chapter describes topics that are specific to the Microsoft Windows
26507 platforms (NT, 2000, and XP Professional).
26510 * Using GNAT on Windows::
26511 * Using a network installation of GNAT::
26512 * CONSOLE and WINDOWS subsystems::
26513 * Temporary Files::
26514 * Mixed-Language Programming on Windows::
26515 * Windows Calling Conventions::
26516 * Introduction to Dynamic Link Libraries (DLLs)::
26517 * Using DLLs with GNAT::
26518 * Building DLLs with GNAT Project files::
26519 * Building DLLs with GNAT::
26520 * Building DLLs with gnatdll::
26521 * GNAT and Windows Resources::
26522 * Debugging a DLL::
26523 * Setting Stack Size from gnatlink::
26524 * Setting Heap Size from gnatlink::
26527 @node Using GNAT on Windows
26528 @section Using GNAT on Windows
26531 One of the strengths of the GNAT technology is that its tool set
26532 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26533 @code{gdb} debugger, etc.) is used in the same way regardless of the
26536 On Windows this tool set is complemented by a number of Microsoft-specific
26537 tools that have been provided to facilitate interoperability with Windows
26538 when this is required. With these tools:
26543 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26547 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26548 relocatable and non-relocatable DLLs are supported).
26551 You can build Ada DLLs for use in other applications. These applications
26552 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26553 relocatable and non-relocatable Ada DLLs are supported.
26556 You can include Windows resources in your Ada application.
26559 You can use or create COM/DCOM objects.
26563 Immediately below are listed all known general GNAT-for-Windows restrictions.
26564 Other restrictions about specific features like Windows Resources and DLLs
26565 are listed in separate sections below.
26570 It is not possible to use @code{GetLastError} and @code{SetLastError}
26571 when tasking, protected records, or exceptions are used. In these
26572 cases, in order to implement Ada semantics, the GNAT run-time system
26573 calls certain Win32 routines that set the last error variable to 0 upon
26574 success. It should be possible to use @code{GetLastError} and
26575 @code{SetLastError} when tasking, protected record, and exception
26576 features are not used, but it is not guaranteed to work.
26579 It is not possible to link against Microsoft libraries except for
26580 import libraries. Interfacing must be done by the mean of DLLs.
26583 When the compilation environment is located on FAT32 drives, users may
26584 experience recompilations of the source files that have not changed if
26585 Daylight Saving Time (DST) state has changed since the last time files
26586 were compiled. NTFS drives do not have this problem.
26589 No components of the GNAT toolset use any entries in the Windows
26590 registry. The only entries that can be created are file associations and
26591 PATH settings, provided the user has chosen to create them at installation
26592 time, as well as some minimal book-keeping information needed to correctly
26593 uninstall or integrate different GNAT products.
26596 @node Using a network installation of GNAT
26597 @section Using a network installation of GNAT
26600 Make sure the system on which GNAT is installed is accessible from the
26601 current machine, i.e., the install location is shared over the network.
26602 Shared resources are accessed on Windows by means of UNC paths, which
26603 have the format @code{\\server\sharename\path}
26605 In order to use such a network installation, simply add the UNC path of the
26606 @file{bin} directory of your GNAT installation in front of your PATH. For
26607 example, if GNAT is installed in @file{\GNAT} directory of a share location
26608 called @file{c-drive} on a machine @file{LOKI}, the following command will
26611 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26613 Be aware that every compilation using the network installation results in the
26614 transfer of large amounts of data across the network and will likely cause
26615 serious performance penalty.
26617 @node CONSOLE and WINDOWS subsystems
26618 @section CONSOLE and WINDOWS subsystems
26619 @cindex CONSOLE Subsystem
26620 @cindex WINDOWS Subsystem
26624 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26625 (which is the default subsystem) will always create a console when
26626 launching the application. This is not something desirable when the
26627 application has a Windows GUI. To get rid of this console the
26628 application must be using the @code{WINDOWS} subsystem. To do so
26629 the @option{-mwindows} linker option must be specified.
26632 $ gnatmake winprog -largs -mwindows
26635 @node Temporary Files
26636 @section Temporary Files
26637 @cindex Temporary files
26640 It is possible to control where temporary files gets created by setting
26641 the @env{TMP} environment variable. The file will be created:
26644 @item Under the directory pointed to by the @env{TMP} environment variable if
26645 this directory exists.
26647 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
26648 set (or not pointing to a directory) and if this directory exists.
26650 @item Under the current working directory otherwise.
26654 This allows you to determine exactly where the temporary
26655 file will be created. This is particularly useful in networked
26656 environments where you may not have write access to some
26659 @node Mixed-Language Programming on Windows
26660 @section Mixed-Language Programming on Windows
26663 Developing pure Ada applications on Windows is no different than on
26664 other GNAT-supported platforms. However, when developing or porting an
26665 application that contains a mix of Ada and C/C++, the choice of your
26666 Windows C/C++ development environment conditions your overall
26667 interoperability strategy.
26669 If you use @command{gcc} to compile the non-Ada part of your application,
26670 there are no Windows-specific restrictions that affect the overall
26671 interoperability with your Ada code. If you do want to use the
26672 Microsoft tools for your non-Ada code, you have two choices:
26676 Encapsulate your non-Ada code in a DLL to be linked with your Ada
26677 application. In this case, use the Microsoft or whatever environment to
26678 build the DLL and use GNAT to build your executable
26679 (@pxref{Using DLLs with GNAT}).
26682 Or you can encapsulate your Ada code in a DLL to be linked with the
26683 other part of your application. In this case, use GNAT to build the DLL
26684 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
26685 or whatever environment to build your executable.
26688 @node Windows Calling Conventions
26689 @section Windows Calling Conventions
26693 This section pertain only to Win32. On Win64 there is a single native
26694 calling convention. All convention specifiers are ignored on this
26698 * C Calling Convention::
26699 * Stdcall Calling Convention::
26700 * Win32 Calling Convention::
26701 * DLL Calling Convention::
26705 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26706 (callee), there are several ways to push @code{G}'s parameters on the
26707 stack and there are several possible scenarios to clean up the stack
26708 upon @code{G}'s return. A calling convention is an agreed upon software
26709 protocol whereby the responsibilities between the caller (@code{F}) and
26710 the callee (@code{G}) are clearly defined. Several calling conventions
26711 are available for Windows:
26715 @code{C} (Microsoft defined)
26718 @code{Stdcall} (Microsoft defined)
26721 @code{Win32} (GNAT specific)
26724 @code{DLL} (GNAT specific)
26727 @node C Calling Convention
26728 @subsection @code{C} Calling Convention
26731 This is the default calling convention used when interfacing to C/C++
26732 routines compiled with either @command{gcc} or Microsoft Visual C++.
26734 In the @code{C} calling convention subprogram parameters are pushed on the
26735 stack by the caller from right to left. The caller itself is in charge of
26736 cleaning up the stack after the call. In addition, the name of a routine
26737 with @code{C} calling convention is mangled by adding a leading underscore.
26739 The name to use on the Ada side when importing (or exporting) a routine
26740 with @code{C} calling convention is the name of the routine. For
26741 instance the C function:
26744 int get_val (long);
26748 should be imported from Ada as follows:
26750 @smallexample @c ada
26752 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26753 pragma Import (C, Get_Val, External_Name => "get_val");
26758 Note that in this particular case the @code{External_Name} parameter could
26759 have been omitted since, when missing, this parameter is taken to be the
26760 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26761 is missing, as in the above example, this parameter is set to be the
26762 @code{External_Name} with a leading underscore.
26764 When importing a variable defined in C, you should always use the @code{C}
26765 calling convention unless the object containing the variable is part of a
26766 DLL (in which case you should use the @code{Stdcall} calling
26767 convention, @pxref{Stdcall Calling Convention}).
26769 @node Stdcall Calling Convention
26770 @subsection @code{Stdcall} Calling Convention
26773 This convention, which was the calling convention used for Pascal
26774 programs, is used by Microsoft for all the routines in the Win32 API for
26775 efficiency reasons. It must be used to import any routine for which this
26776 convention was specified.
26778 In the @code{Stdcall} calling convention subprogram parameters are pushed
26779 on the stack by the caller from right to left. The callee (and not the
26780 caller) is in charge of cleaning the stack on routine exit. In addition,
26781 the name of a routine with @code{Stdcall} calling convention is mangled by
26782 adding a leading underscore (as for the @code{C} calling convention) and a
26783 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
26784 bytes) of the parameters passed to the routine.
26786 The name to use on the Ada side when importing a C routine with a
26787 @code{Stdcall} calling convention is the name of the C routine. The leading
26788 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
26789 the compiler. For instance the Win32 function:
26792 @b{APIENTRY} int get_val (long);
26796 should be imported from Ada as follows:
26798 @smallexample @c ada
26800 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26801 pragma Import (Stdcall, Get_Val);
26802 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26807 As for the @code{C} calling convention, when the @code{External_Name}
26808 parameter is missing, it is taken to be the name of the Ada entity in lower
26809 case. If instead of writing the above import pragma you write:
26811 @smallexample @c ada
26813 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26814 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26819 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26820 of specifying the @code{External_Name} parameter you specify the
26821 @code{Link_Name} as in the following example:
26823 @smallexample @c ada
26825 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26826 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26831 then the imported routine is @code{retrieve_val}, that is, there is no
26832 decoration at all. No leading underscore and no Stdcall suffix
26833 @code{@@}@code{@var{nn}}.
26836 This is especially important as in some special cases a DLL's entry
26837 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
26838 name generated for a call has it.
26841 It is also possible to import variables defined in a DLL by using an
26842 import pragma for a variable. As an example, if a DLL contains a
26843 variable defined as:
26850 then, to access this variable from Ada you should write:
26852 @smallexample @c ada
26854 My_Var : Interfaces.C.int;
26855 pragma Import (Stdcall, My_Var);
26860 Note that to ease building cross-platform bindings this convention
26861 will be handled as a @code{C} calling convention on non-Windows platforms.
26863 @node Win32 Calling Convention
26864 @subsection @code{Win32} Calling Convention
26867 This convention, which is GNAT-specific is fully equivalent to the
26868 @code{Stdcall} calling convention described above.
26870 @node DLL Calling Convention
26871 @subsection @code{DLL} Calling Convention
26874 This convention, which is GNAT-specific is fully equivalent to the
26875 @code{Stdcall} calling convention described above.
26877 @node Introduction to Dynamic Link Libraries (DLLs)
26878 @section Introduction to Dynamic Link Libraries (DLLs)
26882 A Dynamically Linked Library (DLL) is a library that can be shared by
26883 several applications running under Windows. A DLL can contain any number of
26884 routines and variables.
26886 One advantage of DLLs is that you can change and enhance them without
26887 forcing all the applications that depend on them to be relinked or
26888 recompiled. However, you should be aware than all calls to DLL routines are
26889 slower since, as you will understand below, such calls are indirect.
26891 To illustrate the remainder of this section, suppose that an application
26892 wants to use the services of a DLL @file{API.dll}. To use the services
26893 provided by @file{API.dll} you must statically link against the DLL or
26894 an import library which contains a jump table with an entry for each
26895 routine and variable exported by the DLL. In the Microsoft world this
26896 import library is called @file{API.lib}. When using GNAT this import
26897 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
26898 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26900 After you have linked your application with the DLL or the import library
26901 and you run your application, here is what happens:
26905 Your application is loaded into memory.
26908 The DLL @file{API.dll} is mapped into the address space of your
26909 application. This means that:
26913 The DLL will use the stack of the calling thread.
26916 The DLL will use the virtual address space of the calling process.
26919 The DLL will allocate memory from the virtual address space of the calling
26923 Handles (pointers) can be safely exchanged between routines in the DLL
26924 routines and routines in the application using the DLL.
26928 The entries in the jump table (from the import library @file{libAPI.dll.a}
26929 or @file{API.lib} or automatically created when linking against a DLL)
26930 which is part of your application are initialized with the addresses
26931 of the routines and variables in @file{API.dll}.
26934 If present in @file{API.dll}, routines @code{DllMain} or
26935 @code{DllMainCRTStartup} are invoked. These routines typically contain
26936 the initialization code needed for the well-being of the routines and
26937 variables exported by the DLL.
26941 There is an additional point which is worth mentioning. In the Windows
26942 world there are two kind of DLLs: relocatable and non-relocatable
26943 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26944 in the target application address space. If the addresses of two
26945 non-relocatable DLLs overlap and these happen to be used by the same
26946 application, a conflict will occur and the application will run
26947 incorrectly. Hence, when possible, it is always preferable to use and
26948 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26949 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26950 User's Guide) removes the debugging symbols from the DLL but the DLL can
26951 still be relocated.
26953 As a side note, an interesting difference between Microsoft DLLs and
26954 Unix shared libraries, is the fact that on most Unix systems all public
26955 routines are exported by default in a Unix shared library, while under
26956 Windows it is possible (but not required) to list exported routines in
26957 a definition file (@pxref{The Definition File}).
26959 @node Using DLLs with GNAT
26960 @section Using DLLs with GNAT
26963 * Creating an Ada Spec for the DLL Services::
26964 * Creating an Import Library::
26968 To use the services of a DLL, say @file{API.dll}, in your Ada application
26973 The Ada spec for the routines and/or variables you want to access in
26974 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26975 header files provided with the DLL.
26978 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
26979 mentioned an import library is a statically linked library containing the
26980 import table which will be filled at load time to point to the actual
26981 @file{API.dll} routines. Sometimes you don't have an import library for the
26982 DLL you want to use. The following sections will explain how to build
26983 one. Note that this is optional.
26986 The actual DLL, @file{API.dll}.
26990 Once you have all the above, to compile an Ada application that uses the
26991 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26992 you simply issue the command
26995 $ gnatmake my_ada_app -largs -lAPI
26999 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27000 tells the GNAT linker to look for an import library. The linker will
27001 look for a library name in this specific order:
27004 @item @file{libAPI.dll.a}
27005 @item @file{API.dll.a}
27006 @item @file{libAPI.a}
27007 @item @file{API.lib}
27008 @item @file{libAPI.dll}
27009 @item @file{API.dll}
27012 The first three are the GNU style import libraries. The third is the
27013 Microsoft style import libraries. The last two are the actual DLL names.
27015 Note that if the Ada package spec for @file{API.dll} contains the
27018 @smallexample @c ada
27019 pragma Linker_Options ("-lAPI");
27023 you do not have to add @option{-largs -lAPI} at the end of the
27024 @command{gnatmake} command.
27026 If any one of the items above is missing you will have to create it
27027 yourself. The following sections explain how to do so using as an
27028 example a fictitious DLL called @file{API.dll}.
27030 @node Creating an Ada Spec for the DLL Services
27031 @subsection Creating an Ada Spec for the DLL Services
27034 A DLL typically comes with a C/C++ header file which provides the
27035 definitions of the routines and variables exported by the DLL. The Ada
27036 equivalent of this header file is a package spec that contains definitions
27037 for the imported entities. If the DLL you intend to use does not come with
27038 an Ada spec you have to generate one such spec yourself. For example if
27039 the header file of @file{API.dll} is a file @file{api.h} containing the
27040 following two definitions:
27052 then the equivalent Ada spec could be:
27054 @smallexample @c ada
27057 with Interfaces.C.Strings;
27062 function Get (Str : C.Strings.Chars_Ptr) return C.int;
27065 pragma Import (C, Get);
27066 pragma Import (DLL, Some_Var);
27073 Note that a variable is
27074 @strong{always imported with a DLL convention}. A function
27075 can have @code{C} or @code{Stdcall} convention.
27076 (@pxref{Windows Calling Conventions}).
27078 @node Creating an Import Library
27079 @subsection Creating an Import Library
27080 @cindex Import library
27083 * The Definition File::
27084 * GNAT-Style Import Library::
27085 * Microsoft-Style Import Library::
27089 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27090 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27091 with @file{API.dll} you can skip this section. You can also skip this
27092 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27093 as in this case it is possible to link directly against the
27094 DLL. Otherwise read on.
27096 @node The Definition File
27097 @subsubsection The Definition File
27098 @cindex Definition file
27102 As previously mentioned, and unlike Unix systems, the list of symbols
27103 that are exported from a DLL must be provided explicitly in Windows.
27104 The main goal of a definition file is precisely that: list the symbols
27105 exported by a DLL. A definition file (usually a file with a @code{.def}
27106 suffix) has the following structure:
27111 @r{[}LIBRARY @var{name}@r{]}
27112 @r{[}DESCRIPTION @var{string}@r{]}
27122 @item LIBRARY @var{name}
27123 This section, which is optional, gives the name of the DLL.
27125 @item DESCRIPTION @var{string}
27126 This section, which is optional, gives a description string that will be
27127 embedded in the import library.
27130 This section gives the list of exported symbols (procedures, functions or
27131 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27132 section of @file{API.def} looks like:
27146 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27147 (@pxref{Windows Calling Conventions}) for a Stdcall
27148 calling convention function in the exported symbols list.
27151 There can actually be other sections in a definition file, but these
27152 sections are not relevant to the discussion at hand.
27154 @node GNAT-Style Import Library
27155 @subsubsection GNAT-Style Import Library
27158 To create a static import library from @file{API.dll} with the GNAT tools
27159 you should proceed as follows:
27163 Create the definition file @file{API.def} (@pxref{The Definition File}).
27164 For that use the @code{dll2def} tool as follows:
27167 $ dll2def API.dll > API.def
27171 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27172 to standard output the list of entry points in the DLL. Note that if
27173 some routines in the DLL have the @code{Stdcall} convention
27174 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27175 suffix then you'll have to edit @file{api.def} to add it, and specify
27176 @option{-k} to @command{gnatdll} when creating the import library.
27179 Here are some hints to find the right @code{@@}@var{nn} suffix.
27183 If you have the Microsoft import library (.lib), it is possible to get
27184 the right symbols by using Microsoft @code{dumpbin} tool (see the
27185 corresponding Microsoft documentation for further details).
27188 $ dumpbin /exports api.lib
27192 If you have a message about a missing symbol at link time the compiler
27193 tells you what symbol is expected. You just have to go back to the
27194 definition file and add the right suffix.
27198 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27199 (@pxref{Using gnatdll}) as follows:
27202 $ gnatdll -e API.def -d API.dll
27206 @code{gnatdll} takes as input a definition file @file{API.def} and the
27207 name of the DLL containing the services listed in the definition file
27208 @file{API.dll}. The name of the static import library generated is
27209 computed from the name of the definition file as follows: if the
27210 definition file name is @var{xyz}@code{.def}, the import library name will
27211 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27212 @option{-e} could have been removed because the name of the definition
27213 file (before the ``@code{.def}'' suffix) is the same as the name of the
27214 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27217 @node Microsoft-Style Import Library
27218 @subsubsection Microsoft-Style Import Library
27221 With GNAT you can either use a GNAT-style or Microsoft-style import
27222 library. A Microsoft import library is needed only if you plan to make an
27223 Ada DLL available to applications developed with Microsoft
27224 tools (@pxref{Mixed-Language Programming on Windows}).
27226 To create a Microsoft-style import library for @file{API.dll} you
27227 should proceed as follows:
27231 Create the definition file @file{API.def} from the DLL. For this use either
27232 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27233 tool (see the corresponding Microsoft documentation for further details).
27236 Build the actual import library using Microsoft's @code{lib} utility:
27239 $ lib -machine:IX86 -def:API.def -out:API.lib
27243 If you use the above command the definition file @file{API.def} must
27244 contain a line giving the name of the DLL:
27251 See the Microsoft documentation for further details about the usage of
27255 @node Building DLLs with GNAT Project files
27256 @section Building DLLs with GNAT Project files
27257 @cindex DLLs, building
27260 There is nothing specific to Windows in the build process.
27261 @pxref{Library Projects}.
27264 Due to a system limitation, it is not possible under Windows to create threads
27265 when inside the @code{DllMain} routine which is used for auto-initialization
27266 of shared libraries, so it is not possible to have library level tasks in SALs.
27268 @node Building DLLs with GNAT
27269 @section Building DLLs with GNAT
27270 @cindex DLLs, building
27273 This section explain how to build DLLs using the GNAT built-in DLL
27274 support. With the following procedure it is straight forward to build
27275 and use DLLs with GNAT.
27279 @item building object files
27281 The first step is to build all objects files that are to be included
27282 into the DLL. This is done by using the standard @command{gnatmake} tool.
27284 @item building the DLL
27286 To build the DLL you must use @command{gcc}'s @option{-shared} and
27287 @option{-shared-libgcc} options. It is quite simple to use this method:
27290 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
27293 It is important to note that in this case all symbols found in the
27294 object files are automatically exported. It is possible to restrict
27295 the set of symbols to export by passing to @command{gcc} a definition
27296 file, @pxref{The Definition File}. For example:
27299 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
27302 If you use a definition file you must export the elaboration procedures
27303 for every package that required one. Elaboration procedures are named
27304 using the package name followed by "_E".
27306 @item preparing DLL to be used
27308 For the DLL to be used by client programs the bodies must be hidden
27309 from it and the .ali set with read-only attribute. This is very important
27310 otherwise GNAT will recompile all packages and will not actually use
27311 the code in the DLL. For example:
27315 $ copy *.ads *.ali api.dll apilib
27316 $ attrib +R apilib\*.ali
27321 At this point it is possible to use the DLL by directly linking
27322 against it. Note that you must use the GNAT shared runtime when using
27323 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27327 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27330 @node Building DLLs with gnatdll
27331 @section Building DLLs with gnatdll
27332 @cindex DLLs, building
27335 * Limitations When Using Ada DLLs from Ada::
27336 * Exporting Ada Entities::
27337 * Ada DLLs and Elaboration::
27338 * Ada DLLs and Finalization::
27339 * Creating a Spec for Ada DLLs::
27340 * Creating the Definition File::
27345 Note that it is preferred to use GNAT Project files
27346 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27347 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27349 This section explains how to build DLLs containing Ada code using
27350 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27351 remainder of this section.
27353 The steps required to build an Ada DLL that is to be used by Ada as well as
27354 non-Ada applications are as follows:
27358 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27359 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27360 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27361 skip this step if you plan to use the Ada DLL only from Ada applications.
27364 Your Ada code must export an initialization routine which calls the routine
27365 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27366 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27367 routine exported by the Ada DLL must be invoked by the clients of the DLL
27368 to initialize the DLL.
27371 When useful, the DLL should also export a finalization routine which calls
27372 routine @code{adafinal} generated by @command{gnatbind} to perform the
27373 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27374 The finalization routine exported by the Ada DLL must be invoked by the
27375 clients of the DLL when the DLL services are no further needed.
27378 You must provide a spec for the services exported by the Ada DLL in each
27379 of the programming languages to which you plan to make the DLL available.
27382 You must provide a definition file listing the exported entities
27383 (@pxref{The Definition File}).
27386 Finally you must use @code{gnatdll} to produce the DLL and the import
27387 library (@pxref{Using gnatdll}).
27391 Note that a relocatable DLL stripped using the @code{strip}
27392 binutils tool will not be relocatable anymore. To build a DLL without
27393 debug information pass @code{-largs -s} to @code{gnatdll}. This
27394 restriction does not apply to a DLL built using a Library Project.
27395 @pxref{Library Projects}.
27397 @node Limitations When Using Ada DLLs from Ada
27398 @subsection Limitations When Using Ada DLLs from Ada
27401 When using Ada DLLs from Ada applications there is a limitation users
27402 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27403 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27404 each Ada DLL includes the services of the GNAT run time that are necessary
27405 to the Ada code inside the DLL. As a result, when an Ada program uses an
27406 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27407 one in the main program.
27409 It is therefore not possible to exchange GNAT run-time objects between the
27410 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27411 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27414 It is completely safe to exchange plain elementary, array or record types,
27415 Windows object handles, etc.
27417 @node Exporting Ada Entities
27418 @subsection Exporting Ada Entities
27419 @cindex Export table
27422 Building a DLL is a way to encapsulate a set of services usable from any
27423 application. As a result, the Ada entities exported by a DLL should be
27424 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27425 any Ada name mangling. As an example here is an Ada package
27426 @code{API}, spec and body, exporting two procedures, a function, and a
27429 @smallexample @c ada
27432 with Interfaces.C; use Interfaces;
27434 Count : C.int := 0;
27435 function Factorial (Val : C.int) return C.int;
27437 procedure Initialize_API;
27438 procedure Finalize_API;
27439 -- Initialization & Finalization routines. More in the next section.
27441 pragma Export (C, Initialize_API);
27442 pragma Export (C, Finalize_API);
27443 pragma Export (C, Count);
27444 pragma Export (C, Factorial);
27450 @smallexample @c ada
27453 package body API is
27454 function Factorial (Val : C.int) return C.int is
27457 Count := Count + 1;
27458 for K in 1 .. Val loop
27464 procedure Initialize_API is
27466 pragma Import (C, Adainit);
27469 end Initialize_API;
27471 procedure Finalize_API is
27472 procedure Adafinal;
27473 pragma Import (C, Adafinal);
27483 If the Ada DLL you are building will only be used by Ada applications
27484 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27485 convention. As an example, the previous package could be written as
27488 @smallexample @c ada
27492 Count : Integer := 0;
27493 function Factorial (Val : Integer) return Integer;
27495 procedure Initialize_API;
27496 procedure Finalize_API;
27497 -- Initialization and Finalization routines.
27503 @smallexample @c ada
27506 package body API is
27507 function Factorial (Val : Integer) return Integer is
27508 Fact : Integer := 1;
27510 Count := Count + 1;
27511 for K in 1 .. Val loop
27518 -- The remainder of this package body is unchanged.
27525 Note that if you do not export the Ada entities with a @code{C} or
27526 @code{Stdcall} convention you will have to provide the mangled Ada names
27527 in the definition file of the Ada DLL
27528 (@pxref{Creating the Definition File}).
27530 @node Ada DLLs and Elaboration
27531 @subsection Ada DLLs and Elaboration
27532 @cindex DLLs and elaboration
27535 The DLL that you are building contains your Ada code as well as all the
27536 routines in the Ada library that are needed by it. The first thing a
27537 user of your DLL must do is elaborate the Ada code
27538 (@pxref{Elaboration Order Handling in GNAT}).
27540 To achieve this you must export an initialization routine
27541 (@code{Initialize_API} in the previous example), which must be invoked
27542 before using any of the DLL services. This elaboration routine must call
27543 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27544 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27545 @code{Initialize_Api} for an example. Note that the GNAT binder is
27546 automatically invoked during the DLL build process by the @code{gnatdll}
27547 tool (@pxref{Using gnatdll}).
27549 When a DLL is loaded, Windows systematically invokes a routine called
27550 @code{DllMain}. It would therefore be possible to call @code{adainit}
27551 directly from @code{DllMain} without having to provide an explicit
27552 initialization routine. Unfortunately, it is not possible to call
27553 @code{adainit} from the @code{DllMain} if your program has library level
27554 tasks because access to the @code{DllMain} entry point is serialized by
27555 the system (that is, only a single thread can execute ``through'' it at a
27556 time), which means that the GNAT run time will deadlock waiting for the
27557 newly created task to complete its initialization.
27559 @node Ada DLLs and Finalization
27560 @subsection Ada DLLs and Finalization
27561 @cindex DLLs and finalization
27564 When the services of an Ada DLL are no longer needed, the client code should
27565 invoke the DLL finalization routine, if available. The DLL finalization
27566 routine is in charge of releasing all resources acquired by the DLL. In the
27567 case of the Ada code contained in the DLL, this is achieved by calling
27568 routine @code{adafinal} generated by the GNAT binder
27569 (@pxref{Binding with Non-Ada Main Programs}).
27570 See the body of @code{Finalize_Api} for an
27571 example. As already pointed out the GNAT binder is automatically invoked
27572 during the DLL build process by the @code{gnatdll} tool
27573 (@pxref{Using gnatdll}).
27575 @node Creating a Spec for Ada DLLs
27576 @subsection Creating a Spec for Ada DLLs
27579 To use the services exported by the Ada DLL from another programming
27580 language (e.g.@: C), you have to translate the specs of the exported Ada
27581 entities in that language. For instance in the case of @code{API.dll},
27582 the corresponding C header file could look like:
27587 extern int *_imp__count;
27588 #define count (*_imp__count)
27589 int factorial (int);
27595 It is important to understand that when building an Ada DLL to be used by
27596 other Ada applications, you need two different specs for the packages
27597 contained in the DLL: one for building the DLL and the other for using
27598 the DLL. This is because the @code{DLL} calling convention is needed to
27599 use a variable defined in a DLL, but when building the DLL, the variable
27600 must have either the @code{Ada} or @code{C} calling convention. As an
27601 example consider a DLL comprising the following package @code{API}:
27603 @smallexample @c ada
27607 Count : Integer := 0;
27609 -- Remainder of the package omitted.
27616 After producing a DLL containing package @code{API}, the spec that
27617 must be used to import @code{API.Count} from Ada code outside of the
27620 @smallexample @c ada
27625 pragma Import (DLL, Count);
27631 @node Creating the Definition File
27632 @subsection Creating the Definition File
27635 The definition file is the last file needed to build the DLL. It lists
27636 the exported symbols. As an example, the definition file for a DLL
27637 containing only package @code{API} (where all the entities are exported
27638 with a @code{C} calling convention) is:
27653 If the @code{C} calling convention is missing from package @code{API},
27654 then the definition file contains the mangled Ada names of the above
27655 entities, which in this case are:
27664 api__initialize_api
27669 @node Using gnatdll
27670 @subsection Using @code{gnatdll}
27674 * gnatdll Example::
27675 * gnatdll behind the Scenes::
27680 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27681 and non-Ada sources that make up your DLL have been compiled.
27682 @code{gnatdll} is actually in charge of two distinct tasks: build the
27683 static import library for the DLL and the actual DLL. The form of the
27684 @code{gnatdll} command is
27688 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27689 @c Expanding @ovar macro inline (explanation in macro def comments)
27690 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27695 where @var{list-of-files} is a list of ALI and object files. The object
27696 file list must be the exact list of objects corresponding to the non-Ada
27697 sources whose services are to be included in the DLL. The ALI file list
27698 must be the exact list of ALI files for the corresponding Ada sources
27699 whose services are to be included in the DLL. If @var{list-of-files} is
27700 missing, only the static import library is generated.
27703 You may specify any of the following switches to @code{gnatdll}:
27706 @c @item -a@ovar{address}
27707 @c Expanding @ovar macro inline (explanation in macro def comments)
27708 @item -a@r{[}@var{address}@r{]}
27709 @cindex @option{-a} (@code{gnatdll})
27710 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27711 specified the default address @var{0x11000000} will be used. By default,
27712 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27713 advise the reader to build relocatable DLL.
27715 @item -b @var{address}
27716 @cindex @option{-b} (@code{gnatdll})
27717 Set the relocatable DLL base address. By default the address is
27720 @item -bargs @var{opts}
27721 @cindex @option{-bargs} (@code{gnatdll})
27722 Binder options. Pass @var{opts} to the binder.
27724 @item -d @var{dllfile}
27725 @cindex @option{-d} (@code{gnatdll})
27726 @var{dllfile} is the name of the DLL. This switch must be present for
27727 @code{gnatdll} to do anything. The name of the generated import library is
27728 obtained algorithmically from @var{dllfile} as shown in the following
27729 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27730 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
27731 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27732 as shown in the following example:
27733 if @var{dllfile} is @code{xyz.dll}, the definition
27734 file used is @code{xyz.def}.
27736 @item -e @var{deffile}
27737 @cindex @option{-e} (@code{gnatdll})
27738 @var{deffile} is the name of the definition file.
27741 @cindex @option{-g} (@code{gnatdll})
27742 Generate debugging information. This information is stored in the object
27743 file and copied from there to the final DLL file by the linker,
27744 where it can be read by the debugger. You must use the
27745 @option{-g} switch if you plan on using the debugger or the symbolic
27749 @cindex @option{-h} (@code{gnatdll})
27750 Help mode. Displays @code{gnatdll} switch usage information.
27753 @cindex @option{-I} (@code{gnatdll})
27754 Direct @code{gnatdll} to search the @var{dir} directory for source and
27755 object files needed to build the DLL.
27756 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27759 @cindex @option{-k} (@code{gnatdll})
27760 Removes the @code{@@}@var{nn} suffix from the import library's exported
27761 names, but keeps them for the link names. You must specify this
27762 option if you want to use a @code{Stdcall} function in a DLL for which
27763 the @code{@@}@var{nn} suffix has been removed. This is the case for most
27764 of the Windows NT DLL for example. This option has no effect when
27765 @option{-n} option is specified.
27767 @item -l @var{file}
27768 @cindex @option{-l} (@code{gnatdll})
27769 The list of ALI and object files used to build the DLL are listed in
27770 @var{file}, instead of being given in the command line. Each line in
27771 @var{file} contains the name of an ALI or object file.
27774 @cindex @option{-n} (@code{gnatdll})
27775 No Import. Do not create the import library.
27778 @cindex @option{-q} (@code{gnatdll})
27779 Quiet mode. Do not display unnecessary messages.
27782 @cindex @option{-v} (@code{gnatdll})
27783 Verbose mode. Display extra information.
27785 @item -largs @var{opts}
27786 @cindex @option{-largs} (@code{gnatdll})
27787 Linker options. Pass @var{opts} to the linker.
27790 @node gnatdll Example
27791 @subsubsection @code{gnatdll} Example
27794 As an example the command to build a relocatable DLL from @file{api.adb}
27795 once @file{api.adb} has been compiled and @file{api.def} created is
27798 $ gnatdll -d api.dll api.ali
27802 The above command creates two files: @file{libapi.dll.a} (the import
27803 library) and @file{api.dll} (the actual DLL). If you want to create
27804 only the DLL, just type:
27807 $ gnatdll -d api.dll -n api.ali
27811 Alternatively if you want to create just the import library, type:
27814 $ gnatdll -d api.dll
27817 @node gnatdll behind the Scenes
27818 @subsubsection @code{gnatdll} behind the Scenes
27821 This section details the steps involved in creating a DLL. @code{gnatdll}
27822 does these steps for you. Unless you are interested in understanding what
27823 goes on behind the scenes, you should skip this section.
27825 We use the previous example of a DLL containing the Ada package @code{API},
27826 to illustrate the steps necessary to build a DLL. The starting point is a
27827 set of objects that will make up the DLL and the corresponding ALI
27828 files. In the case of this example this means that @file{api.o} and
27829 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27834 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27835 the information necessary to generate relocation information for the
27841 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27846 In addition to the base file, the @command{gnatlink} command generates an
27847 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27848 asks @command{gnatlink} to generate the routines @code{DllMain} and
27849 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27850 is loaded into memory.
27853 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27854 export table (@file{api.exp}). The export table contains the relocation
27855 information in a form which can be used during the final link to ensure
27856 that the Windows loader is able to place the DLL anywhere in memory.
27860 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27861 --output-exp api.exp
27866 @code{gnatdll} builds the base file using the new export table. Note that
27867 @command{gnatbind} must be called once again since the binder generated file
27868 has been deleted during the previous call to @command{gnatlink}.
27873 $ gnatlink api -o api.jnk api.exp -mdll
27874 -Wl,--base-file,api.base
27879 @code{gnatdll} builds the new export table using the new base file and
27880 generates the DLL import library @file{libAPI.dll.a}.
27884 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27885 --output-exp api.exp --output-lib libAPI.a
27890 Finally @code{gnatdll} builds the relocatable DLL using the final export
27896 $ gnatlink api api.exp -o api.dll -mdll
27901 @node Using dlltool
27902 @subsubsection Using @code{dlltool}
27905 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27906 DLLs and static import libraries. This section summarizes the most
27907 common @code{dlltool} switches. The form of the @code{dlltool} command
27911 @c $ dlltool @ovar{switches}
27912 @c Expanding @ovar macro inline (explanation in macro def comments)
27913 $ dlltool @r{[}@var{switches}@r{]}
27917 @code{dlltool} switches include:
27920 @item --base-file @var{basefile}
27921 @cindex @option{--base-file} (@command{dlltool})
27922 Read the base file @var{basefile} generated by the linker. This switch
27923 is used to create a relocatable DLL.
27925 @item --def @var{deffile}
27926 @cindex @option{--def} (@command{dlltool})
27927 Read the definition file.
27929 @item --dllname @var{name}
27930 @cindex @option{--dllname} (@command{dlltool})
27931 Gives the name of the DLL. This switch is used to embed the name of the
27932 DLL in the static import library generated by @code{dlltool} with switch
27933 @option{--output-lib}.
27936 @cindex @option{-k} (@command{dlltool})
27937 Kill @code{@@}@var{nn} from exported names
27938 (@pxref{Windows Calling Conventions}
27939 for a discussion about @code{Stdcall}-style symbols.
27942 @cindex @option{--help} (@command{dlltool})
27943 Prints the @code{dlltool} switches with a concise description.
27945 @item --output-exp @var{exportfile}
27946 @cindex @option{--output-exp} (@command{dlltool})
27947 Generate an export file @var{exportfile}. The export file contains the
27948 export table (list of symbols in the DLL) and is used to create the DLL.
27950 @item --output-lib @var{libfile}
27951 @cindex @option{--output-lib} (@command{dlltool})
27952 Generate a static import library @var{libfile}.
27955 @cindex @option{-v} (@command{dlltool})
27958 @item --as @var{assembler-name}
27959 @cindex @option{--as} (@command{dlltool})
27960 Use @var{assembler-name} as the assembler. The default is @code{as}.
27963 @node GNAT and Windows Resources
27964 @section GNAT and Windows Resources
27965 @cindex Resources, windows
27968 * Building Resources::
27969 * Compiling Resources::
27970 * Using Resources::
27974 Resources are an easy way to add Windows specific objects to your
27975 application. The objects that can be added as resources include:
27984 @item string tables
27994 @item version information
27997 For example, a version information resource can be defined as follow and
27998 embedded into an executable or DLL:
28000 A version information resource can be used to embed information into an
28001 executable or a DLL. These information can be viewed using the file properties
28002 from the Windows Explorer. Here is an example of a version information
28008 FILEVERSION 1,0,0,0
28009 PRODUCTVERSION 1,0,0,0
28011 BLOCK "StringFileInfo"
28015 VALUE "CompanyName", "My Company Name"
28016 VALUE "FileDescription", "My application"
28017 VALUE "FileVersion", "1.0"
28018 VALUE "InternalName", "my_app"
28019 VALUE "LegalCopyright", "My Name"
28020 VALUE "OriginalFilename", "my_app.exe"
28021 VALUE "ProductName", "My App"
28022 VALUE "ProductVersion", "1.0"
28026 BLOCK "VarFileInfo"
28028 VALUE "Translation", 0x809, 1252
28034 The value @code{0809} (langID) is for the U.K English language and
28035 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28039 This section explains how to build, compile and use resources. Note that this
28040 section does not cover all resource objects, for a complete description see
28041 the corresponding Microsoft documentation.
28043 @node Building Resources
28044 @subsection Building Resources
28045 @cindex Resources, building
28048 A resource file is an ASCII file. By convention resource files have an
28049 @file{.rc} extension.
28050 The easiest way to build a resource file is to use Microsoft tools
28051 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28052 @code{dlgedit.exe} to build dialogs.
28053 It is always possible to build an @file{.rc} file yourself by writing a
28056 It is not our objective to explain how to write a resource file. A
28057 complete description of the resource script language can be found in the
28058 Microsoft documentation.
28060 @node Compiling Resources
28061 @subsection Compiling Resources
28064 @cindex Resources, compiling
28067 This section describes how to build a GNAT-compatible (COFF) object file
28068 containing the resources. This is done using the Resource Compiler
28069 @code{windres} as follows:
28072 $ windres -i myres.rc -o myres.o
28076 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28077 file. You can specify an alternate preprocessor (usually named
28078 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28079 parameter. A list of all possible options may be obtained by entering
28080 the command @code{windres} @option{--help}.
28082 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28083 to produce a @file{.res} file (binary resource file). See the
28084 corresponding Microsoft documentation for further details. In this case
28085 you need to use @code{windres} to translate the @file{.res} file to a
28086 GNAT-compatible object file as follows:
28089 $ windres -i myres.res -o myres.o
28092 @node Using Resources
28093 @subsection Using Resources
28094 @cindex Resources, using
28097 To include the resource file in your program just add the
28098 GNAT-compatible object file for the resource(s) to the linker
28099 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28103 $ gnatmake myprog -largs myres.o
28106 @node Debugging a DLL
28107 @section Debugging a DLL
28108 @cindex DLL debugging
28111 * Program and DLL Both Built with GCC/GNAT::
28112 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28116 Debugging a DLL is similar to debugging a standard program. But
28117 we have to deal with two different executable parts: the DLL and the
28118 program that uses it. We have the following four possibilities:
28122 The program and the DLL are built with @code{GCC/GNAT}.
28124 The program is built with foreign tools and the DLL is built with
28127 The program is built with @code{GCC/GNAT} and the DLL is built with
28132 In this section we address only cases one and two above.
28133 There is no point in trying to debug
28134 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28135 information in it. To do so you must use a debugger compatible with the
28136 tools suite used to build the DLL.
28138 @node Program and DLL Both Built with GCC/GNAT
28139 @subsection Program and DLL Both Built with GCC/GNAT
28142 This is the simplest case. Both the DLL and the program have @code{GDB}
28143 compatible debugging information. It is then possible to break anywhere in
28144 the process. Let's suppose here that the main procedure is named
28145 @code{ada_main} and that in the DLL there is an entry point named
28149 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28150 program must have been built with the debugging information (see GNAT -g
28151 switch). Here are the step-by-step instructions for debugging it:
28154 @item Launch @code{GDB} on the main program.
28160 @item Start the program and stop at the beginning of the main procedure
28167 This step is required to be able to set a breakpoint inside the DLL. As long
28168 as the program is not run, the DLL is not loaded. This has the
28169 consequence that the DLL debugging information is also not loaded, so it is not
28170 possible to set a breakpoint in the DLL.
28172 @item Set a breakpoint inside the DLL
28175 (gdb) break ada_dll
28182 At this stage a breakpoint is set inside the DLL. From there on
28183 you can use the standard approach to debug the whole program
28184 (@pxref{Running and Debugging Ada Programs}).
28187 @c This used to work, probably because the DLLs were non-relocatable
28188 @c keep this section around until the problem is sorted out.
28190 To break on the @code{DllMain} routine it is not possible to follow
28191 the procedure above. At the time the program stop on @code{ada_main}
28192 the @code{DllMain} routine as already been called. Either you can use
28193 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28196 @item Launch @code{GDB} on the main program.
28202 @item Load DLL symbols
28205 (gdb) add-sym api.dll
28208 @item Set a breakpoint inside the DLL
28211 (gdb) break ada_dll.adb:45
28214 Note that at this point it is not possible to break using the routine symbol
28215 directly as the program is not yet running. The solution is to break
28216 on the proper line (break in @file{ada_dll.adb} line 45).
28218 @item Start the program
28227 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28228 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28231 * Debugging the DLL Directly::
28232 * Attaching to a Running Process::
28236 In this case things are slightly more complex because it is not possible to
28237 start the main program and then break at the beginning to load the DLL and the
28238 associated DLL debugging information. It is not possible to break at the
28239 beginning of the program because there is no @code{GDB} debugging information,
28240 and therefore there is no direct way of getting initial control. This
28241 section addresses this issue by describing some methods that can be used
28242 to break somewhere in the DLL to debug it.
28245 First suppose that the main procedure is named @code{main} (this is for
28246 example some C code built with Microsoft Visual C) and that there is a
28247 DLL named @code{test.dll} containing an Ada entry point named
28251 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28252 been built with debugging information (see GNAT -g option).
28254 @node Debugging the DLL Directly
28255 @subsubsection Debugging the DLL Directly
28259 Find out the executable starting address
28262 $ objdump --file-header main.exe
28265 The starting address is reported on the last line. For example:
28268 main.exe: file format pei-i386
28269 architecture: i386, flags 0x0000010a:
28270 EXEC_P, HAS_DEBUG, D_PAGED
28271 start address 0x00401010
28275 Launch the debugger on the executable.
28282 Set a breakpoint at the starting address, and launch the program.
28285 $ (gdb) break *0x00401010
28289 The program will stop at the given address.
28292 Set a breakpoint on a DLL subroutine.
28295 (gdb) break ada_dll.adb:45
28298 Or if you want to break using a symbol on the DLL, you need first to
28299 select the Ada language (language used by the DLL).
28302 (gdb) set language ada
28303 (gdb) break ada_dll
28307 Continue the program.
28314 This will run the program until it reaches the breakpoint that has been
28315 set. From that point you can use the standard way to debug a program
28316 as described in (@pxref{Running and Debugging Ada Programs}).
28321 It is also possible to debug the DLL by attaching to a running process.
28323 @node Attaching to a Running Process
28324 @subsubsection Attaching to a Running Process
28325 @cindex DLL debugging, attach to process
28328 With @code{GDB} it is always possible to debug a running process by
28329 attaching to it. It is possible to debug a DLL this way. The limitation
28330 of this approach is that the DLL must run long enough to perform the
28331 attach operation. It may be useful for instance to insert a time wasting
28332 loop in the code of the DLL to meet this criterion.
28336 @item Launch the main program @file{main.exe}.
28342 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28343 that the process PID for @file{main.exe} is 208.
28351 @item Attach to the running process to be debugged.
28357 @item Load the process debugging information.
28360 (gdb) symbol-file main.exe
28363 @item Break somewhere in the DLL.
28366 (gdb) break ada_dll
28369 @item Continue process execution.
28378 This last step will resume the process execution, and stop at
28379 the breakpoint we have set. From there you can use the standard
28380 approach to debug a program as described in
28381 (@pxref{Running and Debugging Ada Programs}).
28383 @node Setting Stack Size from gnatlink
28384 @section Setting Stack Size from @command{gnatlink}
28387 It is possible to specify the program stack size at link time. On modern
28388 versions of Windows, starting with XP, this is mostly useful to set the size of
28389 the main stack (environment task). The other task stacks are set with pragma
28390 Storage_Size or with the @command{gnatbind -d} command.
28392 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28393 reserve size of individual tasks, the link-time stack size applies to all
28394 tasks, and pragma Storage_Size has no effect.
28395 In particular, Stack Overflow checks are made against this
28396 link-time specified size.
28398 This setting can be done with
28399 @command{gnatlink} using either:
28403 @item using @option{-Xlinker} linker option
28406 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28409 This sets the stack reserve size to 0x10000 bytes and the stack commit
28410 size to 0x1000 bytes.
28412 @item using @option{-Wl} linker option
28415 $ gnatlink hello -Wl,--stack=0x1000000
28418 This sets the stack reserve size to 0x1000000 bytes. Note that with
28419 @option{-Wl} option it is not possible to set the stack commit size
28420 because the coma is a separator for this option.
28424 @node Setting Heap Size from gnatlink
28425 @section Setting Heap Size from @command{gnatlink}
28428 Under Windows systems, it is possible to specify the program heap size from
28429 @command{gnatlink} using either:
28433 @item using @option{-Xlinker} linker option
28436 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28439 This sets the heap reserve size to 0x10000 bytes and the heap commit
28440 size to 0x1000 bytes.
28442 @item using @option{-Wl} linker option
28445 $ gnatlink hello -Wl,--heap=0x1000000
28448 This sets the heap reserve size to 0x1000000 bytes. Note that with
28449 @option{-Wl} option it is not possible to set the heap commit size
28450 because the coma is a separator for this option.
28456 @c **********************************
28457 @c * GNU Free Documentation License *
28458 @c **********************************
28460 @c GNU Free Documentation License
28462 @node Index,,GNU Free Documentation License, Top
28468 @c Put table of contents at end, otherwise it precedes the "title page" in
28469 @c the .txt version
28470 @c Edit the pdf file to move the contents to the beginning, after the title