1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2012, 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 * Creating Unit Tests Using gnattest::
196 * Generating Ada Bindings for C and C++ headers::
197 * Other Utility Programs::
198 * Running and Debugging Ada Programs::
200 * Code Coverage and Profiling::
203 * Compatibility with HP Ada::
205 * Platform-Specific Information for the Run-Time Libraries::
206 * Example of Binder Output File::
207 * Elaboration Order Handling in GNAT::
208 * Conditional Compilation::
210 * Compatibility and Porting Guide::
212 * Microsoft Windows Topics::
214 * GNU Free Documentation License::
217 --- The Detailed Node Listing ---
221 * What This Guide Contains::
222 * What You Should Know before Reading This Guide::
223 * Related Information::
226 Getting Started with GNAT
229 * Running a Simple Ada Program::
230 * Running a Program with Multiple Units::
231 * Using the gnatmake Utility::
233 * Editing with Emacs::
236 * Introduction to GPS::
239 The GNAT Compilation Model
241 * Source Representation::
242 * Foreign Language Representation::
243 * File Naming Rules::
244 * Using Other File Names::
245 * Alternative File Naming Schemes::
246 * Generating Object Files::
247 * Source Dependencies::
248 * The Ada Library Information Files::
249 * Binding an Ada Program::
250 * Mixed Language Programming::
252 * Building Mixed Ada & C++ Programs::
253 * Comparison between GNAT and C/C++ Compilation Models::
255 * Comparison between GNAT and Conventional Ada Library Models::
257 * Placement of temporary files::
260 Foreign Language Representation
263 * Other 8-Bit Codes::
264 * Wide Character Encodings::
266 Compiling Ada Programs With gcc
268 * Compiling Programs::
270 * Search Paths and the Run-Time Library (RTL)::
271 * Order of Compilation Issues::
276 * Output and Error Message Control::
277 * Warning Message Control::
278 * Debugging and Assertion Control::
279 * Validity Checking::
282 * Using gcc for Syntax Checking::
283 * Using gcc for Semantic Checking::
284 * Compiling Different Versions of Ada::
285 * Character Set Control::
286 * File Naming Control::
287 * Subprogram Inlining Control::
288 * Auxiliary Output Control::
289 * Debugging Control::
290 * Exception Handling Control::
291 * Units to Sources Mapping Files::
292 * Integrated Preprocessing::
297 Binding Ada Programs With gnatbind
300 * Switches for gnatbind::
301 * Command-Line Access::
302 * Search Paths for gnatbind::
303 * Examples of gnatbind Usage::
305 Switches for gnatbind
307 * Consistency-Checking Modes::
308 * Binder Error Message Control::
309 * Elaboration Control::
311 * Binding with Non-Ada Main Programs::
312 * Binding Programs with No Main Subprogram::
314 Linking Using gnatlink
317 * Switches for gnatlink::
319 The GNAT Make Program gnatmake
322 * Switches for gnatmake::
323 * Mode Switches for gnatmake::
324 * Notes on the Command Line::
325 * How gnatmake Works::
326 * Examples of gnatmake Usage::
328 Improving Performance
329 * Performance Considerations::
330 * Text_IO Suggestions::
331 * Reducing Size of Ada Executables with gnatelim::
332 * Reducing Size of Executables with unused subprogram/data elimination::
334 Performance Considerations
335 * Controlling Run-Time Checks::
336 * Use of Restrictions::
337 * Optimization Levels::
338 * Debugging Optimized Code::
339 * Inlining of Subprograms::
340 * Vectorization of loops::
341 * Other Optimization Switches::
342 * Optimization and Strict Aliasing::
344 * Coverage Analysis::
347 Reducing Size of Ada Executables with gnatelim
350 * Processing Precompiled Libraries::
351 * Correcting the List of Eliminate Pragmas::
352 * Making Your Executables Smaller::
353 * Summary of the gnatelim Usage Cycle::
355 Reducing Size of Executables with unused subprogram/data elimination
356 * About unused subprogram/data elimination::
357 * Compilation options::
359 Renaming Files Using gnatchop
361 * Handling Files with Multiple Units::
362 * Operating gnatchop in Compilation Mode::
363 * Command Line for gnatchop::
364 * Switches for gnatchop::
365 * Examples of gnatchop Usage::
367 Configuration Pragmas
369 * Handling of Configuration Pragmas::
370 * The Configuration Pragmas Files::
372 Handling Arbitrary File Naming Conventions Using gnatname
374 * Arbitrary File Naming Conventions::
376 * Switches for gnatname::
377 * Examples of gnatname Usage::
379 The Cross-Referencing Tools gnatxref and gnatfind
381 * Switches for gnatxref::
382 * Switches for gnatfind::
383 * Project Files for gnatxref and gnatfind::
384 * Regular Expressions in gnatfind and gnatxref::
385 * Examples of gnatxref Usage::
386 * Examples of gnatfind Usage::
388 The GNAT Pretty-Printer gnatpp
390 * Switches for gnatpp::
393 The GNAT Metrics Tool gnatmetric
395 * Switches for gnatmetric::
397 File Name Krunching Using gnatkr
402 * Examples of gnatkr Usage::
404 Preprocessing Using gnatprep
405 * Preprocessing Symbols::
407 * Switches for gnatprep::
408 * Form of Definitions File::
409 * Form of Input Text for gnatprep::
411 The GNAT Library Browser gnatls
414 * Switches for gnatls::
415 * Examples of gnatls Usage::
417 Cleaning Up Using gnatclean
419 * Running gnatclean::
420 * Switches for gnatclean::
421 @c * Examples of gnatclean Usage::
427 * Introduction to Libraries in GNAT::
428 * General Ada Libraries::
429 * Stand-alone Ada Libraries::
430 * Rebuilding the GNAT Run-Time Library::
432 Using the GNU make Utility
434 * Using gnatmake in a Makefile::
435 * Automatically Creating a List of Directories::
436 * Generating the Command Line Switches::
437 * Overcoming Command Line Length Limits::
440 Memory Management Issues
442 * Some Useful Memory Pools::
443 * The GNAT Debug Pool Facility::
448 Stack Related Facilities
450 * Stack Overflow Checking::
451 * Static Stack Usage Analysis::
452 * Dynamic Stack Usage Analysis::
454 Some Useful Memory Pools
456 The GNAT Debug Pool Facility
462 * Switches for gnatmem::
463 * Example of gnatmem Usage::
466 Verifying Properties Using gnatcheck
468 Sample Bodies Using gnatstub
471 * Switches for gnatstub::
473 Creating Unit Tests Using gnattest
476 * Switches for gnattest::
477 * Project Attributes for gnattest::
479 * Setting Up and Tearing Down the Testing Environment::
480 * Regenerating Tests::
481 * Default Test Behavior::
482 * Testing Primitive Operations of Tagged Types::
483 * Testing Inheritance::
484 * Tagged Types Substitutability Testing::
485 * Testing with Contracts::
487 * Current Limitations::
489 Other Utility Programs
491 * Using Other Utility Programs with GNAT::
492 * The External Symbol Naming Scheme of GNAT::
493 * Converting Ada Files to html with gnathtml::
496 Code Coverage and Profiling
498 * Code Coverage of Ada Programs using gcov::
499 * Profiling an Ada Program using gprof::
502 Running and Debugging Ada Programs
504 * The GNAT Debugger GDB::
506 * Introduction to GDB Commands::
507 * Using Ada Expressions::
508 * Calling User-Defined Subprograms::
509 * Using the Next Command in a Function::
512 * Debugging Generic Units::
513 * Remote Debugging using gdbserver::
514 * GNAT Abnormal Termination or Failure to Terminate::
515 * Naming Conventions for GNAT Source Files::
516 * Getting Internal Debugging Information::
524 Compatibility with HP Ada
526 * Ada Language Compatibility::
527 * Differences in the Definition of Package System::
528 * Language-Related Features::
529 * The Package STANDARD::
530 * The Package SYSTEM::
531 * Tasking and Task-Related Features::
532 * Pragmas and Pragma-Related Features::
533 * Library of Predefined Units::
535 * Main Program Definition::
536 * Implementation-Defined Attributes::
537 * Compiler and Run-Time Interfacing::
538 * Program Compilation and Library Management::
540 * Implementation Limits::
541 * Tools and Utilities::
543 Language-Related Features
545 * Integer Types and Representations::
546 * Floating-Point Types and Representations::
547 * Pragmas Float_Representation and Long_Float::
548 * Fixed-Point Types and Representations::
549 * Record and Array Component Alignment::
551 * Other Representation Clauses::
553 Tasking and Task-Related Features
555 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
556 * Assigning Task IDs::
557 * Task IDs and Delays::
558 * Task-Related Pragmas::
559 * Scheduling and Task Priority::
561 * External Interrupts::
563 Pragmas and Pragma-Related Features
565 * Restrictions on the Pragma INLINE::
566 * Restrictions on the Pragma INTERFACE::
567 * Restrictions on the Pragma SYSTEM_NAME::
569 Library of Predefined Units
571 * Changes to DECLIB::
575 * Shared Libraries and Options Files::
579 Platform-Specific Information for the Run-Time Libraries
581 * Summary of Run-Time Configurations::
582 * Specifying a Run-Time Library::
583 * Choosing the Scheduling Policy::
584 * Solaris-Specific Considerations::
585 * Linux-Specific Considerations::
586 * AIX-Specific Considerations::
587 * Irix-Specific Considerations::
588 * RTX-Specific Considerations::
589 * HP-UX-Specific Considerations::
591 Example of Binder Output File
593 Elaboration Order Handling in GNAT
596 * Checking the Elaboration Order::
597 * Controlling the Elaboration Order::
598 * Controlling Elaboration in GNAT - Internal Calls::
599 * Controlling Elaboration in GNAT - External Calls::
600 * Default Behavior in GNAT - Ensuring Safety::
601 * Treatment of Pragma Elaborate::
602 * Elaboration Issues for Library Tasks::
603 * Mixing Elaboration Models::
604 * What to Do If the Default Elaboration Behavior Fails::
605 * Elaboration for Access-to-Subprogram Values::
606 * Summary of Procedures for Elaboration Control::
607 * Other Elaboration Order Considerations::
609 Conditional Compilation
610 * Use of Boolean Constants::
611 * Debugging - A Special Case::
612 * Conditionalizing Declarations::
613 * Use of Alternative Implementations::
618 * Basic Assembler Syntax::
619 * A Simple Example of Inline Assembler::
620 * Output Variables in Inline Assembler::
621 * Input Variables in Inline Assembler::
622 * Inlining Inline Assembler Code::
623 * Other Asm Functionality::
625 Compatibility and Porting Guide
627 * Compatibility with Ada 83::
628 * Compatibility between Ada 95 and Ada 2005::
629 * Implementation-dependent characteristics::
631 @c This brief section is only in the non-VMS version
632 @c The complete chapter on HP Ada issues is in the VMS version
633 * Compatibility with HP Ada 83::
635 * Compatibility with Other Ada Systems::
636 * Representation Clauses::
638 * Transitioning to 64-Bit GNAT for OpenVMS::
642 Microsoft Windows Topics
644 * Using GNAT on Windows::
645 * CONSOLE and WINDOWS subsystems::
647 * Mixed-Language Programming on Windows::
648 * Windows Calling Conventions::
649 * Introduction to Dynamic Link Libraries (DLLs)::
650 * Using DLLs with GNAT::
651 * Building DLLs with GNAT::
652 * GNAT and Windows Resources::
654 * Setting Stack Size from gnatlink::
655 * Setting Heap Size from gnatlink::
662 @node About This Guide
663 @unnumbered About This Guide
667 This guide describes the use of @value{EDITION},
668 a compiler and software development toolset for the full Ada
669 programming language, implemented on OpenVMS for HP's Alpha and
670 Integrity server (I64) platforms.
673 This guide describes the use of @value{EDITION},
674 a compiler and software development
675 toolset for the full Ada programming language.
677 It documents the features of the compiler and tools, and explains
678 how to use them to build Ada applications.
680 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
681 Ada 83 compatibility mode.
682 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
683 but you can override with a compiler switch
684 (@pxref{Compiling Different Versions of Ada})
685 to explicitly specify the language version.
686 Throughout this manual, references to ``Ada'' without a year suffix
687 apply to both the Ada 95 and Ada 2005 versions of the language.
691 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
692 ``GNAT'' in the remainder of this document.
699 * What This Guide Contains::
700 * What You Should Know before Reading This Guide::
701 * Related Information::
705 @node What This Guide Contains
706 @unnumberedsec What This Guide Contains
709 This guide contains the following chapters:
713 @ref{Getting Started with GNAT}, describes how to get started compiling
714 and running Ada programs with the GNAT Ada programming environment.
716 @ref{The GNAT Compilation Model}, describes the compilation model used
720 @ref{Compiling Using gcc}, describes how to compile
721 Ada programs with @command{gcc}, the Ada compiler.
724 @ref{Binding Using gnatbind}, describes how to
725 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
729 @ref{Linking Using gnatlink},
730 describes @command{gnatlink}, a
731 program that provides for linking using the GNAT run-time library to
732 construct a program. @command{gnatlink} can also incorporate foreign language
733 object units into the executable.
736 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
737 utility that automatically determines the set of sources
738 needed by an Ada compilation unit, and executes the necessary compilations
742 @ref{Improving Performance}, shows various techniques for making your
743 Ada program run faster or take less space.
744 It discusses the effect of the compiler's optimization switch and
745 also describes the @command{gnatelim} tool and unused subprogram/data
749 @ref{Renaming Files Using gnatchop}, describes
750 @code{gnatchop}, a utility that allows you to preprocess a file that
751 contains Ada source code, and split it into one or more new files, one
752 for each compilation unit.
755 @ref{Configuration Pragmas}, describes the configuration pragmas
759 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
760 shows how to override the default GNAT file naming conventions,
761 either for an individual unit or globally.
764 @ref{GNAT Project Manager}, describes how to use project files
765 to organize large projects.
768 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
769 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
770 way to navigate through sources.
773 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
774 version of an Ada source file with control over casing, indentation,
775 comment placement, and other elements of program presentation style.
778 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
779 metrics for an Ada source file, such as the number of types and subprograms,
780 and assorted complexity measures.
783 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
784 file name krunching utility, used to handle shortened
785 file names on operating systems with a limit on the length of names.
788 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
789 preprocessor utility that allows a single source file to be used to
790 generate multiple or parameterized source files by means of macro
794 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
795 utility that displays information about compiled units, including dependences
796 on the corresponding sources files, and consistency of compilations.
799 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
800 to delete files that are produced by the compiler, binder and linker.
804 @ref{GNAT and Libraries}, describes the process of creating and using
805 Libraries with GNAT. It also describes how to recompile the GNAT run-time
809 @ref{Using the GNU make Utility}, describes some techniques for using
810 the GNAT toolset in Makefiles.
814 @ref{Memory Management Issues}, describes some useful predefined storage pools
815 and in particular the GNAT Debug Pool facility, which helps detect incorrect
818 It also describes @command{gnatmem}, a utility that monitors dynamic
819 allocation and deallocation and helps detect ``memory leaks''.
823 @ref{Stack Related Facilities}, describes some useful tools associated with
824 stack checking and analysis.
827 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
828 a utility that checks Ada code against a set of rules.
831 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
832 a utility that generates empty but compilable bodies for library units.
835 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
836 a utility that generates unit testing templates for library units.
839 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
840 generate automatically Ada bindings from C and C++ headers.
843 @ref{Other Utility Programs}, discusses several other GNAT utilities,
844 including @code{gnathtml}.
848 @ref{Code Coverage and Profiling}, describes how to perform a structural
849 coverage and profile the execution of Ada programs.
853 @ref{Running and Debugging Ada Programs}, describes how to run and debug
858 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
859 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
860 developed by Digital Equipment Corporation and currently supported by HP.}
861 for OpenVMS Alpha. This product was formerly known as DEC Ada,
864 historical compatibility reasons, the relevant libraries still use the
869 @ref{Platform-Specific Information for the Run-Time Libraries},
870 describes the various run-time
871 libraries supported by GNAT on various platforms and explains how to
872 choose a particular library.
875 @ref{Example of Binder Output File}, shows the source code for the binder
876 output file for a sample program.
879 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
880 you deal with elaboration order issues.
883 @ref{Conditional Compilation}, describes how to model conditional compilation,
884 both with Ada in general and with GNAT facilities in particular.
887 @ref{Inline Assembler}, shows how to use the inline assembly facility
891 @ref{Compatibility and Porting Guide}, contains sections on compatibility
892 of GNAT with other Ada development environments (including Ada 83 systems),
893 to assist in porting code from those environments.
897 @ref{Microsoft Windows Topics}, presents information relevant to the
898 Microsoft Windows platform.
902 @c *************************************************
903 @node What You Should Know before Reading This Guide
904 @c *************************************************
905 @unnumberedsec What You Should Know before Reading This Guide
907 @cindex Ada 95 Language Reference Manual
908 @cindex Ada 2005 Language Reference Manual
910 This guide assumes a basic familiarity with the Ada 95 language, as
911 described in the International Standard ANSI/ISO/IEC-8652:1995, January
913 It does not require knowledge of the new features introduced by Ada 2005,
914 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
916 Both reference manuals are included in the GNAT documentation
919 @node Related Information
920 @unnumberedsec Related Information
923 For further information about related tools, refer to the following
928 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
929 Reference Manual}, which contains all reference material for the GNAT
930 implementation of Ada.
934 @cite{Using the GNAT Programming Studio}, which describes the GPS
935 Integrated Development Environment.
938 @cite{GNAT Programming Studio Tutorial}, which introduces the
939 main GPS features through examples.
943 @cite{Ada 95 Reference Manual}, which contains reference
944 material for the Ada 95 programming language.
947 @cite{Ada 2005 Reference Manual}, which contains reference
948 material for the Ada 2005 programming language.
951 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
953 in the GNU:[DOCS] directory,
955 for all details on the use of the GNU source-level debugger.
958 @xref{Top,, The extensible self-documenting text editor, emacs,
961 located in the GNU:[DOCS] directory if the EMACS kit is installed,
963 for full information on the extensible editor and programming
970 @unnumberedsec Conventions
972 @cindex Typographical conventions
975 Following are examples of the typographical and graphic conventions used
980 @code{Functions}, @command{utility program names}, @code{standard names},
984 @option{Option flags}
987 @file{File names}, @samp{button names}, and @samp{field names}.
990 @code{Variables}, @env{environment variables}, and @var{metasyntactic
997 @r{[}optional information or parameters@r{]}
1000 Examples are described by text
1002 and then shown this way.
1007 Commands that are entered by the user are preceded in this manual by the
1008 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1009 uses this sequence as a prompt, then the commands will appear exactly as
1010 you see them in the manual. If your system uses some other prompt, then
1011 the command will appear with the @code{$} replaced by whatever prompt
1012 character you are using.
1015 Full file names are shown with the ``@code{/}'' character
1016 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1017 If you are using GNAT on a Windows platform, please note that
1018 the ``@code{\}'' character should be used instead.
1021 @c ****************************
1022 @node Getting Started with GNAT
1023 @chapter Getting Started with GNAT
1026 This chapter describes some simple ways of using GNAT to build
1027 executable Ada programs.
1029 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1030 show how to use the command line environment.
1031 @ref{Introduction to GPS}, provides a brief
1032 introduction to the GNAT Programming Studio, a visually-oriented
1033 Integrated Development Environment for GNAT.
1034 GPS offers a graphical ``look and feel'', support for development in
1035 other programming languages, comprehensive browsing features, and
1036 many other capabilities.
1037 For information on GPS please refer to
1038 @cite{Using the GNAT Programming Studio}.
1043 * Running a Simple Ada Program::
1044 * Running a Program with Multiple Units::
1045 * Using the gnatmake Utility::
1047 * Editing with Emacs::
1050 * Introduction to GPS::
1055 @section Running GNAT
1058 Three steps are needed to create an executable file from an Ada source
1063 The source file(s) must be compiled.
1065 The file(s) must be bound using the GNAT binder.
1067 All appropriate object files must be linked to produce an executable.
1071 All three steps are most commonly handled by using the @command{gnatmake}
1072 utility program that, given the name of the main program, automatically
1073 performs the necessary compilation, binding and linking steps.
1075 @node Running a Simple Ada Program
1076 @section Running a Simple Ada Program
1079 Any text editor may be used to prepare an Ada program.
1081 used, the optional Ada mode may be helpful in laying out the program.)
1083 program text is a normal text file. We will assume in our initial
1084 example that you have used your editor to prepare the following
1085 standard format text file:
1087 @smallexample @c ada
1089 with Ada.Text_IO; use Ada.Text_IO;
1092 Put_Line ("Hello WORLD!");
1098 This file should be named @file{hello.adb}.
1099 With the normal default file naming conventions, GNAT requires
1101 contain a single compilation unit whose file name is the
1103 with periods replaced by hyphens; the
1104 extension is @file{ads} for a
1105 spec and @file{adb} for a body.
1106 You can override this default file naming convention by use of the
1107 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1108 Alternatively, if you want to rename your files according to this default
1109 convention, which is probably more convenient if you will be using GNAT
1110 for all your compilations, then the @code{gnatchop} utility
1111 can be used to generate correctly-named source files
1112 (@pxref{Renaming Files Using gnatchop}).
1114 You can compile the program using the following command (@code{$} is used
1115 as the command prompt in the examples in this document):
1122 @command{gcc} is the command used to run the compiler. This compiler is
1123 capable of compiling programs in several languages, including Ada and
1124 C. It assumes that you have given it an Ada program if the file extension is
1125 either @file{.ads} or @file{.adb}, and it will then call
1126 the GNAT compiler to compile the specified file.
1129 The @option{-c} switch is required. It tells @command{gcc} to only do a
1130 compilation. (For C programs, @command{gcc} can also do linking, but this
1131 capability is not used directly for Ada programs, so the @option{-c}
1132 switch must always be present.)
1135 This compile command generates a file
1136 @file{hello.o}, which is the object
1137 file corresponding to your Ada program. It also generates
1138 an ``Ada Library Information'' file @file{hello.ali},
1139 which contains additional information used to check
1140 that an Ada program is consistent.
1141 To build an executable file,
1142 use @code{gnatbind} to bind the program
1143 and @command{gnatlink} to link it. The
1144 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1145 @file{ALI} file, but the default extension of @file{.ali} can
1146 be omitted. This means that in the most common case, the argument
1147 is simply the name of the main program:
1155 A simpler method of carrying out these steps is to use
1157 a master program that invokes all the required
1158 compilation, binding and linking tools in the correct order. In particular,
1159 @command{gnatmake} automatically recompiles any sources that have been
1160 modified since they were last compiled, or sources that depend
1161 on such modified sources, so that ``version skew'' is avoided.
1162 @cindex Version skew (avoided by @command{gnatmake})
1165 $ gnatmake hello.adb
1169 The result is an executable program called @file{hello}, which can be
1177 assuming that the current directory is on the search path
1178 for executable programs.
1181 and, if all has gone well, you will see
1188 appear in response to this command.
1190 @c ****************************************
1191 @node Running a Program with Multiple Units
1192 @section Running a Program with Multiple Units
1195 Consider a slightly more complicated example that has three files: a
1196 main program, and the spec and body of a package:
1198 @smallexample @c ada
1201 package Greetings is
1206 with Ada.Text_IO; use Ada.Text_IO;
1207 package body Greetings is
1210 Put_Line ("Hello WORLD!");
1213 procedure Goodbye is
1215 Put_Line ("Goodbye WORLD!");
1232 Following the one-unit-per-file rule, place this program in the
1233 following three separate files:
1237 spec of package @code{Greetings}
1240 body of package @code{Greetings}
1243 body of main program
1247 To build an executable version of
1248 this program, we could use four separate steps to compile, bind, and link
1249 the program, as follows:
1253 $ gcc -c greetings.adb
1259 Note that there is no required order of compilation when using GNAT.
1260 In particular it is perfectly fine to compile the main program first.
1261 Also, it is not necessary to compile package specs in the case where
1262 there is an accompanying body; you only need to compile the body. If you want
1263 to submit these files to the compiler for semantic checking and not code
1264 generation, then use the
1265 @option{-gnatc} switch:
1268 $ gcc -c greetings.ads -gnatc
1272 Although the compilation can be done in separate steps as in the
1273 above example, in practice it is almost always more convenient
1274 to use the @command{gnatmake} tool. All you need to know in this case
1275 is the name of the main program's source file. The effect of the above four
1276 commands can be achieved with a single one:
1279 $ gnatmake gmain.adb
1283 In the next section we discuss the advantages of using @command{gnatmake} in
1286 @c *****************************
1287 @node Using the gnatmake Utility
1288 @section Using the @command{gnatmake} Utility
1291 If you work on a program by compiling single components at a time using
1292 @command{gcc}, you typically keep track of the units you modify. In order to
1293 build a consistent system, you compile not only these units, but also any
1294 units that depend on the units you have modified.
1295 For example, in the preceding case,
1296 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1297 you edit @file{greetings.ads}, you must recompile both
1298 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1299 units that depend on @file{greetings.ads}.
1301 @code{gnatbind} will warn you if you forget one of these compilation
1302 steps, so that it is impossible to generate an inconsistent program as a
1303 result of forgetting to do a compilation. Nevertheless it is tedious and
1304 error-prone to keep track of dependencies among units.
1305 One approach to handle the dependency-bookkeeping is to use a
1306 makefile. However, makefiles present maintenance problems of their own:
1307 if the dependencies change as you change the program, you must make
1308 sure that the makefile is kept up-to-date manually, which is also an
1309 error-prone process.
1311 The @command{gnatmake} utility takes care of these details automatically.
1312 Invoke it using either one of the following forms:
1315 $ gnatmake gmain.adb
1316 $ gnatmake ^gmain^GMAIN^
1320 The argument is the name of the file containing the main program;
1321 you may omit the extension. @command{gnatmake}
1322 examines the environment, automatically recompiles any files that need
1323 recompiling, and binds and links the resulting set of object files,
1324 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1325 In a large program, it
1326 can be extremely helpful to use @command{gnatmake}, because working out by hand
1327 what needs to be recompiled can be difficult.
1329 Note that @command{gnatmake}
1330 takes into account all the Ada rules that
1331 establish dependencies among units. These include dependencies that result
1332 from inlining subprogram bodies, and from
1333 generic instantiation. Unlike some other
1334 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1335 found by the compiler on a previous compilation, which may possibly
1336 be wrong when sources change. @command{gnatmake} determines the exact set of
1337 dependencies from scratch each time it is run.
1340 @node Editing with Emacs
1341 @section Editing with Emacs
1345 Emacs is an extensible self-documenting text editor that is available in a
1346 separate VMSINSTAL kit.
1348 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1349 click on the Emacs Help menu and run the Emacs Tutorial.
1350 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1351 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1353 Documentation on Emacs and other tools is available in Emacs under the
1354 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1355 use the middle mouse button to select a topic (e.g.@: Emacs).
1357 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1358 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1359 get to the Emacs manual.
1360 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1363 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1364 which is sufficiently extensible to provide for a complete programming
1365 environment and shell for the sophisticated user.
1369 @node Introduction to GPS
1370 @section Introduction to GPS
1371 @cindex GPS (GNAT Programming Studio)
1372 @cindex GNAT Programming Studio (GPS)
1374 Although the command line interface (@command{gnatmake}, etc.) alone
1375 is sufficient, a graphical Interactive Development
1376 Environment can make it easier for you to compose, navigate, and debug
1377 programs. This section describes the main features of GPS
1378 (``GNAT Programming Studio''), the GNAT graphical IDE.
1379 You will see how to use GPS to build and debug an executable, and
1380 you will also learn some of the basics of the GNAT ``project'' facility.
1382 GPS enables you to do much more than is presented here;
1383 e.g., you can produce a call graph, interface to a third-party
1384 Version Control System, and inspect the generated assembly language
1386 Indeed, GPS also supports languages other than Ada.
1387 Such additional information, and an explanation of all of the GPS menu
1388 items. may be found in the on-line help, which includes
1389 a user's guide and a tutorial (these are also accessible from the GNAT
1393 * Building a New Program with GPS::
1394 * Simple Debugging with GPS::
1397 @node Building a New Program with GPS
1398 @subsection Building a New Program with GPS
1400 GPS invokes the GNAT compilation tools using information
1401 contained in a @emph{project} (also known as a @emph{project file}):
1402 a collection of properties such
1403 as source directories, identities of main subprograms, tool switches, etc.,
1404 and their associated values.
1405 See @ref{GNAT Project Manager} for details.
1406 In order to run GPS, you will need to either create a new project
1407 or else open an existing one.
1409 This section will explain how you can use GPS to create a project,
1410 to associate Ada source files with a project, and to build and run
1414 @item @emph{Creating a project}
1416 Invoke GPS, either from the command line or the platform's IDE.
1417 After it starts, GPS will display a ``Welcome'' screen with three
1422 @code{Start with default project in directory}
1425 @code{Create new project with wizard}
1428 @code{Open existing project}
1432 Select @code{Create new project with wizard} and press @code{OK}.
1433 A new window will appear. In the text box labeled with
1434 @code{Enter the name of the project to create}, type @file{sample}
1435 as the project name.
1436 In the next box, browse to choose the directory in which you
1437 would like to create the project file.
1438 After selecting an appropriate directory, press @code{Forward}.
1440 A window will appear with the title
1441 @code{Version Control System Configuration}.
1442 Simply press @code{Forward}.
1444 A window will appear with the title
1445 @code{Please select the source directories for this project}.
1446 The directory that you specified for the project file will be selected
1447 by default as the one to use for sources; simply press @code{Forward}.
1449 A window will appear with the title
1450 @code{Please select the build directory for this project}.
1451 The directory that you specified for the project file will be selected
1452 by default for object files and executables;
1453 simply press @code{Forward}.
1455 A window will appear with the title
1456 @code{Please select the main units for this project}.
1457 You will supply this information later, after creating the source file.
1458 Simply press @code{Forward} for now.
1460 A window will appear with the title
1461 @code{Please select the switches to build the project}.
1462 Press @code{Apply}. This will create a project file named
1463 @file{sample.prj} in the directory that you had specified.
1465 @item @emph{Creating and saving the source file}
1467 After you create the new project, a GPS window will appear, which is
1468 partitioned into two main sections:
1472 A @emph{Workspace area}, initially greyed out, which you will use for
1473 creating and editing source files
1476 Directly below, a @emph{Messages area}, which initially displays a
1477 ``Welcome'' message.
1478 (If the Messages area is not visible, drag its border upward to expand it.)
1482 Select @code{File} on the menu bar, and then the @code{New} command.
1483 The Workspace area will become white, and you can now
1484 enter the source program explicitly.
1485 Type the following text
1487 @smallexample @c ada
1489 with Ada.Text_IO; use Ada.Text_IO;
1492 Put_Line("Hello from GPS!");
1498 Select @code{File}, then @code{Save As}, and enter the source file name
1500 The file will be saved in the same directory you specified as the
1501 location of the default project file.
1503 @item @emph{Updating the project file}
1505 You need to add the new source file to the project.
1507 the @code{Project} menu and then @code{Edit project properties}.
1508 Click the @code{Main files} tab on the left, and then the
1510 Choose @file{hello.adb} from the list, and press @code{Open}.
1511 The project settings window will reflect this action.
1514 @item @emph{Building and running the program}
1516 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1517 and select @file{hello.adb}.
1518 The Messages window will display the resulting invocations of @command{gcc},
1519 @command{gnatbind}, and @command{gnatlink}
1520 (reflecting the default switch settings from the
1521 project file that you created) and then a ``successful compilation/build''
1524 To run the program, choose the @code{Build} menu, then @code{Run}, and
1525 select @command{hello}.
1526 An @emph{Arguments Selection} window will appear.
1527 There are no command line arguments, so just click @code{OK}.
1529 The Messages window will now display the program's output (the string
1530 @code{Hello from GPS}), and at the bottom of the GPS window a status
1531 update is displayed (@code{Run: hello}).
1532 Close the GPS window (or select @code{File}, then @code{Exit}) to
1533 terminate this GPS session.
1536 @node Simple Debugging with GPS
1537 @subsection Simple Debugging with GPS
1539 This section illustrates basic debugging techniques (setting breakpoints,
1540 examining/modifying variables, single stepping).
1543 @item @emph{Opening a project}
1545 Start GPS and select @code{Open existing project}; browse to
1546 specify the project file @file{sample.prj} that you had created in the
1549 @item @emph{Creating a source file}
1551 Select @code{File}, then @code{New}, and type in the following program:
1553 @smallexample @c ada
1555 with Ada.Text_IO; use Ada.Text_IO;
1556 procedure Example is
1557 Line : String (1..80);
1560 Put_Line("Type a line of text at each prompt; an empty line to exit");
1564 Put_Line (Line (1..N) );
1572 Select @code{File}, then @code{Save as}, and enter the file name
1575 @item @emph{Updating the project file}
1577 Add @code{Example} as a new main unit for the project:
1580 Select @code{Project}, then @code{Edit Project Properties}.
1583 Select the @code{Main files} tab, click @code{Add}, then
1584 select the file @file{example.adb} from the list, and
1586 You will see the file name appear in the list of main units
1592 @item @emph{Building/running the executable}
1594 To build the executable
1595 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1597 Run the program to see its effect (in the Messages area).
1598 Each line that you enter is displayed; an empty line will
1599 cause the loop to exit and the program to terminate.
1601 @item @emph{Debugging the program}
1603 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1604 which are required for debugging, are on by default when you create
1606 Thus unless you intentionally remove these settings, you will be able
1607 to debug any program that you develop using GPS.
1610 @item @emph{Initializing}
1612 Select @code{Debug}, then @code{Initialize}, then @file{example}
1614 @item @emph{Setting a breakpoint}
1616 After performing the initialization step, you will observe a small
1617 icon to the right of each line number.
1618 This serves as a toggle for breakpoints; clicking the icon will
1619 set a breakpoint at the corresponding line (the icon will change to
1620 a red circle with an ``x''), and clicking it again
1621 will remove the breakpoint / reset the icon.
1623 For purposes of this example, set a breakpoint at line 10 (the
1624 statement @code{Put_Line@ (Line@ (1..N));}
1626 @item @emph{Starting program execution}
1628 Select @code{Debug}, then @code{Run}. When the
1629 @code{Program Arguments} window appears, click @code{OK}.
1630 A console window will appear; enter some line of text,
1631 e.g.@: @code{abcde}, at the prompt.
1632 The program will pause execution when it gets to the
1633 breakpoint, and the corresponding line is highlighted.
1635 @item @emph{Examining a variable}
1637 Move the mouse over one of the occurrences of the variable @code{N}.
1638 You will see the value (5) displayed, in ``tool tip'' fashion.
1639 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1640 You will see information about @code{N} appear in the @code{Debugger Data}
1641 pane, showing the value as 5.
1643 @item @emph{Assigning a new value to a variable}
1645 Right click on the @code{N} in the @code{Debugger Data} pane, and
1646 select @code{Set value of N}.
1647 When the input window appears, enter the value @code{4} and click
1649 This value does not automatically appear in the @code{Debugger Data}
1650 pane; to see it, right click again on the @code{N} in the
1651 @code{Debugger Data} pane and select @code{Update value}.
1652 The new value, 4, will appear in red.
1654 @item @emph{Single stepping}
1656 Select @code{Debug}, then @code{Next}.
1657 This will cause the next statement to be executed, in this case the
1658 call of @code{Put_Line} with the string slice.
1659 Notice in the console window that the displayed string is simply
1660 @code{abcd} and not @code{abcde} which you had entered.
1661 This is because the upper bound of the slice is now 4 rather than 5.
1663 @item @emph{Removing a breakpoint}
1665 Toggle the breakpoint icon at line 10.
1667 @item @emph{Resuming execution from a breakpoint}
1669 Select @code{Debug}, then @code{Continue}.
1670 The program will reach the next iteration of the loop, and
1671 wait for input after displaying the prompt.
1672 This time, just hit the @kbd{Enter} key.
1673 The value of @code{N} will be 0, and the program will terminate.
1674 The console window will disappear.
1679 @node The GNAT Compilation Model
1680 @chapter The GNAT Compilation Model
1681 @cindex GNAT compilation model
1682 @cindex Compilation model
1685 * Source Representation::
1686 * Foreign Language Representation::
1687 * File Naming Rules::
1688 * Using Other File Names::
1689 * Alternative File Naming Schemes::
1690 * Generating Object Files::
1691 * Source Dependencies::
1692 * The Ada Library Information Files::
1693 * Binding an Ada Program::
1694 * Mixed Language Programming::
1696 * Building Mixed Ada & C++ Programs::
1697 * Comparison between GNAT and C/C++ Compilation Models::
1699 * Comparison between GNAT and Conventional Ada Library Models::
1701 * Placement of temporary files::
1706 This chapter describes the compilation model used by GNAT. Although
1707 similar to that used by other languages, such as C and C++, this model
1708 is substantially different from the traditional Ada compilation models,
1709 which are based on a library. The model is initially described without
1710 reference to the library-based model. If you have not previously used an
1711 Ada compiler, you need only read the first part of this chapter. The
1712 last section describes and discusses the differences between the GNAT
1713 model and the traditional Ada compiler models. If you have used other
1714 Ada compilers, this section will help you to understand those
1715 differences, and the advantages of the GNAT model.
1717 @node Source Representation
1718 @section Source Representation
1722 Ada source programs are represented in standard text files, using
1723 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1724 7-bit ASCII set, plus additional characters used for
1725 representing foreign languages (@pxref{Foreign Language Representation}
1726 for support of non-USA character sets). The format effector characters
1727 are represented using their standard ASCII encodings, as follows:
1732 Vertical tab, @code{16#0B#}
1736 Horizontal tab, @code{16#09#}
1740 Carriage return, @code{16#0D#}
1744 Line feed, @code{16#0A#}
1748 Form feed, @code{16#0C#}
1752 Source files are in standard text file format. In addition, GNAT will
1753 recognize a wide variety of stream formats, in which the end of
1754 physical lines is marked by any of the following sequences:
1755 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1756 in accommodating files that are imported from other operating systems.
1758 @cindex End of source file
1759 @cindex Source file, end
1761 The end of a source file is normally represented by the physical end of
1762 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1763 recognized as signalling the end of the source file. Again, this is
1764 provided for compatibility with other operating systems where this
1765 code is used to represent the end of file.
1767 Each file contains a single Ada compilation unit, including any pragmas
1768 associated with the unit. For example, this means you must place a
1769 package declaration (a package @dfn{spec}) and the corresponding body in
1770 separate files. An Ada @dfn{compilation} (which is a sequence of
1771 compilation units) is represented using a sequence of files. Similarly,
1772 you will place each subunit or child unit in a separate file.
1774 @node Foreign Language Representation
1775 @section Foreign Language Representation
1778 GNAT supports the standard character sets defined in Ada as well as
1779 several other non-standard character sets for use in localized versions
1780 of the compiler (@pxref{Character Set Control}).
1783 * Other 8-Bit Codes::
1784 * Wide Character Encodings::
1792 The basic character set is Latin-1. This character set is defined by ISO
1793 standard 8859, part 1. The lower half (character codes @code{16#00#}
1794 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1795 half is used to represent additional characters. These include extended letters
1796 used by European languages, such as French accents, the vowels with umlauts
1797 used in German, and the extra letter A-ring used in Swedish.
1799 @findex Ada.Characters.Latin_1
1800 For a complete list of Latin-1 codes and their encodings, see the source
1801 file of library unit @code{Ada.Characters.Latin_1} in file
1802 @file{a-chlat1.ads}.
1803 You may use any of these extended characters freely in character or
1804 string literals. In addition, the extended characters that represent
1805 letters can be used in identifiers.
1807 @node Other 8-Bit Codes
1808 @subsection Other 8-Bit Codes
1811 GNAT also supports several other 8-bit coding schemes:
1814 @item ISO 8859-2 (Latin-2)
1817 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1820 @item ISO 8859-3 (Latin-3)
1823 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1826 @item ISO 8859-4 (Latin-4)
1829 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1832 @item ISO 8859-5 (Cyrillic)
1835 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1836 lowercase equivalence.
1838 @item ISO 8859-15 (Latin-9)
1841 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1842 lowercase equivalence
1844 @item IBM PC (code page 437)
1845 @cindex code page 437
1846 This code page is the normal default for PCs in the U.S. It corresponds
1847 to the original IBM PC character set. This set has some, but not all, of
1848 the extended Latin-1 letters, but these letters do not have the same
1849 encoding as Latin-1. In this mode, these letters are allowed in
1850 identifiers with uppercase and lowercase equivalence.
1852 @item IBM PC (code page 850)
1853 @cindex code page 850
1854 This code page is a modification of 437 extended to include all the
1855 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1856 mode, all these letters are allowed in identifiers with uppercase and
1857 lowercase equivalence.
1859 @item Full Upper 8-bit
1860 Any character in the range 80-FF allowed in identifiers, and all are
1861 considered distinct. In other words, there are no uppercase and lowercase
1862 equivalences in this range. This is useful in conjunction with
1863 certain encoding schemes used for some foreign character sets (e.g.,
1864 the typical method of representing Chinese characters on the PC).
1867 No upper-half characters in the range 80-FF are allowed in identifiers.
1868 This gives Ada 83 compatibility for identifier names.
1872 For precise data on the encodings permitted, and the uppercase and lowercase
1873 equivalences that are recognized, see the file @file{csets.adb} in
1874 the GNAT compiler sources. You will need to obtain a full source release
1875 of GNAT to obtain this file.
1877 @node Wide Character Encodings
1878 @subsection Wide Character Encodings
1881 GNAT allows wide character codes to appear in character and string
1882 literals, and also optionally in identifiers, by means of the following
1883 possible encoding schemes:
1888 In this encoding, a wide character is represented by the following five
1896 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1897 characters (using uppercase letters) of the wide character code. For
1898 example, ESC A345 is used to represent the wide character with code
1900 This scheme is compatible with use of the full Wide_Character set.
1902 @item Upper-Half Coding
1903 @cindex Upper-Half Coding
1904 The wide character with encoding @code{16#abcd#} where the upper bit is on
1905 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1906 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1907 character, but is not required to be in the upper half. This method can
1908 be also used for shift-JIS or EUC, where the internal coding matches the
1911 @item Shift JIS Coding
1912 @cindex Shift JIS Coding
1913 A wide character is represented by a two-character sequence,
1915 @code{16#cd#}, with the restrictions described for upper-half encoding as
1916 described above. The internal character code is the corresponding JIS
1917 character according to the standard algorithm for Shift-JIS
1918 conversion. Only characters defined in the JIS code set table can be
1919 used with this encoding method.
1923 A wide character is represented by a two-character sequence
1925 @code{16#cd#}, with both characters being in the upper half. The internal
1926 character code is the corresponding JIS character according to the EUC
1927 encoding algorithm. Only characters defined in the JIS code set table
1928 can be used with this encoding method.
1931 A wide character is represented using
1932 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1933 10646-1/Am.2. Depending on the character value, the representation
1934 is a one, two, or three byte sequence:
1939 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1940 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1941 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1946 where the @var{xxx} bits correspond to the left-padded bits of the
1947 16-bit character value. Note that all lower half ASCII characters
1948 are represented as ASCII bytes and all upper half characters and
1949 other wide characters are represented as sequences of upper-half
1950 (The full UTF-8 scheme allows for encoding 31-bit characters as
1951 6-byte sequences, but in this implementation, all UTF-8 sequences
1952 of four or more bytes length will be treated as illegal).
1953 @item Brackets Coding
1954 In this encoding, a wide character is represented by the following eight
1962 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1963 characters (using uppercase letters) of the wide character code. For
1964 example, [``A345''] is used to represent the wide character with code
1965 @code{16#A345#}. It is also possible (though not required) to use the
1966 Brackets coding for upper half characters. For example, the code
1967 @code{16#A3#} can be represented as @code{[``A3'']}.
1969 This scheme is compatible with use of the full Wide_Character set,
1970 and is also the method used for wide character encoding in the standard
1971 ACVC (Ada Compiler Validation Capability) test suite distributions.
1976 Note: Some of these coding schemes do not permit the full use of the
1977 Ada character set. For example, neither Shift JIS, nor EUC allow the
1978 use of the upper half of the Latin-1 set.
1980 @node File Naming Rules
1981 @section File Naming Rules
1984 The default file name is determined by the name of the unit that the
1985 file contains. The name is formed by taking the full expanded name of
1986 the unit and replacing the separating dots with hyphens and using
1987 ^lowercase^uppercase^ for all letters.
1989 An exception arises if the file name generated by the above rules starts
1990 with one of the characters
1992 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1995 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1997 and the second character is a
1998 minus. In this case, the character ^tilde^dollar sign^ is used in place
1999 of the minus. The reason for this special rule is to avoid clashes with
2000 the standard names for child units of the packages System, Ada,
2001 Interfaces, and GNAT, which use the prefixes
2003 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2006 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2010 The file extension is @file{.ads} for a spec and
2011 @file{.adb} for a body. The following list shows some
2012 examples of these rules.
2019 @item arith_functions.ads
2020 Arith_Functions (package spec)
2021 @item arith_functions.adb
2022 Arith_Functions (package body)
2024 Func.Spec (child package spec)
2026 Func.Spec (child package body)
2028 Sub (subunit of Main)
2029 @item ^a~bad.adb^A$BAD.ADB^
2030 A.Bad (child package body)
2034 Following these rules can result in excessively long
2035 file names if corresponding
2036 unit names are long (for example, if child units or subunits are
2037 heavily nested). An option is available to shorten such long file names
2038 (called file name ``krunching''). This may be particularly useful when
2039 programs being developed with GNAT are to be used on operating systems
2040 with limited file name lengths. @xref{Using gnatkr}.
2042 Of course, no file shortening algorithm can guarantee uniqueness over
2043 all possible unit names; if file name krunching is used, it is your
2044 responsibility to ensure no name clashes occur. Alternatively you
2045 can specify the exact file names that you want used, as described
2046 in the next section. Finally, if your Ada programs are migrating from a
2047 compiler with a different naming convention, you can use the gnatchop
2048 utility to produce source files that follow the GNAT naming conventions.
2049 (For details @pxref{Renaming Files Using gnatchop}.)
2051 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2052 systems, case is not significant. So for example on @code{Windows XP}
2053 if the canonical name is @code{main-sub.adb}, you can use the file name
2054 @code{Main-Sub.adb} instead. However, case is significant for other
2055 operating systems, so for example, if you want to use other than
2056 canonically cased file names on a Unix system, you need to follow
2057 the procedures described in the next section.
2059 @node Using Other File Names
2060 @section Using Other File Names
2064 In the previous section, we have described the default rules used by
2065 GNAT to determine the file name in which a given unit resides. It is
2066 often convenient to follow these default rules, and if you follow them,
2067 the compiler knows without being explicitly told where to find all
2070 However, in some cases, particularly when a program is imported from
2071 another Ada compiler environment, it may be more convenient for the
2072 programmer to specify which file names contain which units. GNAT allows
2073 arbitrary file names to be used by means of the Source_File_Name pragma.
2074 The form of this pragma is as shown in the following examples:
2075 @cindex Source_File_Name pragma
2077 @smallexample @c ada
2079 pragma Source_File_Name (My_Utilities.Stacks,
2080 Spec_File_Name => "myutilst_a.ada");
2081 pragma Source_File_name (My_Utilities.Stacks,
2082 Body_File_Name => "myutilst.ada");
2087 As shown in this example, the first argument for the pragma is the unit
2088 name (in this example a child unit). The second argument has the form
2089 of a named association. The identifier
2090 indicates whether the file name is for a spec or a body;
2091 the file name itself is given by a string literal.
2093 The source file name pragma is a configuration pragma, which means that
2094 normally it will be placed in the @file{gnat.adc}
2095 file used to hold configuration
2096 pragmas that apply to a complete compilation environment.
2097 For more details on how the @file{gnat.adc} file is created and used
2098 see @ref{Handling of Configuration Pragmas}.
2099 @cindex @file{gnat.adc}
2102 GNAT allows completely arbitrary file names to be specified using the
2103 source file name pragma. However, if the file name specified has an
2104 extension other than @file{.ads} or @file{.adb} it is necessary to use
2105 a special syntax when compiling the file. The name in this case must be
2106 preceded by the special sequence @option{-x} followed by a space and the name
2107 of the language, here @code{ada}, as in:
2110 $ gcc -c -x ada peculiar_file_name.sim
2115 @command{gnatmake} handles non-standard file names in the usual manner (the
2116 non-standard file name for the main program is simply used as the
2117 argument to gnatmake). Note that if the extension is also non-standard,
2118 then it must be included in the @command{gnatmake} command, it may not
2121 @node Alternative File Naming Schemes
2122 @section Alternative File Naming Schemes
2123 @cindex File naming schemes, alternative
2126 In the previous section, we described the use of the @code{Source_File_Name}
2127 pragma to allow arbitrary names to be assigned to individual source files.
2128 However, this approach requires one pragma for each file, and especially in
2129 large systems can result in very long @file{gnat.adc} files, and also create
2130 a maintenance problem.
2132 GNAT also provides a facility for specifying systematic file naming schemes
2133 other than the standard default naming scheme previously described. An
2134 alternative scheme for naming is specified by the use of
2135 @code{Source_File_Name} pragmas having the following format:
2136 @cindex Source_File_Name pragma
2138 @smallexample @c ada
2139 pragma Source_File_Name (
2140 Spec_File_Name => FILE_NAME_PATTERN
2141 @r{[},Casing => CASING_SPEC@r{]}
2142 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2144 pragma Source_File_Name (
2145 Body_File_Name => FILE_NAME_PATTERN
2146 @r{[},Casing => CASING_SPEC@r{]}
2147 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2149 pragma Source_File_Name (
2150 Subunit_File_Name => FILE_NAME_PATTERN
2151 @r{[},Casing => CASING_SPEC@r{]}
2152 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154 FILE_NAME_PATTERN ::= STRING_LITERAL
2155 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2159 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2160 It contains a single asterisk character, and the unit name is substituted
2161 systematically for this asterisk. The optional parameter
2162 @code{Casing} indicates
2163 whether the unit name is to be all upper-case letters, all lower-case letters,
2164 or mixed-case. If no
2165 @code{Casing} parameter is used, then the default is all
2166 ^lower-case^upper-case^.
2168 The optional @code{Dot_Replacement} string is used to replace any periods
2169 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2170 argument is used then separating dots appear unchanged in the resulting
2172 Although the above syntax indicates that the
2173 @code{Casing} argument must appear
2174 before the @code{Dot_Replacement} argument, but it
2175 is also permissible to write these arguments in the opposite order.
2177 As indicated, it is possible to specify different naming schemes for
2178 bodies, specs, and subunits. Quite often the rule for subunits is the
2179 same as the rule for bodies, in which case, there is no need to give
2180 a separate @code{Subunit_File_Name} rule, and in this case the
2181 @code{Body_File_name} rule is used for subunits as well.
2183 The separate rule for subunits can also be used to implement the rather
2184 unusual case of a compilation environment (e.g.@: a single directory) which
2185 contains a subunit and a child unit with the same unit name. Although
2186 both units cannot appear in the same partition, the Ada Reference Manual
2187 allows (but does not require) the possibility of the two units coexisting
2188 in the same environment.
2190 The file name translation works in the following steps:
2195 If there is a specific @code{Source_File_Name} pragma for the given unit,
2196 then this is always used, and any general pattern rules are ignored.
2199 If there is a pattern type @code{Source_File_Name} pragma that applies to
2200 the unit, then the resulting file name will be used if the file exists. If
2201 more than one pattern matches, the latest one will be tried first, and the
2202 first attempt resulting in a reference to a file that exists will be used.
2205 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2206 for which the corresponding file exists, then the standard GNAT default
2207 naming rules are used.
2212 As an example of the use of this mechanism, consider a commonly used scheme
2213 in which file names are all lower case, with separating periods copied
2214 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2215 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2218 @smallexample @c ada
2219 pragma Source_File_Name
2220 (Spec_File_Name => "*.1.ada");
2221 pragma Source_File_Name
2222 (Body_File_Name => "*.2.ada");
2226 The default GNAT scheme is actually implemented by providing the following
2227 default pragmas internally:
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2232 pragma Source_File_Name
2233 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2237 Our final example implements a scheme typically used with one of the
2238 Ada 83 compilers, where the separator character for subunits was ``__''
2239 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2240 by adding @file{.ADA}, and subunits by
2241 adding @file{.SEP}. All file names were
2242 upper case. Child units were not present of course since this was an
2243 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2244 the same double underscore separator for child units.
2246 @smallexample @c ada
2247 pragma Source_File_Name
2248 (Spec_File_Name => "*_.ADA",
2249 Dot_Replacement => "__",
2250 Casing = Uppercase);
2251 pragma Source_File_Name
2252 (Body_File_Name => "*.ADA",
2253 Dot_Replacement => "__",
2254 Casing = Uppercase);
2255 pragma Source_File_Name
2256 (Subunit_File_Name => "*.SEP",
2257 Dot_Replacement => "__",
2258 Casing = Uppercase);
2261 @node Generating Object Files
2262 @section Generating Object Files
2265 An Ada program consists of a set of source files, and the first step in
2266 compiling the program is to generate the corresponding object files.
2267 These are generated by compiling a subset of these source files.
2268 The files you need to compile are the following:
2272 If a package spec has no body, compile the package spec to produce the
2273 object file for the package.
2276 If a package has both a spec and a body, compile the body to produce the
2277 object file for the package. The source file for the package spec need
2278 not be compiled in this case because there is only one object file, which
2279 contains the code for both the spec and body of the package.
2282 For a subprogram, compile the subprogram body to produce the object file
2283 for the subprogram. The spec, if one is present, is as usual in a
2284 separate file, and need not be compiled.
2288 In the case of subunits, only compile the parent unit. A single object
2289 file is generated for the entire subunit tree, which includes all the
2293 Compile child units independently of their parent units
2294 (though, of course, the spec of all the ancestor unit must be present in order
2295 to compile a child unit).
2299 Compile generic units in the same manner as any other units. The object
2300 files in this case are small dummy files that contain at most the
2301 flag used for elaboration checking. This is because GNAT always handles generic
2302 instantiation by means of macro expansion. However, it is still necessary to
2303 compile generic units, for dependency checking and elaboration purposes.
2307 The preceding rules describe the set of files that must be compiled to
2308 generate the object files for a program. Each object file has the same
2309 name as the corresponding source file, except that the extension is
2312 You may wish to compile other files for the purpose of checking their
2313 syntactic and semantic correctness. For example, in the case where a
2314 package has a separate spec and body, you would not normally compile the
2315 spec. However, it is convenient in practice to compile the spec to make
2316 sure it is error-free before compiling clients of this spec, because such
2317 compilations will fail if there is an error in the spec.
2319 GNAT provides an option for compiling such files purely for the
2320 purposes of checking correctness; such compilations are not required as
2321 part of the process of building a program. To compile a file in this
2322 checking mode, use the @option{-gnatc} switch.
2324 @node Source Dependencies
2325 @section Source Dependencies
2328 A given object file clearly depends on the source file which is compiled
2329 to produce it. Here we are using @dfn{depends} in the sense of a typical
2330 @code{make} utility; in other words, an object file depends on a source
2331 file if changes to the source file require the object file to be
2333 In addition to this basic dependency, a given object may depend on
2334 additional source files as follows:
2338 If a file being compiled @code{with}'s a unit @var{X}, the object file
2339 depends on the file containing the spec of unit @var{X}. This includes
2340 files that are @code{with}'ed implicitly either because they are parents
2341 of @code{with}'ed child units or they are run-time units required by the
2342 language constructs used in a particular unit.
2345 If a file being compiled instantiates a library level generic unit, the
2346 object file depends on both the spec and body files for this generic
2350 If a file being compiled instantiates a generic unit defined within a
2351 package, the object file depends on the body file for the package as
2352 well as the spec file.
2356 @cindex @option{-gnatn} switch
2357 If a file being compiled contains a call to a subprogram for which
2358 pragma @code{Inline} applies and inlining is activated with the
2359 @option{-gnatn} switch, the object file depends on the file containing the
2360 body of this subprogram as well as on the file containing the spec. Note
2361 that for inlining to actually occur as a result of the use of this switch,
2362 it is necessary to compile in optimizing mode.
2364 @cindex @option{-gnatN} switch
2365 The use of @option{-gnatN} activates inlining optimization
2366 that is performed by the front end of the compiler. This inlining does
2367 not require that the code generation be optimized. Like @option{-gnatn},
2368 the use of this switch generates additional dependencies.
2370 When using a gcc-based back end (in practice this means using any version
2371 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2372 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2373 Historically front end inlining was more extensive than the gcc back end
2374 inlining, but that is no longer the case.
2377 If an object file @file{O} depends on the proper body of a subunit through
2378 inlining or instantiation, it depends on the parent unit of the subunit.
2379 This means that any modification of the parent unit or one of its subunits
2380 affects the compilation of @file{O}.
2383 The object file for a parent unit depends on all its subunit body files.
2386 The previous two rules meant that for purposes of computing dependencies and
2387 recompilation, a body and all its subunits are treated as an indivisible whole.
2390 These rules are applied transitively: if unit @code{A} @code{with}'s
2391 unit @code{B}, whose elaboration calls an inlined procedure in package
2392 @code{C}, the object file for unit @code{A} will depend on the body of
2393 @code{C}, in file @file{c.adb}.
2395 The set of dependent files described by these rules includes all the
2396 files on which the unit is semantically dependent, as dictated by the
2397 Ada language standard. However, it is a superset of what the
2398 standard describes, because it includes generic, inline, and subunit
2401 An object file must be recreated by recompiling the corresponding source
2402 file if any of the source files on which it depends are modified. For
2403 example, if the @code{make} utility is used to control compilation,
2404 the rule for an Ada object file must mention all the source files on
2405 which the object file depends, according to the above definition.
2406 The determination of the necessary
2407 recompilations is done automatically when one uses @command{gnatmake}.
2410 @node The Ada Library Information Files
2411 @section The Ada Library Information Files
2412 @cindex Ada Library Information files
2413 @cindex @file{ALI} files
2416 Each compilation actually generates two output files. The first of these
2417 is the normal object file that has a @file{.o} extension. The second is a
2418 text file containing full dependency information. It has the same
2419 name as the source file, but an @file{.ali} extension.
2420 This file is known as the Ada Library Information (@file{ALI}) file.
2421 The following information is contained in the @file{ALI} file.
2425 Version information (indicates which version of GNAT was used to compile
2426 the unit(s) in question)
2429 Main program information (including priority and time slice settings,
2430 as well as the wide character encoding used during compilation).
2433 List of arguments used in the @command{gcc} command for the compilation
2436 Attributes of the unit, including configuration pragmas used, an indication
2437 of whether the compilation was successful, exception model used etc.
2440 A list of relevant restrictions applying to the unit (used for consistency)
2444 Categorization information (e.g.@: use of pragma @code{Pure}).
2447 Information on all @code{with}'ed units, including presence of
2448 @code{Elaborate} or @code{Elaborate_All} pragmas.
2451 Information from any @code{Linker_Options} pragmas used in the unit
2454 Information on the use of @code{Body_Version} or @code{Version}
2455 attributes in the unit.
2458 Dependency information. This is a list of files, together with
2459 time stamp and checksum information. These are files on which
2460 the unit depends in the sense that recompilation is required
2461 if any of these units are modified.
2464 Cross-reference data. Contains information on all entities referenced
2465 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2466 provide cross-reference information.
2471 For a full detailed description of the format of the @file{ALI} file,
2472 see the source of the body of unit @code{Lib.Writ}, contained in file
2473 @file{lib-writ.adb} in the GNAT compiler sources.
2475 @node Binding an Ada Program
2476 @section Binding an Ada Program
2479 When using languages such as C and C++, once the source files have been
2480 compiled the only remaining step in building an executable program
2481 is linking the object modules together. This means that it is possible to
2482 link an inconsistent version of a program, in which two units have
2483 included different versions of the same header.
2485 The rules of Ada do not permit such an inconsistent program to be built.
2486 For example, if two clients have different versions of the same package,
2487 it is illegal to build a program containing these two clients.
2488 These rules are enforced by the GNAT binder, which also determines an
2489 elaboration order consistent with the Ada rules.
2491 The GNAT binder is run after all the object files for a program have
2492 been created. It is given the name of the main program unit, and from
2493 this it determines the set of units required by the program, by reading the
2494 corresponding ALI files. It generates error messages if the program is
2495 inconsistent or if no valid order of elaboration exists.
2497 If no errors are detected, the binder produces a main program, in Ada by
2498 default, that contains calls to the elaboration procedures of those
2499 compilation unit that require them, followed by
2500 a call to the main program. This Ada program is compiled to generate the
2501 object file for the main program. The name of
2502 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2503 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2506 Finally, the linker is used to build the resulting executable program,
2507 using the object from the main program from the bind step as well as the
2508 object files for the Ada units of the program.
2510 @node Mixed Language Programming
2511 @section Mixed Language Programming
2512 @cindex Mixed Language Programming
2515 This section describes how to develop a mixed-language program,
2516 specifically one that comprises units in both Ada and C.
2519 * Interfacing to C::
2520 * Calling Conventions::
2523 @node Interfacing to C
2524 @subsection Interfacing to C
2526 Interfacing Ada with a foreign language such as C involves using
2527 compiler directives to import and/or export entity definitions in each
2528 language---using @code{extern} statements in C, for instance, and the
2529 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2530 A full treatment of these topics is provided in Appendix B, section 1
2531 of the Ada Reference Manual.
2533 There are two ways to build a program using GNAT that contains some Ada
2534 sources and some foreign language sources, depending on whether or not
2535 the main subprogram is written in Ada. Here is a source example with
2536 the main subprogram in Ada:
2542 void print_num (int num)
2544 printf ("num is %d.\n", num);
2550 /* num_from_Ada is declared in my_main.adb */
2551 extern int num_from_Ada;
2555 return num_from_Ada;
2559 @smallexample @c ada
2561 procedure My_Main is
2563 -- Declare then export an Integer entity called num_from_Ada
2564 My_Num : Integer := 10;
2565 pragma Export (C, My_Num, "num_from_Ada");
2567 -- Declare an Ada function spec for Get_Num, then use
2568 -- C function get_num for the implementation.
2569 function Get_Num return Integer;
2570 pragma Import (C, Get_Num, "get_num");
2572 -- Declare an Ada procedure spec for Print_Num, then use
2573 -- C function print_num for the implementation.
2574 procedure Print_Num (Num : Integer);
2575 pragma Import (C, Print_Num, "print_num");
2578 Print_Num (Get_Num);
2584 To build this example, first compile the foreign language files to
2585 generate object files:
2587 ^gcc -c file1.c^gcc -c FILE1.C^
2588 ^gcc -c file2.c^gcc -c FILE2.C^
2592 Then, compile the Ada units to produce a set of object files and ALI
2595 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2599 Run the Ada binder on the Ada main program:
2601 gnatbind my_main.ali
2605 Link the Ada main program, the Ada objects and the other language
2608 gnatlink my_main.ali file1.o file2.o
2612 The last three steps can be grouped in a single command:
2614 gnatmake my_main.adb -largs file1.o file2.o
2617 @cindex Binder output file
2619 If the main program is in a language other than Ada, then you may have
2620 more than one entry point into the Ada subsystem. You must use a special
2621 binder option to generate callable routines that initialize and
2622 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2623 Calls to the initialization and finalization routines must be inserted
2624 in the main program, or some other appropriate point in the code. The
2625 call to initialize the Ada units must occur before the first Ada
2626 subprogram is called, and the call to finalize the Ada units must occur
2627 after the last Ada subprogram returns. The binder will place the
2628 initialization and finalization subprograms into the
2629 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2630 sources. To illustrate, we have the following example:
2634 extern void adainit (void);
2635 extern void adafinal (void);
2636 extern int add (int, int);
2637 extern int sub (int, int);
2639 int main (int argc, char *argv[])
2645 /* Should print "21 + 7 = 28" */
2646 printf ("%d + %d = %d\n", a, b, add (a, b));
2647 /* Should print "21 - 7 = 14" */
2648 printf ("%d - %d = %d\n", a, b, sub (a, b));
2654 @smallexample @c ada
2657 function Add (A, B : Integer) return Integer;
2658 pragma Export (C, Add, "add");
2662 package body Unit1 is
2663 function Add (A, B : Integer) return Integer is
2671 function Sub (A, B : Integer) return Integer;
2672 pragma Export (C, Sub, "sub");
2676 package body Unit2 is
2677 function Sub (A, B : Integer) return Integer is
2686 The build procedure for this application is similar to the last
2687 example's. First, compile the foreign language files to generate object
2690 ^gcc -c main.c^gcc -c main.c^
2694 Next, compile the Ada units to produce a set of object files and ALI
2697 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2698 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2702 Run the Ada binder on every generated ALI file. Make sure to use the
2703 @option{-n} option to specify a foreign main program:
2705 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2709 Link the Ada main program, the Ada objects and the foreign language
2710 objects. You need only list the last ALI file here:
2712 gnatlink unit2.ali main.o -o exec_file
2715 This procedure yields a binary executable called @file{exec_file}.
2719 Depending on the circumstances (for example when your non-Ada main object
2720 does not provide symbol @code{main}), you may also need to instruct the
2721 GNAT linker not to include the standard startup objects by passing the
2722 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2724 @node Calling Conventions
2725 @subsection Calling Conventions
2726 @cindex Foreign Languages
2727 @cindex Calling Conventions
2728 GNAT follows standard calling sequence conventions and will thus interface
2729 to any other language that also follows these conventions. The following
2730 Convention identifiers are recognized by GNAT:
2733 @cindex Interfacing to Ada
2734 @cindex Other Ada compilers
2735 @cindex Convention Ada
2737 This indicates that the standard Ada calling sequence will be
2738 used and all Ada data items may be passed without any limitations in the
2739 case where GNAT is used to generate both the caller and callee. It is also
2740 possible to mix GNAT generated code and code generated by another Ada
2741 compiler. In this case, the data types should be restricted to simple
2742 cases, including primitive types. Whether complex data types can be passed
2743 depends on the situation. Probably it is safe to pass simple arrays, such
2744 as arrays of integers or floats. Records may or may not work, depending
2745 on whether both compilers lay them out identically. Complex structures
2746 involving variant records, access parameters, tasks, or protected types,
2747 are unlikely to be able to be passed.
2749 Note that in the case of GNAT running
2750 on a platform that supports HP Ada 83, a higher degree of compatibility
2751 can be guaranteed, and in particular records are layed out in an identical
2752 manner in the two compilers. Note also that if output from two different
2753 compilers is mixed, the program is responsible for dealing with elaboration
2754 issues. Probably the safest approach is to write the main program in the
2755 version of Ada other than GNAT, so that it takes care of its own elaboration
2756 requirements, and then call the GNAT-generated adainit procedure to ensure
2757 elaboration of the GNAT components. Consult the documentation of the other
2758 Ada compiler for further details on elaboration.
2760 However, it is not possible to mix the tasking run time of GNAT and
2761 HP Ada 83, All the tasking operations must either be entirely within
2762 GNAT compiled sections of the program, or entirely within HP Ada 83
2763 compiled sections of the program.
2765 @cindex Interfacing to Assembly
2766 @cindex Convention Assembler
2768 Specifies assembler as the convention. In practice this has the
2769 same effect as convention Ada (but is not equivalent in the sense of being
2770 considered the same convention).
2772 @cindex Convention Asm
2775 Equivalent to Assembler.
2777 @cindex Interfacing to COBOL
2778 @cindex Convention COBOL
2781 Data will be passed according to the conventions described
2782 in section B.4 of the Ada Reference Manual.
2785 @cindex Interfacing to C
2786 @cindex Convention C
2788 Data will be passed according to the conventions described
2789 in section B.3 of the Ada Reference Manual.
2791 A note on interfacing to a C ``varargs'' function:
2792 @findex C varargs function
2793 @cindex Interfacing to C varargs function
2794 @cindex varargs function interfaces
2798 In C, @code{varargs} allows a function to take a variable number of
2799 arguments. There is no direct equivalent in this to Ada. One
2800 approach that can be used is to create a C wrapper for each
2801 different profile and then interface to this C wrapper. For
2802 example, to print an @code{int} value using @code{printf},
2803 create a C function @code{printfi} that takes two arguments, a
2804 pointer to a string and an int, and calls @code{printf}.
2805 Then in the Ada program, use pragma @code{Import} to
2806 interface to @code{printfi}.
2809 It may work on some platforms to directly interface to
2810 a @code{varargs} function by providing a specific Ada profile
2811 for a particular call. However, this does not work on
2812 all platforms, since there is no guarantee that the
2813 calling sequence for a two argument normal C function
2814 is the same as for calling a @code{varargs} C function with
2815 the same two arguments.
2818 @cindex Convention Default
2823 @cindex Convention External
2830 @cindex Interfacing to C++
2831 @cindex Convention C++
2832 @item C_Plus_Plus (or CPP)
2833 This stands for C++. For most purposes this is identical to C.
2834 See the separate description of the specialized GNAT pragmas relating to
2835 C++ interfacing for further details.
2839 @cindex Interfacing to Fortran
2840 @cindex Convention Fortran
2842 Data will be passed according to the conventions described
2843 in section B.5 of the Ada Reference Manual.
2846 This applies to an intrinsic operation, as defined in the Ada
2847 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2848 this means that the body of the subprogram is provided by the compiler itself,
2849 usually by means of an efficient code sequence, and that the user does not
2850 supply an explicit body for it. In an application program, the pragma may
2851 be applied to the following sets of names:
2855 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2856 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2857 two formal parameters. The
2858 first one must be a signed integer type or a modular type with a binary
2859 modulus, and the second parameter must be of type Natural.
2860 The return type must be the same as the type of the first argument. The size
2861 of this type can only be 8, 16, 32, or 64.
2864 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2865 The corresponding operator declaration must have parameters and result type
2866 that have the same root numeric type (for example, all three are long_float
2867 types). This simplifies the definition of operations that use type checking
2868 to perform dimensional checks:
2870 @smallexample @c ada
2871 type Distance is new Long_Float;
2872 type Time is new Long_Float;
2873 type Velocity is new Long_Float;
2874 function "/" (D : Distance; T : Time)
2876 pragma Import (Intrinsic, "/");
2880 This common idiom is often programmed with a generic definition and an
2881 explicit body. The pragma makes it simpler to introduce such declarations.
2882 It incurs no overhead in compilation time or code size, because it is
2883 implemented as a single machine instruction.
2886 General subprogram entities, to bind an Ada subprogram declaration to
2887 a compiler builtin by name with back-ends where such interfaces are
2888 available. A typical example is the set of ``__builtin'' functions
2889 exposed by the GCC back-end, as in the following example:
2891 @smallexample @c ada
2892 function builtin_sqrt (F : Float) return Float;
2893 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2896 Most of the GCC builtins are accessible this way, and as for other
2897 import conventions (e.g. C), it is the user's responsibility to ensure
2898 that the Ada subprogram profile matches the underlying builtin
2906 @cindex Convention Stdcall
2908 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2909 and specifies that the @code{Stdcall} calling sequence will be used,
2910 as defined by the NT API. Nevertheless, to ease building
2911 cross-platform bindings this convention will be handled as a @code{C} calling
2912 convention on non-Windows platforms.
2915 @cindex Convention DLL
2917 This is equivalent to @code{Stdcall}.
2920 @cindex Convention Win32
2922 This is equivalent to @code{Stdcall}.
2926 @cindex Convention Stubbed
2928 This is a special convention that indicates that the compiler
2929 should provide a stub body that raises @code{Program_Error}.
2933 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2934 that can be used to parameterize conventions and allow additional synonyms
2935 to be specified. For example if you have legacy code in which the convention
2936 identifier Fortran77 was used for Fortran, you can use the configuration
2939 @smallexample @c ada
2940 pragma Convention_Identifier (Fortran77, Fortran);
2944 And from now on the identifier Fortran77 may be used as a convention
2945 identifier (for example in an @code{Import} pragma) with the same
2949 @node Building Mixed Ada & C++ Programs
2950 @section Building Mixed Ada and C++ Programs
2953 A programmer inexperienced with mixed-language development may find that
2954 building an application containing both Ada and C++ code can be a
2955 challenge. This section gives a few
2956 hints that should make this task easier. The first section addresses
2957 the differences between interfacing with C and interfacing with C++.
2959 looks into the delicate problem of linking the complete application from
2960 its Ada and C++ parts. The last section gives some hints on how the GNAT
2961 run-time library can be adapted in order to allow inter-language dispatching
2962 with a new C++ compiler.
2965 * Interfacing to C++::
2966 * Linking a Mixed C++ & Ada Program::
2967 * A Simple Example::
2968 * Interfacing with C++ constructors::
2969 * Interfacing with C++ at the Class Level::
2972 @node Interfacing to C++
2973 @subsection Interfacing to C++
2976 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2977 generating code that is compatible with the G++ Application Binary
2978 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2981 Interfacing can be done at 3 levels: simple data, subprograms, and
2982 classes. In the first two cases, GNAT offers a specific @code{Convention
2983 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2984 Usually, C++ mangles the names of subprograms. To generate proper mangled
2985 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2986 This problem can also be addressed manually in two ways:
2990 by modifying the C++ code in order to force a C convention using
2991 the @code{extern "C"} syntax.
2994 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2995 Link_Name argument of the pragma import.
2999 Interfacing at the class level can be achieved by using the GNAT specific
3000 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
3001 gnat_rm, GNAT Reference Manual}, for additional information.
3003 @node Linking a Mixed C++ & Ada Program
3004 @subsection Linking a Mixed C++ & Ada Program
3007 Usually the linker of the C++ development system must be used to link
3008 mixed applications because most C++ systems will resolve elaboration
3009 issues (such as calling constructors on global class instances)
3010 transparently during the link phase. GNAT has been adapted to ease the
3011 use of a foreign linker for the last phase. Three cases can be
3016 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3017 The C++ linker can simply be called by using the C++ specific driver
3020 Note that if the C++ code uses inline functions, you will need to
3021 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3022 order to provide an existing function implementation that the Ada code can
3026 $ g++ -c -fkeep-inline-functions file1.C
3027 $ g++ -c -fkeep-inline-functions file2.C
3028 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3032 Using GNAT and G++ from two different GCC installations: If both
3033 compilers are on the @env{PATH}, the previous method may be used. It is
3034 important to note that environment variables such as
3035 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3036 @env{GCC_ROOT} will affect both compilers
3037 at the same time and may make one of the two compilers operate
3038 improperly if set during invocation of the wrong compiler. It is also
3039 very important that the linker uses the proper @file{libgcc.a} GCC
3040 library -- that is, the one from the C++ compiler installation. The
3041 implicit link command as suggested in the @command{gnatmake} command
3042 from the former example can be replaced by an explicit link command with
3043 the full-verbosity option in order to verify which library is used:
3046 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3048 If there is a problem due to interfering environment variables, it can
3049 be worked around by using an intermediate script. The following example
3050 shows the proper script to use when GNAT has not been installed at its
3051 default location and g++ has been installed at its default location:
3059 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3063 Using a non-GNU C++ compiler: The commands previously described can be
3064 used to insure that the C++ linker is used. Nonetheless, you need to add
3065 a few more parameters to the link command line, depending on the exception
3068 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3069 to the libgcc libraries are required:
3074 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3075 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3078 Where CC is the name of the non-GNU C++ compiler.
3080 If the @code{zero cost} exception mechanism is used, and the platform
3081 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3082 paths to more objects are required:
3087 CC `gcc -print-file-name=crtbegin.o` $* \
3088 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3089 `gcc -print-file-name=crtend.o`
3090 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3093 If the @code{zero cost} exception mechanism is used, and the platform
3094 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3095 Tru64 or AIX), the simple approach described above will not work and
3096 a pre-linking phase using GNAT will be necessary.
3100 Another alternative is to use the @command{gprbuild} multi-language builder
3101 which has a large knowledge base and knows how to link Ada and C++ code
3102 together automatically in most cases.
3104 @node A Simple Example
3105 @subsection A Simple Example
3107 The following example, provided as part of the GNAT examples, shows how
3108 to achieve procedural interfacing between Ada and C++ in both
3109 directions. The C++ class A has two methods. The first method is exported
3110 to Ada by the means of an extern C wrapper function. The second method
3111 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3112 a limited record with a layout comparable to the C++ class. The Ada
3113 subprogram, in turn, calls the C++ method. So, starting from the C++
3114 main program, the process passes back and forth between the two
3118 Here are the compilation commands:
3120 $ gnatmake -c simple_cpp_interface
3123 $ gnatbind -n simple_cpp_interface
3124 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3125 -lstdc++ ex7.o cpp_main.o
3129 Here are the corresponding sources:
3137 void adainit (void);
3138 void adafinal (void);
3139 void method1 (A *t);
3161 class A : public Origin @{
3163 void method1 (void);
3164 void method2 (int v);
3174 extern "C" @{ void ada_method2 (A *t, int v);@}
3176 void A::method1 (void)
3179 printf ("in A::method1, a_value = %d \n",a_value);
3183 void A::method2 (int v)
3185 ada_method2 (this, v);
3186 printf ("in A::method2, a_value = %d \n",a_value);
3193 printf ("in A::A, a_value = %d \n",a_value);
3197 @smallexample @c ada
3199 package body Simple_Cpp_Interface is
3201 procedure Ada_Method2 (This : in out A; V : Integer) is
3207 end Simple_Cpp_Interface;
3210 package Simple_Cpp_Interface is
3213 Vptr : System.Address;
3217 pragma Convention (C, A);
3219 procedure Method1 (This : in out A);
3220 pragma Import (C, Method1);
3222 procedure Ada_Method2 (This : in out A; V : Integer);
3223 pragma Export (C, Ada_Method2);
3225 end Simple_Cpp_Interface;
3228 @node Interfacing with C++ constructors
3229 @subsection Interfacing with C++ constructors
3232 In order to interface with C++ constructors GNAT provides the
3233 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3234 gnat_rm, GNAT Reference Manual}, for additional information).
3235 In this section we present some common uses of C++ constructors
3236 in mixed-languages programs in GNAT.
3238 Let us assume that we need to interface with the following
3246 @b{virtual} int Get_Value ();
3247 Root(); // Default constructor
3248 Root(int v); // 1st non-default constructor
3249 Root(int v, int w); // 2nd non-default constructor
3253 For this purpose we can write the following package spec (further
3254 information on how to build this spec is available in
3255 @ref{Interfacing with C++ at the Class Level} and
3256 @ref{Generating Ada Bindings for C and C++ headers}).
3258 @smallexample @c ada
3259 with Interfaces.C; use Interfaces.C;
3261 type Root is tagged limited record
3265 pragma Import (CPP, Root);
3267 function Get_Value (Obj : Root) return int;
3268 pragma Import (CPP, Get_Value);
3270 function Constructor return Root;
3271 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3273 function Constructor (v : Integer) return Root;
3274 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3276 function Constructor (v, w : Integer) return Root;
3277 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3281 On the Ada side the constructor is represented by a function (whose
3282 name is arbitrary) that returns the classwide type corresponding to
3283 the imported C++ class. Although the constructor is described as a
3284 function, it is typically a procedure with an extra implicit argument
3285 (the object being initialized) at the implementation level. GNAT
3286 issues the appropriate call, whatever it is, to get the object
3287 properly initialized.
3289 Constructors can only appear in the following contexts:
3293 On the right side of an initialization of an object of type @var{T}.
3295 On the right side of an initialization of a record component of type @var{T}.
3297 In an Ada 2005 limited aggregate.
3299 In an Ada 2005 nested limited aggregate.
3301 In an Ada 2005 limited aggregate that initializes an object built in
3302 place by an extended return statement.
3306 In a declaration of an object whose type is a class imported from C++,
3307 either the default C++ constructor is implicitly called by GNAT, or
3308 else the required C++ constructor must be explicitly called in the
3309 expression that initializes the object. For example:
3311 @smallexample @c ada
3313 Obj2 : Root := Constructor;
3314 Obj3 : Root := Constructor (v => 10);
3315 Obj4 : Root := Constructor (30, 40);
3318 The first two declarations are equivalent: in both cases the default C++
3319 constructor is invoked (in the former case the call to the constructor is
3320 implicit, and in the latter case the call is explicit in the object
3321 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3322 that takes an integer argument, and @code{Obj4} is initialized by the
3323 non-default C++ constructor that takes two integers.
3325 Let us derive the imported C++ class in the Ada side. For example:
3327 @smallexample @c ada
3328 type DT is new Root with record
3329 C_Value : Natural := 2009;
3333 In this case the components DT inherited from the C++ side must be
3334 initialized by a C++ constructor, and the additional Ada components
3335 of type DT are initialized by GNAT. The initialization of such an
3336 object is done either by default, or by means of a function returning
3337 an aggregate of type DT, or by means of an extension aggregate.
3339 @smallexample @c ada
3341 Obj6 : DT := Function_Returning_DT (50);
3342 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3345 The declaration of @code{Obj5} invokes the default constructors: the
3346 C++ default constructor of the parent type takes care of the initialization
3347 of the components inherited from Root, and GNAT takes care of the default
3348 initialization of the additional Ada components of type DT (that is,
3349 @code{C_Value} is initialized to value 2009). The order of invocation of
3350 the constructors is consistent with the order of elaboration required by
3351 Ada and C++. That is, the constructor of the parent type is always called
3352 before the constructor of the derived type.
3354 Let us now consider a record that has components whose type is imported
3355 from C++. For example:
3357 @smallexample @c ada
3358 type Rec1 is limited record
3359 Data1 : Root := Constructor (10);
3360 Value : Natural := 1000;
3363 type Rec2 (D : Integer := 20) is limited record
3365 Data2 : Root := Constructor (D, 30);
3369 The initialization of an object of type @code{Rec2} will call the
3370 non-default C++ constructors specified for the imported components.
3373 @smallexample @c ada
3377 Using Ada 2005 we can use limited aggregates to initialize an object
3378 invoking C++ constructors that differ from those specified in the type
3379 declarations. For example:
3381 @smallexample @c ada
3382 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3387 The above declaration uses an Ada 2005 limited aggregate to
3388 initialize @code{Obj9}, and the C++ constructor that has two integer
3389 arguments is invoked to initialize the @code{Data1} component instead
3390 of the constructor specified in the declaration of type @code{Rec1}. In
3391 Ada 2005 the box in the aggregate indicates that unspecified components
3392 are initialized using the expression (if any) available in the component
3393 declaration. That is, in this case discriminant @code{D} is initialized
3394 to value @code{20}, @code{Value} is initialized to value 1000, and the
3395 non-default C++ constructor that handles two integers takes care of
3396 initializing component @code{Data2} with values @code{20,30}.
3398 In Ada 2005 we can use the extended return statement to build the Ada
3399 equivalent to C++ non-default constructors. For example:
3401 @smallexample @c ada
3402 function Constructor (V : Integer) return Rec2 is
3404 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3407 -- Further actions required for construction of
3408 -- objects of type Rec2
3414 In this example the extended return statement construct is used to
3415 build in place the returned object whose components are initialized
3416 by means of a limited aggregate. Any further action associated with
3417 the constructor can be placed inside the construct.
3419 @node Interfacing with C++ at the Class Level
3420 @subsection Interfacing with C++ at the Class Level
3422 In this section we demonstrate the GNAT features for interfacing with
3423 C++ by means of an example making use of Ada 2005 abstract interface
3424 types. This example consists of a classification of animals; classes
3425 have been used to model our main classification of animals, and
3426 interfaces provide support for the management of secondary
3427 classifications. We first demonstrate a case in which the types and
3428 constructors are defined on the C++ side and imported from the Ada
3429 side, and latter the reverse case.
3431 The root of our derivation will be the @code{Animal} class, with a
3432 single private attribute (the @code{Age} of the animal) and two public
3433 primitives to set and get the value of this attribute.
3438 @b{virtual} void Set_Age (int New_Age);
3439 @b{virtual} int Age ();
3445 Abstract interface types are defined in C++ by means of classes with pure
3446 virtual functions and no data members. In our example we will use two
3447 interfaces that provide support for the common management of @code{Carnivore}
3448 and @code{Domestic} animals:
3451 @b{class} Carnivore @{
3453 @b{virtual} int Number_Of_Teeth () = 0;
3456 @b{class} Domestic @{
3458 @b{virtual void} Set_Owner (char* Name) = 0;
3462 Using these declarations, we can now say that a @code{Dog} is an animal that is
3463 both Carnivore and Domestic, that is:
3466 @b{class} Dog : Animal, Carnivore, Domestic @{
3468 @b{virtual} int Number_Of_Teeth ();
3469 @b{virtual} void Set_Owner (char* Name);
3471 Dog(); // Constructor
3478 In the following examples we will assume that the previous declarations are
3479 located in a file named @code{animals.h}. The following package demonstrates
3480 how to import these C++ declarations from the Ada side:
3482 @smallexample @c ada
3483 with Interfaces.C.Strings; use Interfaces.C.Strings;
3485 type Carnivore is interface;
3486 pragma Convention (C_Plus_Plus, Carnivore);
3487 function Number_Of_Teeth (X : Carnivore)
3488 return Natural is abstract;
3490 type Domestic is interface;
3491 pragma Convention (C_Plus_Plus, Set_Owner);
3493 (X : in out Domestic;
3494 Name : Chars_Ptr) is abstract;
3496 type Animal is tagged record
3499 pragma Import (C_Plus_Plus, Animal);
3501 procedure Set_Age (X : in out Animal; Age : Integer);
3502 pragma Import (C_Plus_Plus, Set_Age);
3504 function Age (X : Animal) return Integer;
3505 pragma Import (C_Plus_Plus, Age);
3507 type Dog is new Animal and Carnivore and Domestic with record
3508 Tooth_Count : Natural;
3509 Owner : String (1 .. 30);
3511 pragma Import (C_Plus_Plus, Dog);
3513 function Number_Of_Teeth (A : Dog) return Integer;
3514 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3516 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3517 pragma Import (C_Plus_Plus, Set_Owner);
3519 function New_Dog return Dog;
3520 pragma CPP_Constructor (New_Dog);
3521 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3525 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3526 interfacing with these C++ classes is easy. The only requirement is that all
3527 the primitives and components must be declared exactly in the same order in
3530 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3531 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3532 the arguments to the called primitives will be the same as for C++. For the
3533 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3534 to indicate that they have been defined on the C++ side; this is required
3535 because the dispatch table associated with these tagged types will be built
3536 in the C++ side and therefore will not contain the predefined Ada primitives
3537 which Ada would otherwise expect.
3539 As the reader can see there is no need to indicate the C++ mangled names
3540 associated with each subprogram because it is assumed that all the calls to
3541 these primitives will be dispatching calls. The only exception is the
3542 constructor, which must be registered with the compiler by means of
3543 @code{pragma CPP_Constructor} and needs to provide its associated C++
3544 mangled name because the Ada compiler generates direct calls to it.
3546 With the above packages we can now declare objects of type Dog on the Ada side
3547 and dispatch calls to the corresponding subprograms on the C++ side. We can
3548 also extend the tagged type Dog with further fields and primitives, and
3549 override some of its C++ primitives on the Ada side. For example, here we have
3550 a type derivation defined on the Ada side that inherits all the dispatching
3551 primitives of the ancestor from the C++ side.
3554 @b{with} Animals; @b{use} Animals;
3555 @b{package} Vaccinated_Animals @b{is}
3556 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3557 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3558 @b{end} Vaccinated_Animals;
3561 It is important to note that, because of the ABI compatibility, the programmer
3562 does not need to add any further information to indicate either the object
3563 layout or the dispatch table entry associated with each dispatching operation.
3565 Now let us define all the types and constructors on the Ada side and export
3566 them to C++, using the same hierarchy of our previous example:
3568 @smallexample @c ada
3569 with Interfaces.C.Strings;
3570 use Interfaces.C.Strings;
3572 type Carnivore is interface;
3573 pragma Convention (C_Plus_Plus, Carnivore);
3574 function Number_Of_Teeth (X : Carnivore)
3575 return Natural is abstract;
3577 type Domestic is interface;
3578 pragma Convention (C_Plus_Plus, Set_Owner);
3580 (X : in out Domestic;
3581 Name : Chars_Ptr) is abstract;
3583 type Animal is tagged record
3586 pragma Convention (C_Plus_Plus, Animal);
3588 procedure Set_Age (X : in out Animal; Age : Integer);
3589 pragma Export (C_Plus_Plus, Set_Age);
3591 function Age (X : Animal) return Integer;
3592 pragma Export (C_Plus_Plus, Age);
3594 type Dog is new Animal and Carnivore and Domestic with record
3595 Tooth_Count : Natural;
3596 Owner : String (1 .. 30);
3598 pragma Convention (C_Plus_Plus, Dog);
3600 function Number_Of_Teeth (A : Dog) return Integer;
3601 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3603 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3604 pragma Export (C_Plus_Plus, Set_Owner);
3606 function New_Dog return Dog'Class;
3607 pragma Export (C_Plus_Plus, New_Dog);
3611 Compared with our previous example the only difference is the use of
3612 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3613 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3614 nothing else to be done; as explained above, the only requirement is that all
3615 the primitives and components are declared in exactly the same order.
3617 For completeness, let us see a brief C++ main program that uses the
3618 declarations available in @code{animals.h} (presented in our first example) to
3619 import and use the declarations from the Ada side, properly initializing and
3620 finalizing the Ada run-time system along the way:
3623 @b{#include} "animals.h"
3624 @b{#include} <iostream>
3625 @b{using namespace} std;
3627 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3628 void Check_Domestic (Domestic *obj) @{@dots{}@}
3629 void Check_Animal (Animal *obj) @{@dots{}@}
3630 void Check_Dog (Dog *obj) @{@dots{}@}
3633 void adainit (void);
3634 void adafinal (void);
3640 Dog *obj = new_dog(); // Ada constructor
3641 Check_Carnivore (obj); // Check secondary DT
3642 Check_Domestic (obj); // Check secondary DT
3643 Check_Animal (obj); // Check primary DT
3644 Check_Dog (obj); // Check primary DT
3649 adainit (); test(); adafinal ();
3654 @node Comparison between GNAT and C/C++ Compilation Models
3655 @section Comparison between GNAT and C/C++ Compilation Models
3658 The GNAT model of compilation is close to the C and C++ models. You can
3659 think of Ada specs as corresponding to header files in C. As in C, you
3660 don't need to compile specs; they are compiled when they are used. The
3661 Ada @code{with} is similar in effect to the @code{#include} of a C
3664 One notable difference is that, in Ada, you may compile specs separately
3665 to check them for semantic and syntactic accuracy. This is not always
3666 possible with C headers because they are fragments of programs that have
3667 less specific syntactic or semantic rules.
3669 The other major difference is the requirement for running the binder,
3670 which performs two important functions. First, it checks for
3671 consistency. In C or C++, the only defense against assembling
3672 inconsistent programs lies outside the compiler, in a makefile, for
3673 example. The binder satisfies the Ada requirement that it be impossible
3674 to construct an inconsistent program when the compiler is used in normal
3677 @cindex Elaboration order control
3678 The other important function of the binder is to deal with elaboration
3679 issues. There are also elaboration issues in C++ that are handled
3680 automatically. This automatic handling has the advantage of being
3681 simpler to use, but the C++ programmer has no control over elaboration.
3682 Where @code{gnatbind} might complain there was no valid order of
3683 elaboration, a C++ compiler would simply construct a program that
3684 malfunctioned at run time.
3687 @node Comparison between GNAT and Conventional Ada Library Models
3688 @section Comparison between GNAT and Conventional Ada Library Models
3691 This section is intended for Ada programmers who have
3692 used an Ada compiler implementing the traditional Ada library
3693 model, as described in the Ada Reference Manual.
3695 @cindex GNAT library
3696 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3697 source files themselves acts as the library. Compiling Ada programs does
3698 not generate any centralized information, but rather an object file and
3699 a ALI file, which are of interest only to the binder and linker.
3700 In a traditional system, the compiler reads information not only from
3701 the source file being compiled, but also from the centralized library.
3702 This means that the effect of a compilation depends on what has been
3703 previously compiled. In particular:
3707 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3708 to the version of the unit most recently compiled into the library.
3711 Inlining is effective only if the necessary body has already been
3712 compiled into the library.
3715 Compiling a unit may obsolete other units in the library.
3719 In GNAT, compiling one unit never affects the compilation of any other
3720 units because the compiler reads only source files. Only changes to source
3721 files can affect the results of a compilation. In particular:
3725 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3726 to the source version of the unit that is currently accessible to the
3731 Inlining requires the appropriate source files for the package or
3732 subprogram bodies to be available to the compiler. Inlining is always
3733 effective, independent of the order in which units are complied.
3736 Compiling a unit never affects any other compilations. The editing of
3737 sources may cause previous compilations to be out of date if they
3738 depended on the source file being modified.
3742 The most important result of these differences is that order of compilation
3743 is never significant in GNAT. There is no situation in which one is
3744 required to do one compilation before another. What shows up as order of
3745 compilation requirements in the traditional Ada library becomes, in
3746 GNAT, simple source dependencies; in other words, there is only a set
3747 of rules saying what source files must be present when a file is
3751 @node Placement of temporary files
3752 @section Placement of temporary files
3753 @cindex Temporary files (user control over placement)
3756 GNAT creates temporary files in the directory designated by the environment
3757 variable @env{TMPDIR}.
3758 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3759 for detailed information on how environment variables are resolved.
3760 For most users the easiest way to make use of this feature is to simply
3761 define @env{TMPDIR} as a job level logical name).
3762 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3763 for compiler temporary files, then you can include something like the
3764 following command in your @file{LOGIN.COM} file:
3767 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3771 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3772 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3773 designated by @env{TEMP}.
3774 If none of these environment variables are defined then GNAT uses the
3775 directory designated by the logical name @code{SYS$SCRATCH:}
3776 (by default the user's home directory). If all else fails
3777 GNAT uses the current directory for temporary files.
3780 @c *************************
3781 @node Compiling Using gcc
3782 @chapter Compiling Using @command{gcc}
3785 This chapter discusses how to compile Ada programs using the @command{gcc}
3786 command. It also describes the set of switches
3787 that can be used to control the behavior of the compiler.
3789 * Compiling Programs::
3790 * Switches for gcc::
3791 * Search Paths and the Run-Time Library (RTL)::
3792 * Order of Compilation Issues::
3796 @node Compiling Programs
3797 @section Compiling Programs
3800 The first step in creating an executable program is to compile the units
3801 of the program using the @command{gcc} command. You must compile the
3806 the body file (@file{.adb}) for a library level subprogram or generic
3810 the spec file (@file{.ads}) for a library level package or generic
3811 package that has no body
3814 the body file (@file{.adb}) for a library level package
3815 or generic package that has a body
3820 You need @emph{not} compile the following files
3825 the spec of a library unit which has a body
3832 because they are compiled as part of compiling related units. GNAT
3834 when the corresponding body is compiled, and subunits when the parent is
3837 @cindex cannot generate code
3838 If you attempt to compile any of these files, you will get one of the
3839 following error messages (where @var{fff} is the name of the file you
3843 cannot generate code for file @var{fff} (package spec)
3844 to check package spec, use -gnatc
3846 cannot generate code for file @var{fff} (missing subunits)
3847 to check parent unit, use -gnatc
3849 cannot generate code for file @var{fff} (subprogram spec)
3850 to check subprogram spec, use -gnatc
3852 cannot generate code for file @var{fff} (subunit)
3853 to check subunit, use -gnatc
3857 As indicated by the above error messages, if you want to submit
3858 one of these files to the compiler to check for correct semantics
3859 without generating code, then use the @option{-gnatc} switch.
3861 The basic command for compiling a file containing an Ada unit is
3864 @c $ gcc -c @ovar{switches} @file{file name}
3865 @c Expanding @ovar macro inline (explanation in macro def comments)
3866 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3870 where @var{file name} is the name of the Ada file (usually
3872 @file{.ads} for a spec or @file{.adb} for a body).
3875 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3877 The result of a successful compilation is an object file, which has the
3878 same name as the source file but an extension of @file{.o} and an Ada
3879 Library Information (ALI) file, which also has the same name as the
3880 source file, but with @file{.ali} as the extension. GNAT creates these
3881 two output files in the current directory, but you may specify a source
3882 file in any directory using an absolute or relative path specification
3883 containing the directory information.
3886 @command{gcc} is actually a driver program that looks at the extensions of
3887 the file arguments and loads the appropriate compiler. For example, the
3888 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3889 These programs are in directories known to the driver program (in some
3890 configurations via environment variables you set), but need not be in
3891 your path. The @command{gcc} driver also calls the assembler and any other
3892 utilities needed to complete the generation of the required object
3895 It is possible to supply several file names on the same @command{gcc}
3896 command. This causes @command{gcc} to call the appropriate compiler for
3897 each file. For example, the following command lists three separate
3898 files to be compiled:
3901 $ gcc -c x.adb y.adb z.c
3905 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3906 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3907 The compiler generates three object files @file{x.o}, @file{y.o} and
3908 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3909 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3912 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3915 @node Switches for gcc
3916 @section Switches for @command{gcc}
3919 The @command{gcc} command accepts switches that control the
3920 compilation process. These switches are fully described in this section.
3921 First we briefly list all the switches, in alphabetical order, then we
3922 describe the switches in more detail in functionally grouped sections.
3924 More switches exist for GCC than those documented here, especially
3925 for specific targets. However, their use is not recommended as
3926 they may change code generation in ways that are incompatible with
3927 the Ada run-time library, or can cause inconsistencies between
3931 * Output and Error Message Control::
3932 * Warning Message Control::
3933 * Debugging and Assertion Control::
3934 * Validity Checking::
3937 * Using gcc for Syntax Checking::
3938 * Using gcc for Semantic Checking::
3939 * Compiling Different Versions of Ada::
3940 * Character Set Control::
3941 * File Naming Control::
3942 * Subprogram Inlining Control::
3943 * Auxiliary Output Control::
3944 * Debugging Control::
3945 * Exception Handling Control::
3946 * Units to Sources Mapping Files::
3947 * Integrated Preprocessing::
3948 * Code Generation Control::
3957 @cindex @option{-b} (@command{gcc})
3958 @item -b @var{target}
3959 Compile your program to run on @var{target}, which is the name of a
3960 system configuration. You must have a GNAT cross-compiler built if
3961 @var{target} is not the same as your host system.
3964 @cindex @option{-B} (@command{gcc})
3965 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3966 from @var{dir} instead of the default location. Only use this switch
3967 when multiple versions of the GNAT compiler are available.
3968 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3969 GNU Compiler Collection (GCC)}, for further details. You would normally
3970 use the @option{-b} or @option{-V} switch instead.
3973 @cindex @option{-c} (@command{gcc})
3974 Compile. Always use this switch when compiling Ada programs.
3976 Note: for some other languages when using @command{gcc}, notably in
3977 the case of C and C++, it is possible to use
3978 use @command{gcc} without a @option{-c} switch to
3979 compile and link in one step. In the case of GNAT, you
3980 cannot use this approach, because the binder must be run
3981 and @command{gcc} cannot be used to run the GNAT binder.
3985 @cindex @option{-fno-inline} (@command{gcc})
3986 Suppresses all inlining, even if other optimization or inlining
3987 switches are set. This includes suppression of inlining that
3988 results from the use of the pragma @code{Inline_Always}.
3989 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3990 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3991 effect if this switch is present.
3993 @item -fno-inline-functions
3994 @cindex @option{-fno-inline-functions} (@command{gcc})
3995 Suppresses automatic inlining of subprograms, which is enabled
3996 if @option{-O3} is used.
3998 @item -fno-inline-small-functions
3999 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4000 Suppresses automatic inlining of small subprograms, which is enabled
4001 if @option{-O2} is used.
4003 @item -fno-inline-functions-called-once
4004 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4005 Suppresses inlining of subprograms local to the unit and called once
4006 from within it, which is enabled if @option{-O1} is used.
4009 @cindex @option{-fno-ivopts} (@command{gcc})
4010 Suppresses high-level loop induction variable optimizations, which are
4011 enabled if @option{-O1} is used. These optimizations are generally
4012 profitable but, for some specific cases of loops with numerous uses
4013 of the iteration variable that follow a common pattern, they may end
4014 up destroying the regularity that could be exploited at a lower level
4015 and thus producing inferior code.
4017 @item -fno-strict-aliasing
4018 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4019 Causes the compiler to avoid assumptions regarding non-aliasing
4020 of objects of different types. See
4021 @ref{Optimization and Strict Aliasing} for details.
4024 @cindex @option{-fstack-check} (@command{gcc})
4025 Activates stack checking.
4026 See @ref{Stack Overflow Checking} for details.
4029 @cindex @option{-fstack-usage} (@command{gcc})
4030 Makes the compiler output stack usage information for the program, on a
4031 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4033 @item -fcallgraph-info@r{[}=su@r{]}
4034 @cindex @option{-fcallgraph-info} (@command{gcc})
4035 Makes the compiler output callgraph information for the program, on a
4036 per-file basis. The information is generated in the VCG format. It can
4037 be decorated with stack-usage per-node information.
4040 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4041 Generate debugging information. This information is stored in the object
4042 file and copied from there to the final executable file by the linker,
4043 where it can be read by the debugger. You must use the
4044 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4047 @cindex @option{-gnat83} (@command{gcc})
4048 Enforce Ada 83 restrictions.
4051 @cindex @option{-gnat95} (@command{gcc})
4052 Enforce Ada 95 restrictions.
4055 @cindex @option{-gnat05} (@command{gcc})
4056 Allow full Ada 2005 features.
4059 @cindex @option{-gnat2005} (@command{gcc})
4060 Allow full Ada 2005 features (same as @option{-gnat05})
4063 @cindex @option{-gnat12} (@command{gcc})
4066 @cindex @option{-gnat2012} (@command{gcc})
4067 Allow full Ada 2012 features (same as @option{-gnat12})
4070 @cindex @option{-gnata} (@command{gcc})
4071 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4072 activated. Note that these pragmas can also be controlled using the
4073 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4074 It also activates pragmas @code{Check}, @code{Precondition}, and
4075 @code{Postcondition}. Note that these pragmas can also be controlled
4076 using the configuration pragma @code{Check_Policy}.
4079 @cindex @option{-gnatA} (@command{gcc})
4080 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4084 @cindex @option{-gnatb} (@command{gcc})
4085 Generate brief messages to @file{stderr} even if verbose mode set.
4088 @cindex @option{-gnatB} (@command{gcc})
4089 Assume no invalid (bad) values except for 'Valid attribute use
4090 (@pxref{Validity Checking}).
4093 @cindex @option{-gnatc} (@command{gcc})
4094 Check syntax and semantics only (no code generation attempted).
4097 @cindex @option{-gnatC} (@command{gcc})
4098 Generate CodePeer information (no code generation attempted).
4099 This switch will generate an intermediate representation suitable for
4100 use by CodePeer (@file{.scil} files). This switch is not compatible with
4101 code generation (it will, among other things, disable some switches such
4102 as -gnatn, and enable others such as -gnata).
4105 @cindex @option{-gnatd} (@command{gcc})
4106 Specify debug options for the compiler. The string of characters after
4107 the @option{-gnatd} specify the specific debug options. The possible
4108 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4109 compiler source file @file{debug.adb} for details of the implemented
4110 debug options. Certain debug options are relevant to applications
4111 programmers, and these are documented at appropriate points in this
4116 @cindex @option{-gnatD[nn]} (@command{gcc})
4119 @item /XDEBUG /LXDEBUG=nnn
4121 Create expanded source files for source level debugging. This switch
4122 also suppress generation of cross-reference information
4123 (see @option{-gnatx}).
4125 @item -gnatec=@var{path}
4126 @cindex @option{-gnatec} (@command{gcc})
4127 Specify a configuration pragma file
4129 (the equal sign is optional)
4131 (@pxref{The Configuration Pragmas Files}).
4133 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4134 @cindex @option{-gnateD} (@command{gcc})
4135 Defines a symbol, associated with @var{value}, for preprocessing.
4136 (@pxref{Integrated Preprocessing}).
4139 @cindex @option{-gnateE} (@command{gcc})
4140 Generate extra information in exception messages. In particular, display
4141 extra column information and the value and range associated with index and
4142 range check failures, and extra column information for access checks.
4143 In cases where the compiler is able to determine at compile time that
4144 a check will fail, it gives a warning, and the extra information is not
4145 produced at run time.
4148 @cindex @option{-gnatef} (@command{gcc})
4149 Display full source path name in brief error messages.
4152 @cindex @option{-gnateG} (@command{gcc})
4153 Save result of preprocessing in a text file.
4155 @item ^-gnateI^/MULTI_UNIT_INDEX=^@var{nnn}
4156 @cindex @option{-gnateI} (@command{gcc})
4157 Indicates that the source is a multi-unit source and that the index of the
4158 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4159 to be a valid index in the multi-unit source.
4161 @item -gnatem=@var{path}
4162 @cindex @option{-gnatem} (@command{gcc})
4163 Specify a mapping file
4165 (the equal sign is optional)
4167 (@pxref{Units to Sources Mapping Files}).
4169 @item -gnatep=@var{file}
4170 @cindex @option{-gnatep} (@command{gcc})
4171 Specify a preprocessing data file
4173 (the equal sign is optional)
4175 (@pxref{Integrated Preprocessing}).
4178 @cindex @option{-gnateP} (@command{gcc})
4179 Turn categorization dependency errors into warnings.
4180 Ada requires that units that WITH one another have compatible categories, for
4181 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4182 these errors become warnings (which can be ignored, or suppressed in the usual
4183 manner). This can be useful in some specialized circumstances such as the
4184 temporary use of special test software.
4186 @cindex @option{-gnateS} (@command{gcc})
4187 Generate SCO (Source Coverage Obligation) information in the ALI
4188 file. This information is used by advanced coverage tools. See
4189 unit @file{SCOs} in the compiler sources for details in files
4190 @file{scos.ads} and @file{scos.adb}.
4193 @cindex @option{-gnatE} (@command{gcc})
4194 Full dynamic elaboration checks.
4197 @cindex @option{-gnatf} (@command{gcc})
4198 Full errors. Multiple errors per line, all undefined references, do not
4199 attempt to suppress cascaded errors.
4202 @cindex @option{-gnatF} (@command{gcc})
4203 Externals names are folded to all uppercase.
4205 @item ^-gnatg^/GNAT_INTERNAL^
4206 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4207 Internal GNAT implementation mode. This should not be used for
4208 applications programs, it is intended only for use by the compiler
4209 and its run-time library. For documentation, see the GNAT sources.
4210 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4211 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4212 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4213 so that all standard warnings and all standard style options are turned on.
4214 All warnings and style messages are treated as errors.
4218 @cindex @option{-gnatG[nn]} (@command{gcc})
4221 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4223 List generated expanded code in source form.
4225 @item ^-gnath^/HELP^
4226 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4227 Output usage information. The output is written to @file{stdout}.
4229 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4230 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4231 Identifier character set
4233 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4235 For details of the possible selections for @var{c},
4236 see @ref{Character Set Control}.
4238 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4239 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4240 Ignore representation clauses. When this switch is used,
4241 representation clauses are treated as comments. This is useful
4242 when initially porting code where you want to ignore rep clause
4243 problems, and also for compiling foreign code (particularly
4244 for use with ASIS). The representation clauses that are ignored
4245 are: enumeration_representation_clause, record_representation_clause,
4246 and attribute_definition_clause for the following attributes:
4247 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4248 Object_Size, Size, Small, Stream_Size, and Value_Size.
4249 Note that this option should be used only for compiling -- the
4250 code is likely to malfunction at run time.
4253 @cindex @option{-gnatjnn} (@command{gcc})
4254 Reformat error messages to fit on nn character lines
4256 @item -gnatk=@var{n}
4257 @cindex @option{-gnatk} (@command{gcc})
4258 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4261 @cindex @option{-gnatl} (@command{gcc})
4262 Output full source listing with embedded error messages.
4265 @cindex @option{-gnatL} (@command{gcc})
4266 Used in conjunction with -gnatG or -gnatD to intersperse original
4267 source lines (as comment lines with line numbers) in the expanded
4270 @item -gnatm=@var{n}
4271 @cindex @option{-gnatm} (@command{gcc})
4272 Limit number of detected error or warning messages to @var{n}
4273 where @var{n} is in the range 1..999999. The default setting if
4274 no switch is given is 9999. If the number of warnings reaches this
4275 limit, then a message is output and further warnings are suppressed,
4276 but the compilation is continued. If the number of error messages
4277 reaches this limit, then a message is output and the compilation
4278 is abandoned. The equal sign here is optional. A value of zero
4279 means that no limit applies.
4282 @cindex @option{-gnatn} (@command{gcc})
4283 Activate inlining for subprograms for which
4284 pragma @code{Inline} is specified. This inlining is performed
4285 by the GCC back-end.
4288 @cindex @option{-gnatN} (@command{gcc})
4289 Activate front end inlining for subprograms for which
4290 pragma @code{Inline} is specified. This inlining is performed
4291 by the front end and will be visible in the
4292 @option{-gnatG} output.
4294 When using a gcc-based back end (in practice this means using any version
4295 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4296 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4297 Historically front end inlining was more extensive than the gcc back end
4298 inlining, but that is no longer the case.
4301 @cindex @option{-gnato} (@command{gcc})
4302 Enable numeric overflow checking (which is not normally enabled by
4303 default). Note that division by zero is a separate check that is not
4304 controlled by this switch (division by zero checking is on by default).
4307 @cindex @option{-gnatp} (@command{gcc})
4308 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4309 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4312 @cindex @option{-gnat-p} (@command{gcc})
4313 Cancel effect of previous @option{-gnatp} switch.
4316 @cindex @option{-gnatP} (@command{gcc})
4317 Enable polling. This is required on some systems (notably Windows NT) to
4318 obtain asynchronous abort and asynchronous transfer of control capability.
4319 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4323 @cindex @option{-gnatq} (@command{gcc})
4324 Don't quit. Try semantics, even if parse errors.
4327 @cindex @option{-gnatQ} (@command{gcc})
4328 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4331 @cindex @option{-gnatr} (@command{gcc})
4332 Treat pragma Restrictions as Restriction_Warnings.
4334 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4335 @cindex @option{-gnatR} (@command{gcc})
4336 Output representation information for declared types and objects.
4339 @cindex @option{-gnats} (@command{gcc})
4343 @cindex @option{-gnatS} (@command{gcc})
4344 Print package Standard.
4347 @cindex @option{-gnatt} (@command{gcc})
4348 Generate tree output file.
4350 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4351 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4352 All compiler tables start at @var{nnn} times usual starting size.
4355 @cindex @option{-gnatu} (@command{gcc})
4356 List units for this compilation.
4359 @cindex @option{-gnatU} (@command{gcc})
4360 Tag all error messages with the unique string ``error:''
4363 @cindex @option{-gnatv} (@command{gcc})
4364 Verbose mode. Full error output with source lines to @file{stdout}.
4367 @cindex @option{-gnatV} (@command{gcc})
4368 Control level of validity checking (@pxref{Validity Checking}).
4370 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4371 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4373 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4374 the exact warnings that
4375 are enabled or disabled (@pxref{Warning Message Control}).
4377 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4378 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4379 Wide character encoding method
4381 (@var{e}=n/h/u/s/e/8).
4384 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4388 @cindex @option{-gnatx} (@command{gcc})
4389 Suppress generation of cross-reference information.
4392 @cindex @option{-gnatX} (@command{gcc})
4393 Enable GNAT implementation extensions and latest Ada version.
4395 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4396 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4397 Enable built-in style checks (@pxref{Style Checking}).
4399 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4400 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4401 Distribution stub generation and compilation
4403 (@var{m}=r/c for receiver/caller stubs).
4406 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4407 to be generated and compiled).
4410 @item ^-I^/SEARCH=^@var{dir}
4411 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4413 Direct GNAT to search the @var{dir} directory for source files needed by
4414 the current compilation
4415 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4417 @item ^-I-^/NOCURRENT_DIRECTORY^
4418 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4420 Except for the source file named in the command line, do not look for source
4421 files in the directory containing the source file named in the command line
4422 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4426 @cindex @option{-mbig-switch} (@command{gcc})
4427 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4428 This standard gcc switch causes the compiler to use larger offsets in its
4429 jump table representation for @code{case} statements.
4430 This may result in less efficient code, but is sometimes necessary
4431 (for example on HP-UX targets)
4432 @cindex HP-UX and @option{-mbig-switch} option
4433 in order to compile large and/or nested @code{case} statements.
4436 @cindex @option{-o} (@command{gcc})
4437 This switch is used in @command{gcc} to redirect the generated object file
4438 and its associated ALI file. Beware of this switch with GNAT, because it may
4439 cause the object file and ALI file to have different names which in turn
4440 may confuse the binder and the linker.
4444 @cindex @option{-nostdinc} (@command{gcc})
4445 Inhibit the search of the default location for the GNAT Run Time
4446 Library (RTL) source files.
4449 @cindex @option{-nostdlib} (@command{gcc})
4450 Inhibit the search of the default location for the GNAT Run Time
4451 Library (RTL) ALI files.
4455 @c Expanding @ovar macro inline (explanation in macro def comments)
4456 @item -O@r{[}@var{n}@r{]}
4457 @cindex @option{-O} (@command{gcc})
4458 @var{n} controls the optimization level.
4462 No optimization, the default setting if no @option{-O} appears
4465 Normal optimization, the default if you specify @option{-O} without
4466 an operand. A good compromise between code quality and compilation
4470 Extensive optimization, may improve execution time, possibly at the cost of
4471 substantially increased compilation time.
4474 Same as @option{-O2}, and also includes inline expansion for small subprograms
4478 Optimize space usage
4482 See also @ref{Optimization Levels}.
4487 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4488 Equivalent to @option{/OPTIMIZE=NONE}.
4489 This is the default behavior in the absence of an @option{/OPTIMIZE}
4492 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4493 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4494 Selects the level of optimization for your program. The supported
4495 keywords are as follows:
4498 Perform most optimizations, including those that
4500 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4501 without keyword options.
4504 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4507 Perform some optimizations, but omit ones that are costly.
4510 Same as @code{SOME}.
4513 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4514 automatic inlining of small subprograms within a unit
4517 Try to unroll loops. This keyword may be specified together with
4518 any keyword above other than @code{NONE}. Loop unrolling
4519 usually, but not always, improves the performance of programs.
4522 Optimize space usage
4526 See also @ref{Optimization Levels}.
4530 @item -pass-exit-codes
4531 @cindex @option{-pass-exit-codes} (@command{gcc})
4532 Catch exit codes from the compiler and use the most meaningful as
4536 @item --RTS=@var{rts-path}
4537 @cindex @option{--RTS} (@command{gcc})
4538 Specifies the default location of the runtime library. Same meaning as the
4539 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4542 @cindex @option{^-S^/ASM^} (@command{gcc})
4543 ^Used in place of @option{-c} to^Used to^
4544 cause the assembler source file to be
4545 generated, using @file{^.s^.S^} as the extension,
4546 instead of the object file.
4547 This may be useful if you need to examine the generated assembly code.
4549 @item ^-fverbose-asm^/VERBOSE_ASM^
4550 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4551 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4552 to cause the generated assembly code file to be annotated with variable
4553 names, making it significantly easier to follow.
4556 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4557 Show commands generated by the @command{gcc} driver. Normally used only for
4558 debugging purposes or if you need to be sure what version of the
4559 compiler you are executing.
4563 @cindex @option{-V} (@command{gcc})
4564 Execute @var{ver} version of the compiler. This is the @command{gcc}
4565 version, not the GNAT version.
4568 @item ^-w^/NO_BACK_END_WARNINGS^
4569 @cindex @option{-w} (@command{gcc})
4570 Turn off warnings generated by the back end of the compiler. Use of
4571 this switch also causes the default for front end warnings to be set
4572 to suppress (as though @option{-gnatws} had appeared at the start of
4578 @c Combining qualifiers does not work on VMS
4579 You may combine a sequence of GNAT switches into a single switch. For
4580 example, the combined switch
4582 @cindex Combining GNAT switches
4588 is equivalent to specifying the following sequence of switches:
4591 -gnato -gnatf -gnati3
4596 The following restrictions apply to the combination of switches
4601 The switch @option{-gnatc} if combined with other switches must come
4602 first in the string.
4605 The switch @option{-gnats} if combined with other switches must come
4606 first in the string.
4610 ^^@option{/DISTRIBUTION_STUBS=},^
4611 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4612 switches, and only one of them may appear in the command line.
4615 The switch @option{-gnat-p} may not be combined with any other switch.
4619 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4620 switch), then all further characters in the switch are interpreted
4621 as style modifiers (see description of @option{-gnaty}).
4624 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4625 switch), then all further characters in the switch are interpreted
4626 as debug flags (see description of @option{-gnatd}).
4629 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4630 switch), then all further characters in the switch are interpreted
4631 as warning mode modifiers (see description of @option{-gnatw}).
4634 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4635 switch), then all further characters in the switch are interpreted
4636 as validity checking options (@pxref{Validity Checking}).
4639 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4640 a combined list of options.
4644 @node Output and Error Message Control
4645 @subsection Output and Error Message Control
4649 The standard default format for error messages is called ``brief format''.
4650 Brief format messages are written to @file{stderr} (the standard error
4651 file) and have the following form:
4654 e.adb:3:04: Incorrect spelling of keyword "function"
4655 e.adb:4:20: ";" should be "is"
4659 The first integer after the file name is the line number in the file,
4660 and the second integer is the column number within the line.
4662 @code{GPS} can parse the error messages
4663 and point to the referenced character.
4665 The following switches provide control over the error message
4671 @cindex @option{-gnatv} (@command{gcc})
4674 The v stands for verbose.
4676 The effect of this setting is to write long-format error
4677 messages to @file{stdout} (the standard output file.
4678 The same program compiled with the
4679 @option{-gnatv} switch would generate:
4683 3. funcion X (Q : Integer)
4685 >>> Incorrect spelling of keyword "function"
4688 >>> ";" should be "is"
4693 The vertical bar indicates the location of the error, and the @samp{>>>}
4694 prefix can be used to search for error messages. When this switch is
4695 used the only source lines output are those with errors.
4698 @cindex @option{-gnatl} (@command{gcc})
4700 The @code{l} stands for list.
4702 This switch causes a full listing of
4703 the file to be generated. In the case where a body is
4704 compiled, the corresponding spec is also listed, along
4705 with any subunits. Typical output from compiling a package
4706 body @file{p.adb} might look like:
4708 @smallexample @c ada
4712 1. package body p is
4714 3. procedure a is separate;
4725 2. pragma Elaborate_Body
4749 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4750 standard output is redirected, a brief summary is written to
4751 @file{stderr} (standard error) giving the number of error messages and
4752 warning messages generated.
4754 @item ^-gnatl^/OUTPUT_FILE^=file
4755 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4756 This has the same effect as @option{-gnatl} except that the output is
4757 written to a file instead of to standard output. If the given name
4758 @file{fname} does not start with a period, then it is the full name
4759 of the file to be written. If @file{fname} is an extension, it is
4760 appended to the name of the file being compiled. For example, if
4761 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4762 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4765 @cindex @option{-gnatU} (@command{gcc})
4766 This switch forces all error messages to be preceded by the unique
4767 string ``error:''. This means that error messages take a few more
4768 characters in space, but allows easy searching for and identification
4772 @cindex @option{-gnatb} (@command{gcc})
4774 The @code{b} stands for brief.
4776 This switch causes GNAT to generate the
4777 brief format error messages to @file{stderr} (the standard error
4778 file) as well as the verbose
4779 format message or full listing (which as usual is written to
4780 @file{stdout} (the standard output file).
4782 @item -gnatm=@var{n}
4783 @cindex @option{-gnatm} (@command{gcc})
4785 The @code{m} stands for maximum.
4787 @var{n} is a decimal integer in the
4788 range of 1 to 999999 and limits the number of error or warning
4789 messages to be generated. For example, using
4790 @option{-gnatm2} might yield
4793 e.adb:3:04: Incorrect spelling of keyword "function"
4794 e.adb:5:35: missing ".."
4795 fatal error: maximum number of errors detected
4796 compilation abandoned
4800 The default setting if
4801 no switch is given is 9999. If the number of warnings reaches this
4802 limit, then a message is output and further warnings are suppressed,
4803 but the compilation is continued. If the number of error messages
4804 reaches this limit, then a message is output and the compilation
4805 is abandoned. A value of zero means that no limit applies.
4808 Note that the equal sign is optional, so the switches
4809 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4812 @cindex @option{-gnatf} (@command{gcc})
4813 @cindex Error messages, suppressing
4815 The @code{f} stands for full.
4817 Normally, the compiler suppresses error messages that are likely to be
4818 redundant. This switch causes all error
4819 messages to be generated. In particular, in the case of
4820 references to undefined variables. If a given variable is referenced
4821 several times, the normal format of messages is
4823 e.adb:7:07: "V" is undefined (more references follow)
4827 where the parenthetical comment warns that there are additional
4828 references to the variable @code{V}. Compiling the same program with the
4829 @option{-gnatf} switch yields
4832 e.adb:7:07: "V" is undefined
4833 e.adb:8:07: "V" is undefined
4834 e.adb:8:12: "V" is undefined
4835 e.adb:8:16: "V" is undefined
4836 e.adb:9:07: "V" is undefined
4837 e.adb:9:12: "V" is undefined
4841 The @option{-gnatf} switch also generates additional information for
4842 some error messages. Some examples are:
4846 Details on possibly non-portable unchecked conversion
4848 List possible interpretations for ambiguous calls
4850 Additional details on incorrect parameters
4854 @cindex @option{-gnatjnn} (@command{gcc})
4855 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4856 with continuation lines are treated as though the continuation lines were
4857 separate messages (and so a warning with two continuation lines counts as
4858 three warnings, and is listed as three separate messages).
4860 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4861 messages are output in a different manner. A message and all its continuation
4862 lines are treated as a unit, and count as only one warning or message in the
4863 statistics totals. Furthermore, the message is reformatted so that no line
4864 is longer than nn characters.
4867 @cindex @option{-gnatq} (@command{gcc})
4869 The @code{q} stands for quit (really ``don't quit'').
4871 In normal operation mode, the compiler first parses the program and
4872 determines if there are any syntax errors. If there are, appropriate
4873 error messages are generated and compilation is immediately terminated.
4875 GNAT to continue with semantic analysis even if syntax errors have been
4876 found. This may enable the detection of more errors in a single run. On
4877 the other hand, the semantic analyzer is more likely to encounter some
4878 internal fatal error when given a syntactically invalid tree.
4881 @cindex @option{-gnatQ} (@command{gcc})
4882 In normal operation mode, the @file{ALI} file is not generated if any
4883 illegalities are detected in the program. The use of @option{-gnatQ} forces
4884 generation of the @file{ALI} file. This file is marked as being in
4885 error, so it cannot be used for binding purposes, but it does contain
4886 reasonably complete cross-reference information, and thus may be useful
4887 for use by tools (e.g., semantic browsing tools or integrated development
4888 environments) that are driven from the @file{ALI} file. This switch
4889 implies @option{-gnatq}, since the semantic phase must be run to get a
4890 meaningful ALI file.
4892 In addition, if @option{-gnatt} is also specified, then the tree file is
4893 generated even if there are illegalities. It may be useful in this case
4894 to also specify @option{-gnatq} to ensure that full semantic processing
4895 occurs. The resulting tree file can be processed by ASIS, for the purpose
4896 of providing partial information about illegal units, but if the error
4897 causes the tree to be badly malformed, then ASIS may crash during the
4900 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4901 being in error, @command{gnatmake} will attempt to recompile the source when it
4902 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4904 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4905 since ALI files are never generated if @option{-gnats} is set.
4909 @node Warning Message Control
4910 @subsection Warning Message Control
4911 @cindex Warning messages
4913 In addition to error messages, which correspond to illegalities as defined
4914 in the Ada Reference Manual, the compiler detects two kinds of warning
4917 First, the compiler considers some constructs suspicious and generates a
4918 warning message to alert you to a possible error. Second, if the
4919 compiler detects a situation that is sure to raise an exception at
4920 run time, it generates a warning message. The following shows an example
4921 of warning messages:
4923 e.adb:4:24: warning: creation of object may raise Storage_Error
4924 e.adb:10:17: warning: static value out of range
4925 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4929 GNAT considers a large number of situations as appropriate
4930 for the generation of warning messages. As always, warnings are not
4931 definite indications of errors. For example, if you do an out-of-range
4932 assignment with the deliberate intention of raising a
4933 @code{Constraint_Error} exception, then the warning that may be
4934 issued does not indicate an error. Some of the situations for which GNAT
4935 issues warnings (at least some of the time) are given in the following
4936 list. This list is not complete, and new warnings are often added to
4937 subsequent versions of GNAT. The list is intended to give a general idea
4938 of the kinds of warnings that are generated.
4942 Possible infinitely recursive calls
4945 Out-of-range values being assigned
4948 Possible order of elaboration problems
4951 Assertions (pragma Assert) that are sure to fail
4957 Address clauses with possibly unaligned values, or where an attempt is
4958 made to overlay a smaller variable with a larger one.
4961 Fixed-point type declarations with a null range
4964 Direct_IO or Sequential_IO instantiated with a type that has access values
4967 Variables that are never assigned a value
4970 Variables that are referenced before being initialized
4973 Task entries with no corresponding @code{accept} statement
4976 Duplicate accepts for the same task entry in a @code{select}
4979 Objects that take too much storage
4982 Unchecked conversion between types of differing sizes
4985 Missing @code{return} statement along some execution path in a function
4988 Incorrect (unrecognized) pragmas
4991 Incorrect external names
4994 Allocation from empty storage pool
4997 Potentially blocking operation in protected type
5000 Suspicious parenthesization of expressions
5003 Mismatching bounds in an aggregate
5006 Attempt to return local value by reference
5009 Premature instantiation of a generic body
5012 Attempt to pack aliased components
5015 Out of bounds array subscripts
5018 Wrong length on string assignment
5021 Violations of style rules if style checking is enabled
5024 Unused @code{with} clauses
5027 @code{Bit_Order} usage that does not have any effect
5030 @code{Standard.Duration} used to resolve universal fixed expression
5033 Dereference of possibly null value
5036 Declaration that is likely to cause storage error
5039 Internal GNAT unit @code{with}'ed by application unit
5042 Values known to be out of range at compile time
5045 Unreferenced labels and variables
5048 Address overlays that could clobber memory
5051 Unexpected initialization when address clause present
5054 Bad alignment for address clause
5057 Useless type conversions
5060 Redundant assignment statements and other redundant constructs
5063 Useless exception handlers
5066 Accidental hiding of name by child unit
5069 Access before elaboration detected at compile time
5072 A range in a @code{for} loop that is known to be null or might be null
5077 The following section lists compiler switches that are available
5078 to control the handling of warning messages. It is also possible
5079 to exercise much finer control over what warnings are issued and
5080 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5081 gnat_rm, GNAT Reference manual}.
5086 @emph{Activate most optional warnings.}
5087 @cindex @option{-gnatwa} (@command{gcc})
5088 This switch activates most optional warning messages. See the remaining list
5089 in this section for details on optional warning messages that can be
5090 individually controlled. The warnings that are not turned on by this
5092 @option{-gnatwd} (implicit dereferencing),
5093 @option{-gnatwh} (hiding),
5094 @option{-gnatw.h} (holes (gaps) in record layouts)
5095 @option{-gnatw.i} (overlapping actuals),
5096 @option{-gnatwl} (elaboration warnings),
5097 @option{-gnatw.l} (inherited aspects),
5098 @option{-gnatw.o} (warn on values set by out parameters ignored),
5099 @option{-gnatwt} (tracking of deleted conditional code)
5100 and @option{-gnatw.u} (unordered enumeration),
5101 All other optional warnings are turned on.
5104 @emph{Suppress all optional errors.}
5105 @cindex @option{-gnatwA} (@command{gcc})
5106 This switch suppresses all optional warning messages, see remaining list
5107 in this section for details on optional warning messages that can be
5108 individually controlled. Note that unlike switch @option{-gnatws}, the
5109 use of switch @option{-gnatwA} does not suppress warnings that are
5110 normally given unconditionally and cannot be individually controlled
5111 (for example, the warning about a missing exit path in a function).
5112 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5113 the use of switch @option{-gnatwA} can be individually turned back
5114 on. For example the use of switch @option{-gnatwA} followed by
5115 switch @option{-gnatwd} will suppress all optional warnings except
5116 the warnings for implicit dereferencing.
5119 @emph{Activate warnings on failing assertions.}
5120 @cindex @option{-gnatw.a} (@command{gcc})
5121 @cindex Assert failures
5122 This switch activates warnings for assertions where the compiler can tell at
5123 compile time that the assertion will fail. Note that this warning is given
5124 even if assertions are disabled. The default is that such warnings are
5128 @emph{Suppress warnings on failing assertions.}
5129 @cindex @option{-gnatw.A} (@command{gcc})
5130 @cindex Assert failures
5131 This switch suppresses warnings for assertions where the compiler can tell at
5132 compile time that the assertion will fail.
5135 @emph{Activate warnings on bad fixed values.}
5136 @cindex @option{-gnatwb} (@command{gcc})
5137 @cindex Bad fixed values
5138 @cindex Fixed-point Small value
5140 This switch activates warnings for static fixed-point expressions whose
5141 value is not an exact multiple of Small. Such values are implementation
5142 dependent, since an implementation is free to choose either of the multiples
5143 that surround the value. GNAT always chooses the closer one, but this is not
5144 required behavior, and it is better to specify a value that is an exact
5145 multiple, ensuring predictable execution. The default is that such warnings
5149 @emph{Suppress warnings on bad fixed values.}
5150 @cindex @option{-gnatwB} (@command{gcc})
5151 This switch suppresses warnings for static fixed-point expressions whose
5152 value is not an exact multiple of Small.
5155 @emph{Activate warnings on biased representation.}
5156 @cindex @option{-gnatw.b} (@command{gcc})
5157 @cindex Biased representation
5158 This switch activates warnings when a size clause, value size clause, component
5159 clause, or component size clause forces the use of biased representation for an
5160 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5161 to represent 10/11). The default is that such warnings are generated.
5164 @emph{Suppress warnings on biased representation.}
5165 @cindex @option{-gnatwB} (@command{gcc})
5166 This switch suppresses warnings for representation clauses that force the use
5167 of biased representation.
5170 @emph{Activate warnings on conditionals.}
5171 @cindex @option{-gnatwc} (@command{gcc})
5172 @cindex Conditionals, constant
5173 This switch activates warnings for conditional expressions used in
5174 tests that are known to be True or False at compile time. The default
5175 is that such warnings are not generated.
5176 Note that this warning does
5177 not get issued for the use of boolean variables or constants whose
5178 values are known at compile time, since this is a standard technique
5179 for conditional compilation in Ada, and this would generate too many
5180 false positive warnings.
5182 This warning option also activates a special test for comparisons using
5183 the operators ``>='' and`` <=''.
5184 If the compiler can tell that only the equality condition is possible,
5185 then it will warn that the ``>'' or ``<'' part of the test
5186 is useless and that the operator could be replaced by ``=''.
5187 An example would be comparing a @code{Natural} variable <= 0.
5189 This warning option also generates warnings if
5190 one or both tests is optimized away in a membership test for integer
5191 values if the result can be determined at compile time. Range tests on
5192 enumeration types are not included, since it is common for such tests
5193 to include an end point.
5195 This warning can also be turned on using @option{-gnatwa}.
5198 @emph{Suppress warnings on conditionals.}
5199 @cindex @option{-gnatwC} (@command{gcc})
5200 This switch suppresses warnings for conditional expressions used in
5201 tests that are known to be True or False at compile time.
5204 @emph{Activate warnings on missing component clauses.}
5205 @cindex @option{-gnatw.c} (@command{gcc})
5206 @cindex Component clause, missing
5207 This switch activates warnings for record components where a record
5208 representation clause is present and has component clauses for the
5209 majority, but not all, of the components. A warning is given for each
5210 component for which no component clause is present.
5212 This warning can also be turned on using @option{-gnatwa}.
5215 @emph{Suppress warnings on missing component clauses.}
5216 @cindex @option{-gnatwC} (@command{gcc})
5217 This switch suppresses warnings for record components that are
5218 missing a component clause in the situation described above.
5221 @emph{Activate warnings on implicit dereferencing.}
5222 @cindex @option{-gnatwd} (@command{gcc})
5223 If this switch is set, then the use of a prefix of an access type
5224 in an indexed component, slice, or selected component without an
5225 explicit @code{.all} will generate a warning. With this warning
5226 enabled, access checks occur only at points where an explicit
5227 @code{.all} appears in the source code (assuming no warnings are
5228 generated as a result of this switch). The default is that such
5229 warnings are not generated.
5230 Note that @option{-gnatwa} does not affect the setting of
5231 this warning option.
5234 @emph{Suppress warnings on implicit dereferencing.}
5235 @cindex @option{-gnatwD} (@command{gcc})
5236 @cindex Implicit dereferencing
5237 @cindex Dereferencing, implicit
5238 This switch suppresses warnings for implicit dereferences in
5239 indexed components, slices, and selected components.
5242 @emph{Treat warnings and style checks as errors.}
5243 @cindex @option{-gnatwe} (@command{gcc})
5244 @cindex Warnings, treat as error
5245 This switch causes warning messages and style check messages to be
5247 The warning string still appears, but the warning messages are counted
5248 as errors, and prevent the generation of an object file. Note that this
5249 is the only -gnatw switch that affects the handling of style check messages.
5252 @emph{Activate every optional warning}
5253 @cindex @option{-gnatw.e} (@command{gcc})
5254 @cindex Warnings, activate every optional warning
5255 This switch activates all optional warnings, including those which
5256 are not activated by @code{-gnatwa}. The use of this switch is not
5257 recommended for normal use. If you turn this switch on, it is almost
5258 certain that you will get large numbers of useless warnings. The
5259 warnings that are excluded from @code{-gnatwa} are typically highly
5260 specialized warnings that are suitable for use only in code that has
5261 been specifically designed according to specialized coding rules.
5264 @emph{Activate warnings on unreferenced formals.}
5265 @cindex @option{-gnatwf} (@command{gcc})
5266 @cindex Formals, unreferenced
5267 This switch causes a warning to be generated if a formal parameter
5268 is not referenced in the body of the subprogram. This warning can
5269 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5270 default is that these warnings are not generated.
5273 @emph{Suppress warnings on unreferenced formals.}
5274 @cindex @option{-gnatwF} (@command{gcc})
5275 This switch suppresses warnings for unreferenced formal
5276 parameters. Note that the
5277 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5278 effect of warning on unreferenced entities other than subprogram
5282 @emph{Activate warnings on unrecognized pragmas.}
5283 @cindex @option{-gnatwg} (@command{gcc})
5284 @cindex Pragmas, unrecognized
5285 This switch causes a warning to be generated if an unrecognized
5286 pragma is encountered. Apart from issuing this warning, the
5287 pragma is ignored and has no effect. This warning can
5288 also be turned on using @option{-gnatwa}. The default
5289 is that such warnings are issued (satisfying the Ada Reference
5290 Manual requirement that such warnings appear).
5293 @emph{Suppress warnings on unrecognized pragmas.}
5294 @cindex @option{-gnatwG} (@command{gcc})
5295 This switch suppresses warnings for unrecognized pragmas.
5298 @emph{Activate warnings on hiding.}
5299 @cindex @option{-gnatwh} (@command{gcc})
5300 @cindex Hiding of Declarations
5301 This switch activates warnings on hiding declarations.
5302 A declaration is considered hiding
5303 if it is for a non-overloadable entity, and it declares an entity with the
5304 same name as some other entity that is directly or use-visible. The default
5305 is that such warnings are not generated.
5306 Note that @option{-gnatwa} does not affect the setting of this warning option.
5309 @emph{Suppress warnings on hiding.}
5310 @cindex @option{-gnatwH} (@command{gcc})
5311 This switch suppresses warnings on hiding declarations.
5314 @emph{Activate warnings on holes/gaps in records.}
5315 @cindex @option{-gnatw.h} (@command{gcc})
5316 @cindex Record Representation (gaps)
5317 This switch activates warnings on component clauses in record
5318 representation clauses that leave holes (gaps) in the record layout.
5319 If this warning option is active, then record representation clauses
5320 should specify a contiguous layout, adding unused fill fields if needed.
5321 Note that @option{-gnatwa} does not affect the setting of this warning option.
5324 @emph{Suppress warnings on holes/gaps in records.}
5325 @cindex @option{-gnatw.H} (@command{gcc})
5326 This switch suppresses warnings on component clauses in record
5327 representation clauses that leave holes (haps) in the record layout.
5330 @emph{Activate warnings on implementation units.}
5331 @cindex @option{-gnatwi} (@command{gcc})
5332 This switch activates warnings for a @code{with} of an internal GNAT
5333 implementation unit, defined as any unit from the @code{Ada},
5334 @code{Interfaces}, @code{GNAT},
5335 ^^@code{DEC},^ or @code{System}
5336 hierarchies that is not
5337 documented in either the Ada Reference Manual or the GNAT
5338 Programmer's Reference Manual. Such units are intended only
5339 for internal implementation purposes and should not be @code{with}'ed
5340 by user programs. The default is that such warnings are generated
5341 This warning can also be turned on using @option{-gnatwa}.
5344 @emph{Disable warnings on implementation units.}
5345 @cindex @option{-gnatwI} (@command{gcc})
5346 This switch disables warnings for a @code{with} of an internal GNAT
5347 implementation unit.
5350 @emph{Activate warnings on overlapping actuals.}
5351 @cindex @option{-gnatw.i} (@command{gcc})
5352 This switch enables a warning on statically detectable overlapping actuals in
5353 a subprogram call, when one of the actuals is an in-out parameter, and the
5354 types of the actuals are not by-copy types. The warning is off by default,
5355 and is not included under -gnatwa.
5358 @emph{Disable warnings on overlapping actuals.}
5359 @cindex @option{-gnatw.I} (@command{gcc})
5360 This switch disables warnings on overlapping actuals in a call..
5363 @emph{Activate warnings on obsolescent features (Annex J).}
5364 @cindex @option{-gnatwj} (@command{gcc})
5365 @cindex Features, obsolescent
5366 @cindex Obsolescent features
5367 If this warning option is activated, then warnings are generated for
5368 calls to subprograms marked with @code{pragma Obsolescent} and
5369 for use of features in Annex J of the Ada Reference Manual. In the
5370 case of Annex J, not all features are flagged. In particular use
5371 of the renamed packages (like @code{Text_IO}) and use of package
5372 @code{ASCII} are not flagged, since these are very common and
5373 would generate many annoying positive warnings. The default is that
5374 such warnings are not generated. This warning is also turned on by
5375 the use of @option{-gnatwa}.
5377 In addition to the above cases, warnings are also generated for
5378 GNAT features that have been provided in past versions but which
5379 have been superseded (typically by features in the new Ada standard).
5380 For example, @code{pragma Ravenscar} will be flagged since its
5381 function is replaced by @code{pragma Profile(Ravenscar)}.
5383 Note that this warning option functions differently from the
5384 restriction @code{No_Obsolescent_Features} in two respects.
5385 First, the restriction applies only to annex J features.
5386 Second, the restriction does flag uses of package @code{ASCII}.
5389 @emph{Suppress warnings on obsolescent features (Annex J).}
5390 @cindex @option{-gnatwJ} (@command{gcc})
5391 This switch disables warnings on use of obsolescent features.
5394 @emph{Activate warnings on variables that could be constants.}
5395 @cindex @option{-gnatwk} (@command{gcc})
5396 This switch activates warnings for variables that are initialized but
5397 never modified, and then could be declared constants. The default is that
5398 such warnings are not given.
5399 This warning can also be turned on using @option{-gnatwa}.
5402 @emph{Suppress warnings on variables that could be constants.}
5403 @cindex @option{-gnatwK} (@command{gcc})
5404 This switch disables warnings on variables that could be declared constants.
5407 @emph{Activate warnings for elaboration pragmas.}
5408 @cindex @option{-gnatwl} (@command{gcc})
5409 @cindex Elaboration, warnings
5410 This switch activates warnings on missing
5411 @code{Elaborate_All} and @code{Elaborate} pragmas.
5412 See the section in this guide on elaboration checking for details on
5413 when such pragmas should be used. In dynamic elaboration mode, this switch
5414 generations warnings about the need to add elaboration pragmas. Note however,
5415 that if you blindly follow these warnings, and add @code{Elaborate_All}
5416 warnings wherever they are recommended, you basically end up with the
5417 equivalent of the static elaboration model, which may not be what you want for
5418 legacy code for which the static model does not work.
5420 For the static model, the messages generated are labeled "info:" (for
5421 information messages). They are not warnings to add elaboration pragmas,
5422 merely informational messages showing what implicit elaboration pragmas
5423 have been added, for use in analyzing elaboration circularity problems.
5425 Warnings are also generated if you
5426 are using the static mode of elaboration, and a @code{pragma Elaborate}
5427 is encountered. The default is that such warnings
5429 This warning is not automatically turned on by the use of @option{-gnatwa}.
5432 @emph{Suppress warnings for elaboration pragmas.}
5433 @cindex @option{-gnatwL} (@command{gcc})
5434 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5435 See the section in this guide on elaboration checking for details on
5436 when such pragmas should be used.
5439 @emph{List inherited aspects.}
5440 @cindex @option{-gnatw.l} (@command{gcc})
5441 This switch causes the compiler to list inherited invariants,
5442 preconditions, and postconditions from Invariant'Class, Pre'Class, and
5443 Post'Class aspects. Also list inherited subtype predicates.
5444 These messages are not automatically turned on by the use of @option{-gnatwa}.
5447 @emph{Suppress listing of inherited aspects.}
5448 @cindex @option{-gnatw.L} (@command{gcc})
5449 This switch suppresses listing of inherited aspects.
5452 @emph{Activate warnings on modified but unreferenced variables.}
5453 @cindex @option{-gnatwm} (@command{gcc})
5454 This switch activates warnings for variables that are assigned (using
5455 an initialization value or with one or more assignment statements) but
5456 whose value is never read. The warning is suppressed for volatile
5457 variables and also for variables that are renamings of other variables
5458 or for which an address clause is given.
5459 This warning can also be turned on using @option{-gnatwa}.
5460 The default is that these warnings are not given.
5463 @emph{Disable warnings on modified but unreferenced variables.}
5464 @cindex @option{-gnatwM} (@command{gcc})
5465 This switch disables warnings for variables that are assigned or
5466 initialized, but never read.
5469 @emph{Activate warnings on suspicious modulus values.}
5470 @cindex @option{-gnatw.m} (@command{gcc})
5471 This switch activates warnings for modulus values that seem suspicious.
5472 The cases caught are where the size is the same as the modulus (e.g.
5473 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5474 with no size clause. The guess in both cases is that 2**x was intended
5475 rather than x. In addition expressions of the form 2*x for small x
5476 generate a warning (the almost certainly accurate guess being that
5477 2**x was intended). The default is that these warnings are given.
5480 @emph{Disable warnings on suspicious modulus values.}
5481 @cindex @option{-gnatw.M} (@command{gcc})
5482 This switch disables warnings for suspicious modulus values.
5485 @emph{Set normal warnings mode.}
5486 @cindex @option{-gnatwn} (@command{gcc})
5487 This switch sets normal warning mode, in which enabled warnings are
5488 issued and treated as warnings rather than errors. This is the default
5489 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5490 an explicit @option{-gnatws} or
5491 @option{-gnatwe}. It also cancels the effect of the
5492 implicit @option{-gnatwe} that is activated by the
5493 use of @option{-gnatg}.
5496 @emph{Activate warnings on address clause overlays.}
5497 @cindex @option{-gnatwo} (@command{gcc})
5498 @cindex Address Clauses, warnings
5499 This switch activates warnings for possibly unintended initialization
5500 effects of defining address clauses that cause one variable to overlap
5501 another. The default is that such warnings are generated.
5502 This warning can also be turned on using @option{-gnatwa}.
5505 @emph{Suppress warnings on address clause overlays.}
5506 @cindex @option{-gnatwO} (@command{gcc})
5507 This switch suppresses warnings on possibly unintended initialization
5508 effects of defining address clauses that cause one variable to overlap
5512 @emph{Activate warnings on modified but unreferenced out parameters.}
5513 @cindex @option{-gnatw.o} (@command{gcc})
5514 This switch activates warnings for variables that are modified by using
5515 them as actuals for a call to a procedure with an out mode formal, where
5516 the resulting assigned value is never read. It is applicable in the case
5517 where there is more than one out mode formal. If there is only one out
5518 mode formal, the warning is issued by default (controlled by -gnatwu).
5519 The warning is suppressed for volatile
5520 variables and also for variables that are renamings of other variables
5521 or for which an address clause is given.
5522 The default is that these warnings are not given. Note that this warning
5523 is not included in -gnatwa, it must be activated explicitly.
5526 @emph{Disable warnings on modified but unreferenced out parameters.}
5527 @cindex @option{-gnatw.O} (@command{gcc})
5528 This switch suppresses warnings for variables that are modified by using
5529 them as actuals for a call to a procedure with an out mode formal, where
5530 the resulting assigned value is never read.
5533 @emph{Activate warnings on ineffective pragma Inlines.}
5534 @cindex @option{-gnatwp} (@command{gcc})
5535 @cindex Inlining, warnings
5536 This switch activates warnings for failure of front end inlining
5537 (activated by @option{-gnatN}) to inline a particular call. There are
5538 many reasons for not being able to inline a call, including most
5539 commonly that the call is too complex to inline. The default is
5540 that such warnings are not given.
5541 This warning can also be turned on using @option{-gnatwa}.
5542 Warnings on ineffective inlining by the gcc back-end can be activated
5543 separately, using the gcc switch -Winline.
5546 @emph{Suppress warnings on ineffective pragma Inlines.}
5547 @cindex @option{-gnatwP} (@command{gcc})
5548 This switch suppresses warnings on ineffective pragma Inlines. If the
5549 inlining mechanism cannot inline a call, it will simply ignore the
5553 @emph{Activate warnings on parameter ordering.}
5554 @cindex @option{-gnatw.p} (@command{gcc})
5555 @cindex Parameter order, warnings
5556 This switch activates warnings for cases of suspicious parameter
5557 ordering when the list of arguments are all simple identifiers that
5558 match the names of the formals, but are in a different order. The
5559 warning is suppressed if any use of named parameter notation is used,
5560 so this is the appropriate way to suppress a false positive (and
5561 serves to emphasize that the "misordering" is deliberate). The
5563 that such warnings are not given.
5564 This warning can also be turned on using @option{-gnatwa}.
5567 @emph{Suppress warnings on parameter ordering.}
5568 @cindex @option{-gnatw.P} (@command{gcc})
5569 This switch suppresses warnings on cases of suspicious parameter
5573 @emph{Activate warnings on questionable missing parentheses.}
5574 @cindex @option{-gnatwq} (@command{gcc})
5575 @cindex Parentheses, warnings
5576 This switch activates warnings for cases where parentheses are not used and
5577 the result is potential ambiguity from a readers point of view. For example
5578 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5579 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5580 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5581 follow the rule of always parenthesizing to make the association clear, and
5582 this warning switch warns if such parentheses are not present. The default
5583 is that these warnings are given.
5584 This warning can also be turned on using @option{-gnatwa}.
5587 @emph{Suppress warnings on questionable missing parentheses.}
5588 @cindex @option{-gnatwQ} (@command{gcc})
5589 This switch suppresses warnings for cases where the association is not
5590 clear and the use of parentheses is preferred.
5593 @emph{Activate warnings on redundant constructs.}
5594 @cindex @option{-gnatwr} (@command{gcc})
5595 This switch activates warnings for redundant constructs. The following
5596 is the current list of constructs regarded as redundant:
5600 Assignment of an item to itself.
5602 Type conversion that converts an expression to its own type.
5604 Use of the attribute @code{Base} where @code{typ'Base} is the same
5607 Use of pragma @code{Pack} when all components are placed by a record
5608 representation clause.
5610 Exception handler containing only a reraise statement (raise with no
5611 operand) which has no effect.
5613 Use of the operator abs on an operand that is known at compile time
5616 Comparison of boolean expressions to an explicit True value.
5619 This warning can also be turned on using @option{-gnatwa}.
5620 The default is that warnings for redundant constructs are not given.
5623 @emph{Suppress warnings on redundant constructs.}
5624 @cindex @option{-gnatwR} (@command{gcc})
5625 This switch suppresses warnings for redundant constructs.
5628 @emph{Activate warnings for object renaming function.}
5629 @cindex @option{-gnatw.r} (@command{gcc})
5630 This switch activates warnings for an object renaming that renames a
5631 function call, which is equivalent to a constant declaration (as
5632 opposed to renaming the function itself). The default is that these
5633 warnings are given. This warning can also be turned on using
5637 @emph{Suppress warnings for object renaming function.}
5638 @cindex @option{-gnatwT} (@command{gcc})
5639 This switch suppresses warnings for object renaming function.
5642 @emph{Suppress all warnings.}
5643 @cindex @option{-gnatws} (@command{gcc})
5644 This switch completely suppresses the
5645 output of all warning messages from the GNAT front end, including
5646 both warnings that can be controlled by switches described in this
5647 section, and those that are normally given unconditionally. The
5648 effect of this suppress action can only be cancelled by a subsequent
5649 use of the switch @option{-gnatwn}.
5651 Note that switch @option{-gnatws} does not suppress
5652 warnings from the @command{gcc} back end.
5653 To suppress these back end warnings as well, use the switch @option{-w}
5654 in addition to @option{-gnatws}. Also this switch has no effect on the
5655 handling of style check messages.
5658 @emph{Activate warnings on overridden size clauses.}
5659 @cindex @option{-gnatw.s} (@command{gcc})
5660 @cindex Record Representation (component sizes)
5661 This switch activates warnings on component clauses in record
5662 representation clauses where the length given overrides that
5663 specified by an explicit size clause for the component type. A
5664 warning is similarly given in the array case if a specified
5665 component size overrides an explicit size clause for the array
5667 Note that @option{-gnatwa} does not affect the setting of this warning option.
5670 @emph{Suppress warnings on overridden size clauses.}
5671 @cindex @option{-gnatw.S} (@command{gcc})
5672 This switch suppresses warnings on component clauses in record
5673 representation clauses that override size clauses, and similar
5674 warnings when an array component size overrides a size clause.
5677 @emph{Activate warnings for tracking of deleted conditional code.}
5678 @cindex @option{-gnatwt} (@command{gcc})
5679 @cindex Deactivated code, warnings
5680 @cindex Deleted code, warnings
5681 This switch activates warnings for tracking of code in conditionals (IF and
5682 CASE statements) that is detected to be dead code which cannot be executed, and
5683 which is removed by the front end. This warning is off by default, and is not
5684 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5685 useful for detecting deactivated code in certified applications.
5688 @emph{Suppress warnings for tracking of deleted conditional code.}
5689 @cindex @option{-gnatwT} (@command{gcc})
5690 This switch suppresses warnings for tracking of deleted conditional code.
5693 @emph{Activate warnings on suspicious contracts.}
5694 @cindex @option{-gnatw.t} (@command{gcc})
5695 This switch activates warnings on suspicious postconditions (whether a
5696 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012). A
5697 function postcondition is suspicious when it does not mention the result
5698 of the function. A procedure postcondition is suspicious when it only
5699 refers to the pre-state of the procedure, because in that case it should
5700 rather be expressed as a precondition. The default is that such warnings
5701 are not generated. This warning can also be turned on using @option{-gnatwa}.
5704 @emph{Suppress warnings on suspicious contracts.}
5705 @cindex @option{-gnatw.T} (@command{gcc})
5706 This switch suppresses warnings on suspicious postconditions.
5709 @emph{Activate warnings on unused entities.}
5710 @cindex @option{-gnatwu} (@command{gcc})
5711 This switch activates warnings to be generated for entities that
5712 are declared but not referenced, and for units that are @code{with}'ed
5714 referenced. In the case of packages, a warning is also generated if
5715 no entities in the package are referenced. This means that if a with'ed
5716 package is referenced but the only references are in @code{use}
5717 clauses or @code{renames}
5718 declarations, a warning is still generated. A warning is also generated
5719 for a generic package that is @code{with}'ed but never instantiated.
5720 In the case where a package or subprogram body is compiled, and there
5721 is a @code{with} on the corresponding spec
5722 that is only referenced in the body,
5723 a warning is also generated, noting that the
5724 @code{with} can be moved to the body. The default is that
5725 such warnings are not generated.
5726 This switch also activates warnings on unreferenced formals
5727 (it includes the effect of @option{-gnatwf}).
5728 This warning can also be turned on using @option{-gnatwa}.
5731 @emph{Suppress warnings on unused entities.}
5732 @cindex @option{-gnatwU} (@command{gcc})
5733 This switch suppresses warnings for unused entities and packages.
5734 It also turns off warnings on unreferenced formals (and thus includes
5735 the effect of @option{-gnatwF}).
5738 @emph{Activate warnings on unordered enumeration types.}
5739 @cindex @option{-gnatw.u} (@command{gcc})
5740 This switch causes enumeration types to be considered as conceptually
5741 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5742 The effect is to generate warnings in clients that use explicit comparisons
5743 or subranges, since these constructs both treat objects of the type as
5744 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5745 which the type is declared, or its body or subunits.) Please refer to
5746 the description of pragma @code{Ordered} in the
5747 @cite{@value{EDITION} Reference Manual} for further details.
5748 The default is that such warnings are not generated.
5749 This warning is not automatically turned on by the use of @option{-gnatwa}.
5752 @emph{Deactivate warnings on unordered enumeration types.}
5753 @cindex @option{-gnatw.U} (@command{gcc})
5754 This switch causes all enumeration types to be considered as ordered, so
5755 that no warnings are given for comparisons or subranges for any type.
5758 @emph{Activate warnings on unassigned variables.}
5759 @cindex @option{-gnatwv} (@command{gcc})
5760 @cindex Unassigned variable warnings
5761 This switch activates warnings for access to variables which
5762 may not be properly initialized. The default is that
5763 such warnings are generated.
5764 This warning can also be turned on using @option{-gnatwa}.
5767 @emph{Suppress warnings on unassigned variables.}
5768 @cindex @option{-gnatwV} (@command{gcc})
5769 This switch suppresses warnings for access to variables which
5770 may not be properly initialized.
5771 For variables of a composite type, the warning can also be suppressed in
5772 Ada 2005 by using a default initialization with a box. For example, if
5773 Table is an array of records whose components are only partially uninitialized,
5774 then the following code:
5776 @smallexample @c ada
5777 Tab : Table := (others => <>);
5780 will suppress warnings on subsequent statements that access components
5784 @emph{Activate warnings on wrong low bound assumption.}
5785 @cindex @option{-gnatww} (@command{gcc})
5786 @cindex String indexing warnings
5787 This switch activates warnings for indexing an unconstrained string parameter
5788 with a literal or S'Length. This is a case where the code is assuming that the
5789 low bound is one, which is in general not true (for example when a slice is
5790 passed). The default is that such warnings are generated.
5791 This warning can also be turned on using @option{-gnatwa}.
5794 @emph{Suppress warnings on wrong low bound assumption.}
5795 @cindex @option{-gnatwW} (@command{gcc})
5796 This switch suppresses warnings for indexing an unconstrained string parameter
5797 with a literal or S'Length. Note that this warning can also be suppressed
5798 in a particular case by adding an
5799 assertion that the lower bound is 1,
5800 as shown in the following example.
5802 @smallexample @c ada
5803 procedure K (S : String) is
5804 pragma Assert (S'First = 1);
5809 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5810 @cindex @option{-gnatw.w} (@command{gcc})
5811 @cindex Warnings Off control
5812 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5813 where either the pragma is entirely useless (because it suppresses no
5814 warnings), or it could be replaced by @code{pragma Unreferenced} or
5815 @code{pragma Unmodified}. The default is that these warnings are not given.
5816 Note that this warning is not included in -gnatwa, it must be
5817 activated explicitly.
5820 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5821 @cindex @option{-gnatw.W} (@command{gcc})
5822 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5825 @emph{Activate warnings on Export/Import pragmas.}
5826 @cindex @option{-gnatwx} (@command{gcc})
5827 @cindex Export/Import pragma warnings
5828 This switch activates warnings on Export/Import pragmas when
5829 the compiler detects a possible conflict between the Ada and
5830 foreign language calling sequences. For example, the use of
5831 default parameters in a convention C procedure is dubious
5832 because the C compiler cannot supply the proper default, so
5833 a warning is issued. The default is that such warnings are
5835 This warning can also be turned on using @option{-gnatwa}.
5838 @emph{Suppress warnings on Export/Import pragmas.}
5839 @cindex @option{-gnatwX} (@command{gcc})
5840 This switch suppresses warnings on Export/Import pragmas.
5841 The sense of this is that you are telling the compiler that
5842 you know what you are doing in writing the pragma, and it
5843 should not complain at you.
5846 @emph{Activate warnings for No_Exception_Propagation mode.}
5847 @cindex @option{-gnatwm} (@command{gcc})
5848 This switch activates warnings for exception usage when pragma Restrictions
5849 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5850 explicit exception raises which are not covered by a local handler, and for
5851 exception handlers which do not cover a local raise. The default is that these
5852 warnings are not given.
5855 @emph{Disable warnings for No_Exception_Propagation mode.}
5856 This switch disables warnings for exception usage when pragma Restrictions
5857 (No_Exception_Propagation) is in effect.
5860 @emph{Activate warnings for Ada compatibility issues.}
5861 @cindex @option{-gnatwy} (@command{gcc})
5862 @cindex Ada compatibility issues warnings
5863 For the most part, newer versions of Ada are upwards compatible
5864 with older versions. For example, Ada 2005 programs will almost
5865 always work when compiled as Ada 2012.
5866 However there are some exceptions (for example the fact that
5867 @code{some} is now a reserved word in Ada 2012). This
5868 switch activates several warnings to help in identifying
5869 and correcting such incompatibilities. The default is that
5870 these warnings are generated. Note that at one point Ada 2005
5871 was called Ada 0Y, hence the choice of character.
5872 This warning can also be turned on using @option{-gnatwa}.
5875 @emph{Disable warnings for Ada compatibility issues.}
5876 @cindex @option{-gnatwY} (@command{gcc})
5877 @cindex Ada compatibility issues warnings
5878 This switch suppresses the warnings intended to help in identifying
5879 incompatibilities between Ada language versions.
5882 @emph{Activate warnings on unchecked conversions.}
5883 @cindex @option{-gnatwz} (@command{gcc})
5884 @cindex Unchecked_Conversion warnings
5885 This switch activates warnings for unchecked conversions
5886 where the types are known at compile time to have different
5888 is that such warnings are generated. Warnings are also
5889 generated for subprogram pointers with different conventions,
5890 and, on VMS only, for data pointers with different conventions.
5891 This warning can also be turned on using @option{-gnatwa}.
5894 @emph{Suppress warnings on unchecked conversions.}
5895 @cindex @option{-gnatwZ} (@command{gcc})
5896 This switch suppresses warnings for unchecked conversions
5897 where the types are known at compile time to have different
5898 sizes or conventions.
5900 @item ^-Wunused^WARNINGS=UNUSED^
5901 @cindex @option{-Wunused}
5902 The warnings controlled by the @option{-gnatw} switch are generated by
5903 the front end of the compiler. The @option{GCC} back end can provide
5904 additional warnings and they are controlled by the @option{-W} switch.
5905 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5906 warnings for entities that are declared but not referenced.
5908 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5909 @cindex @option{-Wuninitialized}
5910 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5911 the back end warning for uninitialized variables. This switch must be
5912 used in conjunction with an optimization level greater than zero.
5914 @item -Wstack-usage=@var{len}
5915 @cindex @option{-Wstack-usage}
5916 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5917 See @ref{Static Stack Usage Analysis} for details.
5919 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5920 @cindex @option{-Wall}
5921 This switch enables most warnings from the @option{GCC} back end.
5922 The code generator detects a number of warning situations that are missed
5923 by the @option{GNAT} front end, and this switch can be used to activate them.
5924 The use of this switch also sets the default front end warning mode to
5925 @option{-gnatwa}, that is, most front end warnings activated as well.
5927 @item ^-w^/NO_BACK_END_WARNINGS^
5929 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5930 The use of this switch also sets the default front end warning mode to
5931 @option{-gnatws}, that is, front end warnings suppressed as well.
5937 A string of warning parameters can be used in the same parameter. For example:
5944 will turn on all optional warnings except for unrecognized pragma warnings,
5945 and also specify that warnings should be treated as errors.
5948 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5990 @node Debugging and Assertion Control
5991 @subsection Debugging and Assertion Control
5995 @cindex @option{-gnata} (@command{gcc})
6001 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6002 are ignored. This switch, where @samp{a} stands for assert, causes
6003 @code{Assert} and @code{Debug} pragmas to be activated.
6005 The pragmas have the form:
6009 @b{pragma} Assert (@var{Boolean-expression} @r{[},
6010 @var{static-string-expression}@r{]})
6011 @b{pragma} Debug (@var{procedure call})
6016 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6017 If the result is @code{True}, the pragma has no effect (other than
6018 possible side effects from evaluating the expression). If the result is
6019 @code{False}, the exception @code{Assert_Failure} declared in the package
6020 @code{System.Assertions} is
6021 raised (passing @var{static-string-expression}, if present, as the
6022 message associated with the exception). If no string expression is
6023 given the default is a string giving the file name and line number
6026 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6027 @code{pragma Debug} may appear within a declaration sequence, allowing
6028 debugging procedures to be called between declarations.
6031 @item /DEBUG@r{[}=debug-level@r{]}
6033 Specifies how much debugging information is to be included in
6034 the resulting object file where 'debug-level' is one of the following:
6037 Include both debugger symbol records and traceback
6039 This is the default setting.
6041 Include both debugger symbol records and traceback in
6044 Excludes both debugger symbol records and traceback
6045 the object file. Same as /NODEBUG.
6047 Includes only debugger symbol records in the object
6048 file. Note that this doesn't include traceback information.
6053 @node Validity Checking
6054 @subsection Validity Checking
6055 @findex Validity Checking
6058 The Ada Reference Manual defines the concept of invalid values (see
6059 RM 13.9.1). The primary source of invalid values is uninitialized
6060 variables. A scalar variable that is left uninitialized may contain
6061 an invalid value; the concept of invalid does not apply to access or
6064 It is an error to read an invalid value, but the RM does not require
6065 run-time checks to detect such errors, except for some minimal
6066 checking to prevent erroneous execution (i.e. unpredictable
6067 behavior). This corresponds to the @option{-gnatVd} switch below,
6068 which is the default. For example, by default, if the expression of a
6069 case statement is invalid, it will raise Constraint_Error rather than
6070 causing a wild jump, and if an array index on the left-hand side of an
6071 assignment is invalid, it will raise Constraint_Error rather than
6072 overwriting an arbitrary memory location.
6074 The @option{-gnatVa} may be used to enable additional validity checks,
6075 which are not required by the RM. These checks are often very
6076 expensive (which is why the RM does not require them). These checks
6077 are useful in tracking down uninitialized variables, but they are
6078 not usually recommended for production builds.
6080 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6081 control; you can enable whichever validity checks you desire. However,
6082 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6083 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6084 sufficient for non-debugging use.
6086 The @option{-gnatB} switch tells the compiler to assume that all
6087 values are valid (that is, within their declared subtype range)
6088 except in the context of a use of the Valid attribute. This means
6089 the compiler can generate more efficient code, since the range
6090 of values is better known at compile time. However, an uninitialized
6091 variable can cause wild jumps and memory corruption in this mode.
6093 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6094 checking mode as described below.
6096 The @code{x} argument is a string of letters that
6097 indicate validity checks that are performed or not performed in addition
6098 to the default checks required by Ada as described above.
6101 The options allowed for this qualifier
6102 indicate validity checks that are performed or not performed in addition
6103 to the default checks required by Ada as described above.
6109 @emph{All validity checks.}
6110 @cindex @option{-gnatVa} (@command{gcc})
6111 All validity checks are turned on.
6113 That is, @option{-gnatVa} is
6114 equivalent to @option{gnatVcdfimorst}.
6118 @emph{Validity checks for copies.}
6119 @cindex @option{-gnatVc} (@command{gcc})
6120 The right hand side of assignments, and the initializing values of
6121 object declarations are validity checked.
6124 @emph{Default (RM) validity checks.}
6125 @cindex @option{-gnatVd} (@command{gcc})
6126 Some validity checks are done by default following normal Ada semantics
6128 A check is done in case statements that the expression is within the range
6129 of the subtype. If it is not, Constraint_Error is raised.
6130 For assignments to array components, a check is done that the expression used
6131 as index is within the range. If it is not, Constraint_Error is raised.
6132 Both these validity checks may be turned off using switch @option{-gnatVD}.
6133 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6134 switch @option{-gnatVd} will leave the checks turned on.
6135 Switch @option{-gnatVD} should be used only if you are sure that all such
6136 expressions have valid values. If you use this switch and invalid values
6137 are present, then the program is erroneous, and wild jumps or memory
6138 overwriting may occur.
6141 @emph{Validity checks for elementary components.}
6142 @cindex @option{-gnatVe} (@command{gcc})
6143 In the absence of this switch, assignments to record or array components are
6144 not validity checked, even if validity checks for assignments generally
6145 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6146 require valid data, but assignment of individual components does. So for
6147 example, there is a difference between copying the elements of an array with a
6148 slice assignment, compared to assigning element by element in a loop. This
6149 switch allows you to turn off validity checking for components, even when they
6150 are assigned component by component.
6153 @emph{Validity checks for floating-point values.}
6154 @cindex @option{-gnatVf} (@command{gcc})
6155 In the absence of this switch, validity checking occurs only for discrete
6156 values. If @option{-gnatVf} is specified, then validity checking also applies
6157 for floating-point values, and NaNs and infinities are considered invalid,
6158 as well as out of range values for constrained types. Note that this means
6159 that standard IEEE infinity mode is not allowed. The exact contexts
6160 in which floating-point values are checked depends on the setting of other
6161 options. For example,
6162 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6163 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6164 (the order does not matter) specifies that floating-point parameters of mode
6165 @code{in} should be validity checked.
6168 @emph{Validity checks for @code{in} mode parameters}
6169 @cindex @option{-gnatVi} (@command{gcc})
6170 Arguments for parameters of mode @code{in} are validity checked in function
6171 and procedure calls at the point of call.
6174 @emph{Validity checks for @code{in out} mode parameters.}
6175 @cindex @option{-gnatVm} (@command{gcc})
6176 Arguments for parameters of mode @code{in out} are validity checked in
6177 procedure calls at the point of call. The @code{'m'} here stands for
6178 modify, since this concerns parameters that can be modified by the call.
6179 Note that there is no specific option to test @code{out} parameters,
6180 but any reference within the subprogram will be tested in the usual
6181 manner, and if an invalid value is copied back, any reference to it
6182 will be subject to validity checking.
6185 @emph{No validity checks.}
6186 @cindex @option{-gnatVn} (@command{gcc})
6187 This switch turns off all validity checking, including the default checking
6188 for case statements and left hand side subscripts. Note that the use of
6189 the switch @option{-gnatp} suppresses all run-time checks, including
6190 validity checks, and thus implies @option{-gnatVn}. When this switch
6191 is used, it cancels any other @option{-gnatV} previously issued.
6194 @emph{Validity checks for operator and attribute operands.}
6195 @cindex @option{-gnatVo} (@command{gcc})
6196 Arguments for predefined operators and attributes are validity checked.
6197 This includes all operators in package @code{Standard},
6198 the shift operators defined as intrinsic in package @code{Interfaces}
6199 and operands for attributes such as @code{Pos}. Checks are also made
6200 on individual component values for composite comparisons, and on the
6201 expressions in type conversions and qualified expressions. Checks are
6202 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6205 @emph{Validity checks for parameters.}
6206 @cindex @option{-gnatVp} (@command{gcc})
6207 This controls the treatment of parameters within a subprogram (as opposed
6208 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6209 of parameters on a call. If either of these call options is used, then
6210 normally an assumption is made within a subprogram that the input arguments
6211 have been validity checking at the point of call, and do not need checking
6212 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6213 is not made, and parameters are not assumed to be valid, so their validity
6214 will be checked (or rechecked) within the subprogram.
6217 @emph{Validity checks for function returns.}
6218 @cindex @option{-gnatVr} (@command{gcc})
6219 The expression in @code{return} statements in functions is validity
6223 @emph{Validity checks for subscripts.}
6224 @cindex @option{-gnatVs} (@command{gcc})
6225 All subscripts expressions are checked for validity, whether they appear
6226 on the right side or left side (in default mode only left side subscripts
6227 are validity checked).
6230 @emph{Validity checks for tests.}
6231 @cindex @option{-gnatVt} (@command{gcc})
6232 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6233 statements are checked, as well as guard expressions in entry calls.
6238 The @option{-gnatV} switch may be followed by
6239 ^a string of letters^a list of options^
6240 to turn on a series of validity checking options.
6242 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6243 specifies that in addition to the default validity checking, copies and
6244 function return expressions are to be validity checked.
6245 In order to make it easier
6246 to specify the desired combination of effects,
6248 the upper case letters @code{CDFIMORST} may
6249 be used to turn off the corresponding lower case option.
6252 the prefix @code{NO} on an option turns off the corresponding validity
6255 @item @code{NOCOPIES}
6256 @item @code{NODEFAULT}
6257 @item @code{NOFLOATS}
6258 @item @code{NOIN_PARAMS}
6259 @item @code{NOMOD_PARAMS}
6260 @item @code{NOOPERANDS}
6261 @item @code{NORETURNS}
6262 @item @code{NOSUBSCRIPTS}
6263 @item @code{NOTESTS}
6267 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6268 turns on all validity checking options except for
6269 checking of @code{@b{in out}} procedure arguments.
6271 The specification of additional validity checking generates extra code (and
6272 in the case of @option{-gnatVa} the code expansion can be substantial).
6273 However, these additional checks can be very useful in detecting
6274 uninitialized variables, incorrect use of unchecked conversion, and other
6275 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6276 is useful in conjunction with the extra validity checking, since this
6277 ensures that wherever possible uninitialized variables have invalid values.
6279 See also the pragma @code{Validity_Checks} which allows modification of
6280 the validity checking mode at the program source level, and also allows for
6281 temporary disabling of validity checks.
6283 @node Style Checking
6284 @subsection Style Checking
6285 @findex Style checking
6288 The @option{-gnaty^x^(option,option,@dots{})^} switch
6289 @cindex @option{-gnaty} (@command{gcc})
6290 causes the compiler to
6291 enforce specified style rules. A limited set of style rules has been used
6292 in writing the GNAT sources themselves. This switch allows user programs
6293 to activate all or some of these checks. If the source program fails a
6294 specified style check, an appropriate message is given, preceded by
6295 the character sequence ``(style)''. This message does not prevent
6296 successful compilation (unless the @option{-gnatwe} switch is used).
6298 Note that this is by no means intended to be a general facility for
6299 checking arbitrary coding standards. It is simply an embedding of the
6300 style rules we have chosen for the GNAT sources. If you are starting
6301 a project which does not have established style standards, you may
6302 find it useful to adopt the entire set of GNAT coding standards, or
6303 some subset of them. If you already have an established set of coding
6304 standards, then it may be that selected style checking options do
6305 indeed correspond to choices you have made, but for general checking
6306 of an existing set of coding rules, you should look to the gnatcheck
6307 tool, which is designed for that purpose.
6310 @code{(option,option,@dots{})} is a sequence of keywords
6313 The string @var{x} is a sequence of letters or digits
6315 indicating the particular style
6316 checks to be performed. The following checks are defined:
6321 @emph{Specify indentation level.}
6322 If a digit from 1-9 appears
6323 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6324 then proper indentation is checked, with the digit indicating the
6325 indentation level required. A value of zero turns off this style check.
6326 The general style of required indentation is as specified by
6327 the examples in the Ada Reference Manual. Full line comments must be
6328 aligned with the @code{--} starting on a column that is a multiple of
6329 the alignment level, or they may be aligned the same way as the following
6330 non-blank line (this is useful when full line comments appear in the middle
6334 @emph{Check attribute casing.}
6335 Attribute names, including the case of keywords such as @code{digits}
6336 used as attributes names, must be written in mixed case, that is, the
6337 initial letter and any letter following an underscore must be uppercase.
6338 All other letters must be lowercase.
6340 @item ^A^ARRAY_INDEXES^
6341 @emph{Use of array index numbers in array attributes.}
6342 When using the array attributes First, Last, Range,
6343 or Length, the index number must be omitted for one-dimensional arrays
6344 and is required for multi-dimensional arrays.
6347 @emph{Blanks not allowed at statement end.}
6348 Trailing blanks are not allowed at the end of statements. The purpose of this
6349 rule, together with h (no horizontal tabs), is to enforce a canonical format
6350 for the use of blanks to separate source tokens.
6352 @item ^B^BOOLEAN_OPERATORS^
6353 @emph{Check Boolean operators.}
6354 The use of AND/OR operators is not permitted except in the cases of modular
6355 operands, array operands, and simple stand-alone boolean variables or
6356 boolean constants. In all other cases @code{and then}/@code{or else} are
6360 @emph{Check comments, double space.}
6361 Comments must meet the following set of rules:
6366 The ``@code{--}'' that starts the column must either start in column one,
6367 or else at least one blank must precede this sequence.
6370 Comments that follow other tokens on a line must have at least one blank
6371 following the ``@code{--}'' at the start of the comment.
6374 Full line comments must have at least two blanks following the
6375 ``@code{--}'' that starts the comment, with the following exceptions.
6378 A line consisting only of the ``@code{--}'' characters, possibly preceded
6379 by blanks is permitted.
6382 A comment starting with ``@code{--x}'' where @code{x} is a special character
6384 This allows proper processing of the output generated by specialized tools
6385 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6387 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6388 special character is defined as being in one of the ASCII ranges
6389 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6390 Note that this usage is not permitted
6391 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6394 A line consisting entirely of minus signs, possibly preceded by blanks, is
6395 permitted. This allows the construction of box comments where lines of minus
6396 signs are used to form the top and bottom of the box.
6399 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6400 least one blank follows the initial ``@code{--}''. Together with the preceding
6401 rule, this allows the construction of box comments, as shown in the following
6404 ---------------------------
6405 -- This is a box comment --
6406 -- with two text lines. --
6407 ---------------------------
6412 @emph{Check comments, single space.}
6413 This is identical to @code{^c^COMMENTS^} except that only one space
6414 is required following the @code{--} of a comment instead of two.
6416 @item ^d^DOS_LINE_ENDINGS^
6417 @emph{Check no DOS line terminators present.}
6418 All lines must be terminated by a single ASCII.LF
6419 character (in particular the DOS line terminator sequence CR/LF is not
6423 @emph{Check end/exit labels.}
6424 Optional labels on @code{end} statements ending subprograms and on
6425 @code{exit} statements exiting named loops, are required to be present.
6428 @emph{No form feeds or vertical tabs.}
6429 Neither form feeds nor vertical tab characters are permitted
6433 @emph{GNAT style mode.}
6434 The set of style check switches is set to match that used by the GNAT sources.
6435 This may be useful when developing code that is eventually intended to be
6436 incorporated into GNAT. For further details, see GNAT sources.
6439 @emph{No horizontal tabs.}
6440 Horizontal tab characters are not permitted in the source text.
6441 Together with the b (no blanks at end of line) check, this
6442 enforces a canonical form for the use of blanks to separate
6446 @emph{Check if-then layout.}
6447 The keyword @code{then} must appear either on the same
6448 line as corresponding @code{if}, or on a line on its own, lined
6449 up under the @code{if} with at least one non-blank line in between
6450 containing all or part of the condition to be tested.
6453 @emph{check mode IN keywords.}
6454 Mode @code{in} (the default mode) is not
6455 allowed to be given explicitly. @code{in out} is fine,
6456 but not @code{in} on its own.
6459 @emph{Check keyword casing.}
6460 All keywords must be in lower case (with the exception of keywords
6461 such as @code{digits} used as attribute names to which this check
6465 @emph{Check layout.}
6466 Layout of statement and declaration constructs must follow the
6467 recommendations in the Ada Reference Manual, as indicated by the
6468 form of the syntax rules. For example an @code{else} keyword must
6469 be lined up with the corresponding @code{if} keyword.
6471 There are two respects in which the style rule enforced by this check
6472 option are more liberal than those in the Ada Reference Manual. First
6473 in the case of record declarations, it is permissible to put the
6474 @code{record} keyword on the same line as the @code{type} keyword, and
6475 then the @code{end} in @code{end record} must line up under @code{type}.
6476 This is also permitted when the type declaration is split on two lines.
6477 For example, any of the following three layouts is acceptable:
6479 @smallexample @c ada
6502 Second, in the case of a block statement, a permitted alternative
6503 is to put the block label on the same line as the @code{declare} or
6504 @code{begin} keyword, and then line the @code{end} keyword up under
6505 the block label. For example both the following are permitted:
6507 @smallexample @c ada
6525 The same alternative format is allowed for loops. For example, both of
6526 the following are permitted:
6528 @smallexample @c ada
6530 Clear : while J < 10 loop
6541 @item ^Lnnn^MAX_NESTING=nnn^
6542 @emph{Set maximum nesting level.}
6543 The maximum level of nesting of constructs (including subprograms, loops,
6544 blocks, packages, and conditionals) may not exceed the given value
6545 @option{nnn}. A value of zero disconnects this style check.
6547 @item ^m^LINE_LENGTH^
6548 @emph{Check maximum line length.}
6549 The length of source lines must not exceed 79 characters, including
6550 any trailing blanks. The value of 79 allows convenient display on an
6551 80 character wide device or window, allowing for possible special
6552 treatment of 80 character lines. Note that this count is of
6553 characters in the source text. This means that a tab character counts
6554 as one character in this count but a wide character sequence counts as
6555 a single character (however many bytes are needed in the encoding).
6557 @item ^Mnnn^MAX_LENGTH=nnn^
6558 @emph{Set maximum line length.}
6559 The length of lines must not exceed the
6560 given value @option{nnn}. The maximum value that can be specified is 32767.
6562 @item ^n^STANDARD_CASING^
6563 @emph{Check casing of entities in Standard.}
6564 Any identifier from Standard must be cased
6565 to match the presentation in the Ada Reference Manual (for example,
6566 @code{Integer} and @code{ASCII.NUL}).
6569 @emph{Turn off all style checks.}
6570 All style check options are turned off.
6572 @item ^o^ORDERED_SUBPROGRAMS^
6573 @emph{Check order of subprogram bodies.}
6574 All subprogram bodies in a given scope
6575 (e.g.@: a package body) must be in alphabetical order. The ordering
6576 rule uses normal Ada rules for comparing strings, ignoring casing
6577 of letters, except that if there is a trailing numeric suffix, then
6578 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6581 @item ^O^OVERRIDING_INDICATORS^
6582 @emph{Check that overriding subprograms are explicitly marked as such.}
6583 The declaration of a primitive operation of a type extension that overrides
6584 an inherited operation must carry an overriding indicator.
6587 @emph{Check pragma casing.}
6588 Pragma names must be written in mixed case, that is, the
6589 initial letter and any letter following an underscore must be uppercase.
6590 All other letters must be lowercase.
6592 @item ^r^REFERENCES^
6593 @emph{Check references.}
6594 All identifier references must be cased in the same way as the
6595 corresponding declaration. No specific casing style is imposed on
6596 identifiers. The only requirement is for consistency of references
6600 @emph{Check separate specs.}
6601 Separate declarations (``specs'') are required for subprograms (a
6602 body is not allowed to serve as its own declaration). The only
6603 exception is that parameterless library level procedures are
6604 not required to have a separate declaration. This exception covers
6605 the most frequent form of main program procedures.
6607 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6608 @emph{Check no statements after @code{then}/@code{else}.}
6609 No statements are allowed
6610 on the same line as a @code{then} or @code{else} keyword following the
6611 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6612 affected, and a special exception allows a pragma to appear after @code{else}.
6615 @emph{Check token spacing.}
6616 The following token spacing rules are enforced:
6621 The keywords @code{abs} and @code{not} must be followed by a space.
6624 The token @code{=>} must be surrounded by spaces.
6627 The token @code{<>} must be preceded by a space or a left parenthesis.
6630 Binary operators other than @code{**} must be surrounded by spaces.
6631 There is no restriction on the layout of the @code{**} binary operator.
6634 Colon must be surrounded by spaces.
6637 Colon-equal (assignment, initialization) must be surrounded by spaces.
6640 Comma must be the first non-blank character on the line, or be
6641 immediately preceded by a non-blank character, and must be followed
6645 If the token preceding a left parenthesis ends with a letter or digit, then
6646 a space must separate the two tokens.
6649 if the token following a right parenthesis starts with a letter or digit, then
6650 a space must separate the two tokens.
6653 A right parenthesis must either be the first non-blank character on
6654 a line, or it must be preceded by a non-blank character.
6657 A semicolon must not be preceded by a space, and must not be followed by
6658 a non-blank character.
6661 A unary plus or minus may not be followed by a space.
6664 A vertical bar must be surrounded by spaces.
6667 @item ^u^UNNECESSARY_BLANK_LINES^
6668 @emph{Check unnecessary blank lines.}
6669 Unnecessary blank lines are not allowed. A blank line is considered
6670 unnecessary if it appears at the end of the file, or if more than
6671 one blank line occurs in sequence.
6673 @item ^x^XTRA_PARENS^
6674 @emph{Check extra parentheses.}
6675 Unnecessary extra level of parentheses (C-style) are not allowed
6676 around conditions in @code{if} statements, @code{while} statements and
6677 @code{exit} statements.
6679 @item ^y^ALL_BUILTIN^
6680 @emph{Set all standard style check options}
6681 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6682 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6683 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6684 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6688 @emph{Remove style check options}
6689 This causes any subsequent options in the string to act as canceling the
6690 corresponding style check option. To cancel maximum nesting level control,
6691 use @option{L} parameter witout any integer value after that, because any
6692 digit following @option{-} in the parameter string of the @option{-gnaty}
6693 option will be threated as canceling indentation check. The same is true
6694 for @option{M} parameter. @option{y} and @option{N} parameters are not
6695 allowed after @option{-}.
6698 This causes any subsequent options in the string to enable the corresponding
6699 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6705 @emph{Removing style check options}
6706 If the name of a style check is preceded by @option{NO} then the corresponding
6707 style check is turned off. For example @option{NOCOMMENTS} turns off style
6708 checking for comments.
6713 In the above rules, appearing in column one is always permitted, that is,
6714 counts as meeting either a requirement for a required preceding space,
6715 or as meeting a requirement for no preceding space.
6717 Appearing at the end of a line is also always permitted, that is, counts
6718 as meeting either a requirement for a following space, or as meeting
6719 a requirement for no following space.
6722 If any of these style rules is violated, a message is generated giving
6723 details on the violation. The initial characters of such messages are
6724 always ``@code{(style)}''. Note that these messages are treated as warning
6725 messages, so they normally do not prevent the generation of an object
6726 file. The @option{-gnatwe} switch can be used to treat warning messages,
6727 including style messages, as fatal errors.
6731 @option{-gnaty} on its own (that is not
6732 followed by any letters or digits) is equivalent
6733 to the use of @option{-gnatyy} as described above, that is all
6734 built-in standard style check options are enabled.
6738 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6739 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6740 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6750 clears any previously set style checks.
6752 @node Run-Time Checks
6753 @subsection Run-Time Checks
6754 @cindex Division by zero
6755 @cindex Access before elaboration
6756 @cindex Checks, division by zero
6757 @cindex Checks, access before elaboration
6758 @cindex Checks, stack overflow checking
6761 By default, the following checks are suppressed: integer overflow
6762 checks, stack overflow checks, and checks for access before
6763 elaboration on subprogram calls. All other checks, including range
6764 checks and array bounds checks, are turned on by default. The
6765 following @command{gcc} switches refine this default behavior.
6770 @cindex @option{-gnatp} (@command{gcc})
6771 @cindex Suppressing checks
6772 @cindex Checks, suppressing
6774 This switch causes the unit to be compiled
6775 as though @code{pragma Suppress (All_checks)}
6776 had been present in the source. Validity checks are also eliminated (in
6777 other words @option{-gnatp} also implies @option{-gnatVn}.
6778 Use this switch to improve the performance
6779 of the code at the expense of safety in the presence of invalid data or
6782 Note that when checks are suppressed, the compiler is allowed, but not
6783 required, to omit the checking code. If the run-time cost of the
6784 checking code is zero or near-zero, the compiler will generate it even
6785 if checks are suppressed. In particular, if the compiler can prove
6786 that a certain check will necessarily fail, it will generate code to
6787 do an unconditional ``raise'', even if checks are suppressed. The
6788 compiler warns in this case. Another case in which checks may not be
6789 eliminated is when they are embedded in certain run time routines such
6790 as math library routines.
6792 Of course, run-time checks are omitted whenever the compiler can prove
6793 that they will not fail, whether or not checks are suppressed.
6795 Note that if you suppress a check that would have failed, program
6796 execution is erroneous, which means the behavior is totally
6797 unpredictable. The program might crash, or print wrong answers, or
6798 do anything else. It might even do exactly what you wanted it to do
6799 (and then it might start failing mysteriously next week or next
6800 year). The compiler will generate code based on the assumption that
6801 the condition being checked is true, which can result in disaster if
6802 that assumption is wrong.
6804 The @option{-gnatp} switch has no effect if a subsequent
6805 @option{-gnat-p} switch appears.
6808 @cindex @option{-gnat-p} (@command{gcc})
6809 @cindex Suppressing checks
6810 @cindex Checks, suppressing
6812 This switch cancels the effect of a previous @option{gnatp} switch.
6815 @cindex @option{-gnato} (@command{gcc})
6816 @cindex Overflow checks
6817 @cindex Check, overflow
6818 Enables overflow checking for integer operations.
6819 This causes GNAT to generate slower and larger executable
6820 programs by adding code to check for overflow (resulting in raising
6821 @code{Constraint_Error} as required by standard Ada
6822 semantics). These overflow checks correspond to situations in which
6823 the true value of the result of an operation may be outside the base
6824 range of the result type. The following example shows the distinction:
6826 @smallexample @c ada
6827 X1 : Integer := "Integer'Last";
6828 X2 : Integer range 1 .. 5 := "5";
6829 X3 : Integer := "Integer'Last";
6830 X4 : Integer range 1 .. 5 := "5";
6831 F : Float := "2.0E+20";
6840 Note that if explicit values are assigned at compile time, the
6841 compiler may be able to detect overflow at compile time, in which case
6842 no actual run-time checking code is required, and Constraint_Error
6843 will be raised unconditionally, with or without
6844 @option{-gnato}. That's why the assigned values in the above fragment
6845 are in quotes, the meaning is "assign a value not known to the
6846 compiler that happens to be equal to ...". The remaining discussion
6847 assumes that the compiler cannot detect the values at compile time.
6849 Here the first addition results in a value that is outside the base range
6850 of Integer, and hence requires an overflow check for detection of the
6851 constraint error. Thus the first assignment to @code{X1} raises a
6852 @code{Constraint_Error} exception only if @option{-gnato} is set.
6854 The second increment operation results in a violation of the explicit
6855 range constraint; such range checks are performed by default, and are
6856 unaffected by @option{-gnato}.
6858 The two conversions of @code{F} both result in values that are outside
6859 the base range of type @code{Integer} and thus will raise
6860 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6861 The fact that the result of the second conversion is assigned to
6862 variable @code{X4} with a restricted range is irrelevant, since the problem
6863 is in the conversion, not the assignment.
6865 Basically the rule is that in the default mode (@option{-gnato} not
6866 used), the generated code assures that all integer variables stay
6867 within their declared ranges, or within the base range if there is
6868 no declared range. This prevents any serious problems like indexes
6869 out of range for array operations.
6871 What is not checked in default mode is an overflow that results in
6872 an in-range, but incorrect value. In the above example, the assignments
6873 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6874 range of the target variable, but the result is wrong in the sense that
6875 it is too large to be represented correctly. Typically the assignment
6876 to @code{X1} will result in wrap around to the largest negative number.
6877 The conversions of @code{F} will result in some @code{Integer} value
6878 and if that integer value is out of the @code{X4} range then the
6879 subsequent assignment would generate an exception.
6881 @findex Machine_Overflows
6882 Note that the @option{-gnato} switch does not affect the code generated
6883 for any floating-point operations; it applies only to integer
6885 For floating-point, GNAT has the @code{Machine_Overflows}
6886 attribute set to @code{False} and the normal mode of operation is to
6887 generate IEEE NaN and infinite values on overflow or invalid operations
6888 (such as dividing 0.0 by 0.0).
6890 The reason that we distinguish overflow checking from other kinds of
6891 range constraint checking is that a failure of an overflow check, unlike
6892 for example the failure of a range check, can result in an incorrect
6893 value, but cannot cause random memory destruction (like an out of range
6894 subscript), or a wild jump (from an out of range case value). Overflow
6895 checking is also quite expensive in time and space, since in general it
6896 requires the use of double length arithmetic.
6898 Note again that @option{-gnato} is off by default, so overflow checking is
6899 not performed in default mode. This means that out of the box, with the
6900 default settings, GNAT does not do all the checks expected from the
6901 language description in the Ada Reference Manual. If you want all constraint
6902 checks to be performed, as described in this Manual, then you must
6903 explicitly use the -gnato switch either on the @command{gnatmake} or
6904 @command{gcc} command.
6907 @cindex @option{-gnatE} (@command{gcc})
6908 @cindex Elaboration checks
6909 @cindex Check, elaboration
6910 Enables dynamic checks for access-before-elaboration
6911 on subprogram calls and generic instantiations.
6912 Note that @option{-gnatE} is not necessary for safety, because in the
6913 default mode, GNAT ensures statically that the checks would not fail.
6914 For full details of the effect and use of this switch,
6915 @xref{Compiling Using gcc}.
6918 @cindex @option{-fstack-check} (@command{gcc})
6919 @cindex Stack Overflow Checking
6920 @cindex Checks, stack overflow checking
6921 Activates stack overflow checking. For full details of the effect and use of
6922 this switch see @ref{Stack Overflow Checking}.
6927 The setting of these switches only controls the default setting of the
6928 checks. You may modify them using either @code{Suppress} (to remove
6929 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6932 @node Using gcc for Syntax Checking
6933 @subsection Using @command{gcc} for Syntax Checking
6936 @cindex @option{-gnats} (@command{gcc})
6940 The @code{s} stands for ``syntax''.
6943 Run GNAT in syntax checking only mode. For
6944 example, the command
6947 $ gcc -c -gnats x.adb
6951 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6952 series of files in a single command
6954 , and can use wild cards to specify such a group of files.
6955 Note that you must specify the @option{-c} (compile
6956 only) flag in addition to the @option{-gnats} flag.
6959 You may use other switches in conjunction with @option{-gnats}. In
6960 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6961 format of any generated error messages.
6963 When the source file is empty or contains only empty lines and/or comments,
6964 the output is a warning:
6967 $ gcc -c -gnats -x ada toto.txt
6968 toto.txt:1:01: warning: empty file, contains no compilation units
6972 Otherwise, the output is simply the error messages, if any. No object file or
6973 ALI file is generated by a syntax-only compilation. Also, no units other
6974 than the one specified are accessed. For example, if a unit @code{X}
6975 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6976 check only mode does not access the source file containing unit
6979 @cindex Multiple units, syntax checking
6980 Normally, GNAT allows only a single unit in a source file. However, this
6981 restriction does not apply in syntax-check-only mode, and it is possible
6982 to check a file containing multiple compilation units concatenated
6983 together. This is primarily used by the @code{gnatchop} utility
6984 (@pxref{Renaming Files Using gnatchop}).
6987 @node Using gcc for Semantic Checking
6988 @subsection Using @command{gcc} for Semantic Checking
6991 @cindex @option{-gnatc} (@command{gcc})
6995 The @code{c} stands for ``check''.
6997 Causes the compiler to operate in semantic check mode,
6998 with full checking for all illegalities specified in the
6999 Ada Reference Manual, but without generation of any object code
7000 (no object file is generated).
7002 Because dependent files must be accessed, you must follow the GNAT
7003 semantic restrictions on file structuring to operate in this mode:
7007 The needed source files must be accessible
7008 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7011 Each file must contain only one compilation unit.
7014 The file name and unit name must match (@pxref{File Naming Rules}).
7017 The output consists of error messages as appropriate. No object file is
7018 generated. An @file{ALI} file is generated for use in the context of
7019 cross-reference tools, but this file is marked as not being suitable
7020 for binding (since no object file is generated).
7021 The checking corresponds exactly to the notion of
7022 legality in the Ada Reference Manual.
7024 Any unit can be compiled in semantics-checking-only mode, including
7025 units that would not normally be compiled (subunits,
7026 and specifications where a separate body is present).
7029 @node Compiling Different Versions of Ada
7030 @subsection Compiling Different Versions of Ada
7033 The switches described in this section allow you to explicitly specify
7034 the version of the Ada language that your programs are written in.
7035 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
7036 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
7037 indicate Ada 83 compatibility mode.
7040 @cindex Compatibility with Ada 83
7042 @item -gnat83 (Ada 83 Compatibility Mode)
7043 @cindex @option{-gnat83} (@command{gcc})
7044 @cindex ACVC, Ada 83 tests
7048 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7049 specifies that the program is to be compiled in Ada 83 mode. With
7050 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7051 semantics where this can be done easily.
7052 It is not possible to guarantee this switch does a perfect
7053 job; some subtle tests, such as are
7054 found in earlier ACVC tests (and that have been removed from the ACATS suite
7055 for Ada 95), might not compile correctly.
7056 Nevertheless, this switch may be useful in some circumstances, for example
7057 where, due to contractual reasons, existing code needs to be maintained
7058 using only Ada 83 features.
7060 With few exceptions (most notably the need to use @code{<>} on
7061 @cindex Generic formal parameters
7062 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7063 reserved words, and the use of packages
7064 with optional bodies), it is not necessary to specify the
7065 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7066 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7067 a correct Ada 83 program is usually also a correct program
7068 in these later versions of the language standard.
7069 For further information, please refer to @ref{Compatibility and Porting Guide}.
7071 @item -gnat95 (Ada 95 mode)
7072 @cindex @option{-gnat95} (@command{gcc})
7076 This switch directs the compiler to implement the Ada 95 version of the
7078 Since Ada 95 is almost completely upwards
7079 compatible with Ada 83, Ada 83 programs may generally be compiled using
7080 this switch (see the description of the @option{-gnat83} switch for further
7081 information about Ada 83 mode).
7082 If an Ada 2005 program is compiled in Ada 95 mode,
7083 uses of the new Ada 2005 features will cause error
7084 messages or warnings.
7086 This switch also can be used to cancel the effect of a previous
7087 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7088 switch earlier in the command line.
7090 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7091 @cindex @option{-gnat05} (@command{gcc})
7092 @cindex @option{-gnat2005} (@command{gcc})
7093 @cindex Ada 2005 mode
7096 This switch directs the compiler to implement the Ada 2005 version of the
7097 language, as documented in the official Ada standards document.
7098 Since Ada 2005 is almost completely upwards
7099 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7100 may generally be compiled using this switch (see the description of the
7101 @option{-gnat83} and @option{-gnat95} switches for further
7105 Note that even though Ada 2005 is the current official version of the
7106 language, GNAT still compiles in Ada 95 mode by default, so if you are
7107 using Ada 2005 features in your program, you must use this switch (or
7108 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7111 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7112 @cindex @option{-gnat12} (@command{gcc})
7113 @cindex @option{-gnat2012} (@command{gcc})
7114 @cindex Ada 2012 mode
7117 This switch directs the compiler to implement the Ada 2012 version of the
7119 Since Ada 2012 is almost completely upwards
7120 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7121 Ada 83 and Ada 95 programs
7122 may generally be compiled using this switch (see the description of the
7123 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7124 for further information).
7126 For information about the approved ``Ada Issues'' that have been incorporated
7127 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7128 Included with GNAT releases is a file @file{features-ada12} that describes
7129 the set of implemented Ada 2012 features.
7131 @item -gnatX (Enable GNAT Extensions)
7132 @cindex @option{-gnatX} (@command{gcc})
7133 @cindex Ada language extensions
7134 @cindex GNAT extensions
7137 This switch directs the compiler to implement the latest version of the
7138 language (currently Ada 2012) and also to enable certain GNAT implementation
7139 extensions that are not part of any Ada standard. For a full list of these
7140 extensions, see the GNAT reference manual.
7144 @node Character Set Control
7145 @subsection Character Set Control
7147 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7148 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7151 Normally GNAT recognizes the Latin-1 character set in source program
7152 identifiers, as described in the Ada Reference Manual.
7154 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7155 single character ^^or word^ indicating the character set, as follows:
7159 ISO 8859-1 (Latin-1) identifiers
7162 ISO 8859-2 (Latin-2) letters allowed in identifiers
7165 ISO 8859-3 (Latin-3) letters allowed in identifiers
7168 ISO 8859-4 (Latin-4) letters allowed in identifiers
7171 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7174 ISO 8859-15 (Latin-9) letters allowed in identifiers
7177 IBM PC letters (code page 437) allowed in identifiers
7180 IBM PC letters (code page 850) allowed in identifiers
7182 @item ^f^FULL_UPPER^
7183 Full upper-half codes allowed in identifiers
7186 No upper-half codes allowed in identifiers
7189 Wide-character codes (that is, codes greater than 255)
7190 allowed in identifiers
7193 @xref{Foreign Language Representation}, for full details on the
7194 implementation of these character sets.
7196 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7197 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7198 Specify the method of encoding for wide characters.
7199 @var{e} is one of the following:
7204 Hex encoding (brackets coding also recognized)
7207 Upper half encoding (brackets encoding also recognized)
7210 Shift/JIS encoding (brackets encoding also recognized)
7213 EUC encoding (brackets encoding also recognized)
7216 UTF-8 encoding (brackets encoding also recognized)
7219 Brackets encoding only (default value)
7221 For full details on these encoding
7222 methods see @ref{Wide Character Encodings}.
7223 Note that brackets coding is always accepted, even if one of the other
7224 options is specified, so for example @option{-gnatW8} specifies that both
7225 brackets and UTF-8 encodings will be recognized. The units that are
7226 with'ed directly or indirectly will be scanned using the specified
7227 representation scheme, and so if one of the non-brackets scheme is
7228 used, it must be used consistently throughout the program. However,
7229 since brackets encoding is always recognized, it may be conveniently
7230 used in standard libraries, allowing these libraries to be used with
7231 any of the available coding schemes.
7233 Note that brackets encoding only applies to program text. Within comments,
7234 brackets are considered to be normal graphic characters, and bracket sequences
7235 are never recognized as wide characters.
7237 If no @option{-gnatW?} parameter is present, then the default
7238 representation is normally Brackets encoding only. However, if the
7239 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7240 byte order mark or BOM for UTF-8), then these three characters are
7241 skipped and the default representation for the file is set to UTF-8.
7243 Note that the wide character representation that is specified (explicitly
7244 or by default) for the main program also acts as the default encoding used
7245 for Wide_Text_IO files if not specifically overridden by a WCEM form
7250 When no @option{-gnatW?} is specified, then characters (other than wide
7251 characters represented using brackets notation) are treated as 8-bit
7252 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7253 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7254 characters in the range 16#00#..16#1F# are not accepted in program text
7255 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7256 in program text, but allowed and ignored in comments. Note in particular
7257 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7258 as an end of line in this default mode. If your source program contains
7259 instances of the NEL character used as a line terminator,
7260 you must use UTF-8 encoding for the whole
7261 source program. In default mode, all lines must be ended by a standard
7262 end of line sequence (CR, CR/LF, or LF).
7264 Note that the convention of simply accepting all upper half characters in
7265 comments means that programs that use standard ASCII for program text, but
7266 UTF-8 encoding for comments are accepted in default mode, providing that the
7267 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7268 This is a common mode for many programs with foreign language comments.
7270 @node File Naming Control
7271 @subsection File Naming Control
7274 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7275 @cindex @option{-gnatk} (@command{gcc})
7276 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7277 1-999, indicates the maximum allowable length of a file name (not
7278 including the @file{.ads} or @file{.adb} extension). The default is not
7279 to enable file name krunching.
7281 For the source file naming rules, @xref{File Naming Rules}.
7284 @node Subprogram Inlining Control
7285 @subsection Subprogram Inlining Control
7290 @cindex @option{-gnatn} (@command{gcc})
7292 The @code{n} here is intended to suggest the first syllable of the
7295 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7296 inlining to actually occur, optimization must be enabled. To enable
7297 inlining of subprograms specified by pragma @code{Inline},
7298 you must also specify this switch.
7299 In the absence of this switch, GNAT does not attempt
7300 inlining and does not need to access the bodies of
7301 subprograms for which @code{pragma Inline} is specified if they are not
7302 in the current unit.
7304 If you specify this switch the compiler will access these bodies,
7305 creating an extra source dependency for the resulting object file, and
7306 where possible, the call will be inlined.
7307 For further details on when inlining is possible
7308 see @ref{Inlining of Subprograms}.
7311 @cindex @option{-gnatN} (@command{gcc})
7312 This switch activates front-end inlining which also
7313 generates additional dependencies.
7315 When using a gcc-based back end (in practice this means using any version
7316 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7317 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7318 Historically front end inlining was more extensive than the gcc back end
7319 inlining, but that is no longer the case.
7322 @node Auxiliary Output Control
7323 @subsection Auxiliary Output Control
7327 @cindex @option{-gnatt} (@command{gcc})
7328 @cindex Writing internal trees
7329 @cindex Internal trees, writing to file
7330 Causes GNAT to write the internal tree for a unit to a file (with the
7331 extension @file{.adt}.
7332 This not normally required, but is used by separate analysis tools.
7334 these tools do the necessary compilations automatically, so you should
7335 not have to specify this switch in normal operation.
7336 Note that the combination of switches @option{-gnatct}
7337 generates a tree in the form required by ASIS applications.
7340 @cindex @option{-gnatu} (@command{gcc})
7341 Print a list of units required by this compilation on @file{stdout}.
7342 The listing includes all units on which the unit being compiled depends
7343 either directly or indirectly.
7346 @item -pass-exit-codes
7347 @cindex @option{-pass-exit-codes} (@command{gcc})
7348 If this switch is not used, the exit code returned by @command{gcc} when
7349 compiling multiple files indicates whether all source files have
7350 been successfully used to generate object files or not.
7352 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7353 exit status and allows an integrated development environment to better
7354 react to a compilation failure. Those exit status are:
7358 There was an error in at least one source file.
7360 At least one source file did not generate an object file.
7362 The compiler died unexpectedly (internal error for example).
7364 An object file has been generated for every source file.
7369 @node Debugging Control
7370 @subsection Debugging Control
7374 @cindex Debugging options
7377 @cindex @option{-gnatd} (@command{gcc})
7378 Activate internal debugging switches. @var{x} is a letter or digit, or
7379 string of letters or digits, which specifies the type of debugging
7380 outputs desired. Normally these are used only for internal development
7381 or system debugging purposes. You can find full documentation for these
7382 switches in the body of the @code{Debug} unit in the compiler source
7383 file @file{debug.adb}.
7387 @cindex @option{-gnatG} (@command{gcc})
7388 This switch causes the compiler to generate auxiliary output containing
7389 a pseudo-source listing of the generated expanded code. Like most Ada
7390 compilers, GNAT works by first transforming the high level Ada code into
7391 lower level constructs. For example, tasking operations are transformed
7392 into calls to the tasking run-time routines. A unique capability of GNAT
7393 is to list this expanded code in a form very close to normal Ada source.
7394 This is very useful in understanding the implications of various Ada
7395 usage on the efficiency of the generated code. There are many cases in
7396 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7397 generate a lot of run-time code. By using @option{-gnatG} you can identify
7398 these cases, and consider whether it may be desirable to modify the coding
7399 approach to improve efficiency.
7401 The optional parameter @code{nn} if present after -gnatG specifies an
7402 alternative maximum line length that overrides the normal default of 72.
7403 This value is in the range 40-999999, values less than 40 being silently
7404 reset to 40. The equal sign is optional.
7406 The format of the output is very similar to standard Ada source, and is
7407 easily understood by an Ada programmer. The following special syntactic
7408 additions correspond to low level features used in the generated code that
7409 do not have any exact analogies in pure Ada source form. The following
7410 is a partial list of these special constructions. See the spec
7411 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7413 If the switch @option{-gnatL} is used in conjunction with
7414 @cindex @option{-gnatL} (@command{gcc})
7415 @option{-gnatG}, then the original source lines are interspersed
7416 in the expanded source (as comment lines with the original line number).
7419 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7420 Shows the storage pool being used for an allocator.
7422 @item at end @var{procedure-name};
7423 Shows the finalization (cleanup) procedure for a scope.
7425 @item (if @var{expr} then @var{expr} else @var{expr})
7426 Conditional expression equivalent to the @code{x?y:z} construction in C.
7428 @item @var{target}^^^(@var{source})
7429 A conversion with floating-point truncation instead of rounding.
7431 @item @var{target}?(@var{source})
7432 A conversion that bypasses normal Ada semantic checking. In particular
7433 enumeration types and fixed-point types are treated simply as integers.
7435 @item @var{target}?^^^(@var{source})
7436 Combines the above two cases.
7438 @item @var{x} #/ @var{y}
7439 @itemx @var{x} #mod @var{y}
7440 @itemx @var{x} #* @var{y}
7441 @itemx @var{x} #rem @var{y}
7442 A division or multiplication of fixed-point values which are treated as
7443 integers without any kind of scaling.
7445 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7446 Shows the storage pool associated with a @code{free} statement.
7448 @item [subtype or type declaration]
7449 Used to list an equivalent declaration for an internally generated
7450 type that is referenced elsewhere in the listing.
7452 @c @item freeze @var{type-name} @ovar{actions}
7453 @c Expanding @ovar macro inline (explanation in macro def comments)
7454 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7455 Shows the point at which @var{type-name} is frozen, with possible
7456 associated actions to be performed at the freeze point.
7458 @item reference @var{itype}
7459 Reference (and hence definition) to internal type @var{itype}.
7461 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7462 Intrinsic function call.
7464 @item @var{label-name} : label
7465 Declaration of label @var{labelname}.
7467 @item #$ @var{subprogram-name}
7468 An implicit call to a run-time support routine
7469 (to meet the requirement of H.3.1(9) in a
7472 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7473 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7474 @var{expr}, but handled more efficiently).
7476 @item [constraint_error]
7477 Raise the @code{Constraint_Error} exception.
7479 @item @var{expression}'reference
7480 A pointer to the result of evaluating @var{expression}.
7482 @item @var{target-type}!(@var{source-expression})
7483 An unchecked conversion of @var{source-expression} to @var{target-type}.
7485 @item [@var{numerator}/@var{denominator}]
7486 Used to represent internal real literals (that) have no exact
7487 representation in base 2-16 (for example, the result of compile time
7488 evaluation of the expression 1.0/27.0).
7492 @cindex @option{-gnatD} (@command{gcc})
7493 When used in conjunction with @option{-gnatG}, this switch causes
7494 the expanded source, as described above for
7495 @option{-gnatG} to be written to files with names
7496 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7497 instead of to the standard output file. For
7498 example, if the source file name is @file{hello.adb}, then a file
7499 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7500 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7501 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7502 you to do source level debugging using the generated code which is
7503 sometimes useful for complex code, for example to find out exactly
7504 which part of a complex construction raised an exception. This switch
7505 also suppress generation of cross-reference information (see
7506 @option{-gnatx}) since otherwise the cross-reference information
7507 would refer to the @file{^.dg^.DG^} file, which would cause
7508 confusion since this is not the original source file.
7510 Note that @option{-gnatD} actually implies @option{-gnatG}
7511 automatically, so it is not necessary to give both options.
7512 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7514 If the switch @option{-gnatL} is used in conjunction with
7515 @cindex @option{-gnatL} (@command{gcc})
7516 @option{-gnatDG}, then the original source lines are interspersed
7517 in the expanded source (as comment lines with the original line number).
7519 The optional parameter @code{nn} if present after -gnatD specifies an
7520 alternative maximum line length that overrides the normal default of 72.
7521 This value is in the range 40-999999, values less than 40 being silently
7522 reset to 40. The equal sign is optional.
7525 @cindex @option{-gnatr} (@command{gcc})
7526 @cindex pragma Restrictions
7527 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7528 so that violation of restrictions causes warnings rather than illegalities.
7529 This is useful during the development process when new restrictions are added
7530 or investigated. The switch also causes pragma Profile to be treated as
7531 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7532 restriction warnings rather than restrictions.
7535 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7536 @cindex @option{-gnatR} (@command{gcc})
7537 This switch controls output from the compiler of a listing showing
7538 representation information for declared types and objects. For
7539 @option{-gnatR0}, no information is output (equivalent to omitting
7540 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7541 so @option{-gnatR} with no parameter has the same effect), size and alignment
7542 information is listed for declared array and record types. For
7543 @option{-gnatR2}, size and alignment information is listed for all
7544 declared types and objects. Finally @option{-gnatR3} includes symbolic
7545 expressions for values that are computed at run time for
7546 variant records. These symbolic expressions have a mostly obvious
7547 format with #n being used to represent the value of the n'th
7548 discriminant. See source files @file{repinfo.ads/adb} in the
7549 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7550 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7551 the output is to a file with the name @file{^file.rep^file_REP^} where
7552 file is the name of the corresponding source file.
7555 @item /REPRESENTATION_INFO
7556 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7557 This qualifier controls output from the compiler of a listing showing
7558 representation information for declared types and objects. For
7559 @option{/REPRESENTATION_INFO=NONE}, no information is output
7560 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7561 @option{/REPRESENTATION_INFO} without option is equivalent to
7562 @option{/REPRESENTATION_INFO=ARRAYS}.
7563 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7564 information is listed for declared array and record types. For
7565 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7566 is listed for all expression information for values that are computed
7567 at run time for variant records. These symbolic expressions have a mostly
7568 obvious format with #n being used to represent the value of the n'th
7569 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7570 @code{GNAT} sources for full details on the format of
7571 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7572 If _FILE is added at the end of an option
7573 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7574 then the output is to a file with the name @file{file_REP} where
7575 file is the name of the corresponding source file.
7577 Note that it is possible for record components to have zero size. In
7578 this case, the component clause uses an obvious extension of permitted
7579 Ada syntax, for example @code{at 0 range 0 .. -1}.
7581 Representation information requires that code be generated (since it is the
7582 code generator that lays out complex data structures). If an attempt is made
7583 to output representation information when no code is generated, for example
7584 when a subunit is compiled on its own, then no information can be generated
7585 and the compiler outputs a message to this effect.
7588 @cindex @option{-gnatS} (@command{gcc})
7589 The use of the switch @option{-gnatS} for an
7590 Ada compilation will cause the compiler to output a
7591 representation of package Standard in a form very
7592 close to standard Ada. It is not quite possible to
7593 do this entirely in standard Ada (since new
7594 numeric base types cannot be created in standard
7595 Ada), but the output is easily
7596 readable to any Ada programmer, and is useful to
7597 determine the characteristics of target dependent
7598 types in package Standard.
7601 @cindex @option{-gnatx} (@command{gcc})
7602 Normally the compiler generates full cross-referencing information in
7603 the @file{ALI} file. This information is used by a number of tools,
7604 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7605 suppresses this information. This saves some space and may slightly
7606 speed up compilation, but means that these tools cannot be used.
7609 @node Exception Handling Control
7610 @subsection Exception Handling Control
7613 GNAT uses two methods for handling exceptions at run-time. The
7614 @code{setjmp/longjmp} method saves the context when entering
7615 a frame with an exception handler. Then when an exception is
7616 raised, the context can be restored immediately, without the
7617 need for tracing stack frames. This method provides very fast
7618 exception propagation, but introduces significant overhead for
7619 the use of exception handlers, even if no exception is raised.
7621 The other approach is called ``zero cost'' exception handling.
7622 With this method, the compiler builds static tables to describe
7623 the exception ranges. No dynamic code is required when entering
7624 a frame containing an exception handler. When an exception is
7625 raised, the tables are used to control a back trace of the
7626 subprogram invocation stack to locate the required exception
7627 handler. This method has considerably poorer performance for
7628 the propagation of exceptions, but there is no overhead for
7629 exception handlers if no exception is raised. Note that in this
7630 mode and in the context of mixed Ada and C/C++ programming,
7631 to propagate an exception through a C/C++ code, the C/C++ code
7632 must be compiled with the @option{-funwind-tables} GCC's
7635 The following switches may be used to control which of the
7636 two exception handling methods is used.
7642 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7643 This switch causes the setjmp/longjmp run-time (when available) to be used
7644 for exception handling. If the default
7645 mechanism for the target is zero cost exceptions, then
7646 this switch can be used to modify this default, and must be
7647 used for all units in the partition.
7648 This option is rarely used. One case in which it may be
7649 advantageous is if you have an application where exception
7650 raising is common and the overall performance of the
7651 application is improved by favoring exception propagation.
7654 @cindex @option{--RTS=zcx} (@command{gnatmake})
7655 @cindex Zero Cost Exceptions
7656 This switch causes the zero cost approach to be used
7657 for exception handling. If this is the default mechanism for the
7658 target (see below), then this switch is unneeded. If the default
7659 mechanism for the target is setjmp/longjmp exceptions, then
7660 this switch can be used to modify this default, and must be
7661 used for all units in the partition.
7662 This option can only be used if the zero cost approach
7663 is available for the target in use, otherwise it will generate an error.
7667 The same option @option{--RTS} must be used both for @command{gcc}
7668 and @command{gnatbind}. Passing this option to @command{gnatmake}
7669 (@pxref{Switches for gnatmake}) will ensure the required consistency
7670 through the compilation and binding steps.
7672 @node Units to Sources Mapping Files
7673 @subsection Units to Sources Mapping Files
7677 @item -gnatem=@var{path}
7678 @cindex @option{-gnatem} (@command{gcc})
7679 A mapping file is a way to communicate to the compiler two mappings:
7680 from unit names to file names (without any directory information) and from
7681 file names to path names (with full directory information). These mappings
7682 are used by the compiler to short-circuit the path search.
7684 The use of mapping files is not required for correct operation of the
7685 compiler, but mapping files can improve efficiency, particularly when
7686 sources are read over a slow network connection. In normal operation,
7687 you need not be concerned with the format or use of mapping files,
7688 and the @option{-gnatem} switch is not a switch that you would use
7689 explicitly. It is intended primarily for use by automatic tools such as
7690 @command{gnatmake} running under the project file facility. The
7691 description here of the format of mapping files is provided
7692 for completeness and for possible use by other tools.
7694 A mapping file is a sequence of sets of three lines. In each set, the
7695 first line is the unit name, in lower case, with @code{%s} appended
7696 for specs and @code{%b} appended for bodies; the second line is the
7697 file name; and the third line is the path name.
7703 /gnat/project1/sources/main.2.ada
7706 When the switch @option{-gnatem} is specified, the compiler will
7707 create in memory the two mappings from the specified file. If there is
7708 any problem (nonexistent file, truncated file or duplicate entries),
7709 no mapping will be created.
7711 Several @option{-gnatem} switches may be specified; however, only the
7712 last one on the command line will be taken into account.
7714 When using a project file, @command{gnatmake} creates a temporary
7715 mapping file and communicates it to the compiler using this switch.
7719 @node Integrated Preprocessing
7720 @subsection Integrated Preprocessing
7723 GNAT sources may be preprocessed immediately before compilation.
7724 In this case, the actual
7725 text of the source is not the text of the source file, but is derived from it
7726 through a process called preprocessing. Integrated preprocessing is specified
7727 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7728 indicates, through a text file, the preprocessing data to be used.
7729 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7732 Note that when integrated preprocessing is used, the output from the
7733 preprocessor is not written to any external file. Instead it is passed
7734 internally to the compiler. If you need to preserve the result of
7735 preprocessing in a file, then you should use @command{gnatprep}
7736 to perform the desired preprocessing in stand-alone mode.
7739 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7740 used when Integrated Preprocessing is used. The reason is that preprocessing
7741 with another Preprocessing Data file without changing the sources will
7742 not trigger recompilation without this switch.
7745 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7746 always trigger recompilation for sources that are preprocessed,
7747 because @command{gnatmake} cannot compute the checksum of the source after
7751 The actual preprocessing function is described in details in section
7752 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7753 preprocessing is triggered and parameterized.
7757 @item -gnatep=@var{file}
7758 @cindex @option{-gnatep} (@command{gcc})
7759 This switch indicates to the compiler the file name (without directory
7760 information) of the preprocessor data file to use. The preprocessor data file
7761 should be found in the source directories. Note that when the compiler is
7762 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7763 file, if the object directory is not also a source directory, the builder needs
7764 to be called with @option{-x}.
7767 A preprocessing data file is a text file with significant lines indicating
7768 how should be preprocessed either a specific source or all sources not
7769 mentioned in other lines. A significant line is a nonempty, non-comment line.
7770 Comments are similar to Ada comments.
7773 Each significant line starts with either a literal string or the character '*'.
7774 A literal string is the file name (without directory information) of the source
7775 to preprocess. A character '*' indicates the preprocessing for all the sources
7776 that are not specified explicitly on other lines (order of the lines is not
7777 significant). It is an error to have two lines with the same file name or two
7778 lines starting with the character '*'.
7781 After the file name or the character '*', another optional literal string
7782 indicating the file name of the definition file to be used for preprocessing
7783 (@pxref{Form of Definitions File}). The definition files are found by the
7784 compiler in one of the source directories. In some cases, when compiling
7785 a source in a directory other than the current directory, if the definition
7786 file is in the current directory, it may be necessary to add the current
7787 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7788 the compiler would not find the definition file.
7791 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7792 be found. Those ^switches^switches^ are:
7797 Causes both preprocessor lines and the lines deleted by
7798 preprocessing to be replaced by blank lines, preserving the line number.
7799 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7800 it cancels the effect of @option{-c}.
7803 Causes both preprocessor lines and the lines deleted
7804 by preprocessing to be retained as comments marked
7805 with the special string ``@code{--! }''.
7807 @item -Dsymbol=value
7808 Define or redefine a symbol, associated with value. A symbol is an Ada
7809 identifier, or an Ada reserved word, with the exception of @code{if},
7810 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7811 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7812 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7813 same name defined in a definition file.
7816 Causes a sorted list of symbol names and values to be
7817 listed on the standard output file.
7820 Causes undefined symbols to be treated as having the value @code{FALSE}
7822 of a preprocessor test. In the absence of this option, an undefined symbol in
7823 a @code{#if} or @code{#elsif} test will be treated as an error.
7828 Examples of valid lines in a preprocessor data file:
7831 "toto.adb" "prep.def" -u
7832 -- preprocess "toto.adb", using definition file "prep.def",
7833 -- undefined symbol are False.
7836 -- preprocess all other sources without a definition file;
7837 -- suppressed lined are commented; symbol VERSION has the value V101.
7839 "titi.adb" "prep2.def" -s
7840 -- preprocess "titi.adb", using definition file "prep2.def";
7841 -- list all symbols with their values.
7844 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7845 @cindex @option{-gnateD} (@command{gcc})
7846 Define or redefine a preprocessing symbol, associated with value. If no value
7847 is given on the command line, then the value of the symbol is @code{True}.
7848 A symbol is an identifier, following normal Ada (case-insensitive)
7849 rules for its syntax, and value is any sequence (including an empty sequence)
7850 of characters from the set (letters, digits, period, underline).
7851 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7852 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7855 A symbol declared with this ^switch^switch^ on the command line replaces a
7856 symbol with the same name either in a definition file or specified with a
7857 ^switch^switch^ -D in the preprocessor data file.
7860 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7863 When integrated preprocessing is performed and the preprocessor modifies
7864 the source text, write the result of this preprocessing into a file
7865 <source>^.prep^_prep^.
7869 @node Code Generation Control
7870 @subsection Code Generation Control
7874 The GCC technology provides a wide range of target dependent
7875 @option{-m} switches for controlling
7876 details of code generation with respect to different versions of
7877 architectures. This includes variations in instruction sets (e.g.@:
7878 different members of the power pc family), and different requirements
7879 for optimal arrangement of instructions (e.g.@: different members of
7880 the x86 family). The list of available @option{-m} switches may be
7881 found in the GCC documentation.
7883 Use of these @option{-m} switches may in some cases result in improved
7886 The @value{EDITION} technology is tested and qualified without any
7887 @option{-m} switches,
7888 so generally the most reliable approach is to avoid the use of these
7889 switches. However, we generally expect most of these switches to work
7890 successfully with @value{EDITION}, and many customers have reported successful
7891 use of these options.
7893 Our general advice is to avoid the use of @option{-m} switches unless
7894 special needs lead to requirements in this area. In particular,
7895 there is no point in using @option{-m} switches to improve performance
7896 unless you actually see a performance improvement.
7900 @subsection Return Codes
7901 @cindex Return Codes
7902 @cindex @option{/RETURN_CODES=VMS}
7905 On VMS, GNAT compiled programs return POSIX-style codes by default,
7906 e.g.@: @option{/RETURN_CODES=POSIX}.
7908 To enable VMS style return codes, use GNAT BIND and LINK with the option
7909 @option{/RETURN_CODES=VMS}. For example:
7912 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7913 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7917 Programs built with /RETURN_CODES=VMS are suitable to be called in
7918 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7919 are suitable for spawning with appropriate GNAT RTL routines.
7923 @node Search Paths and the Run-Time Library (RTL)
7924 @section Search Paths and the Run-Time Library (RTL)
7927 With the GNAT source-based library system, the compiler must be able to
7928 find source files for units that are needed by the unit being compiled.
7929 Search paths are used to guide this process.
7931 The compiler compiles one source file whose name must be given
7932 explicitly on the command line. In other words, no searching is done
7933 for this file. To find all other source files that are needed (the most
7934 common being the specs of units), the compiler examines the following
7935 directories, in the following order:
7939 The directory containing the source file of the main unit being compiled
7940 (the file name on the command line).
7943 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7944 @command{gcc} command line, in the order given.
7947 @findex ADA_PRJ_INCLUDE_FILE
7948 Each of the directories listed in the text file whose name is given
7949 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7952 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7953 driver when project files are used. It should not normally be set
7957 @findex ADA_INCLUDE_PATH
7958 Each of the directories listed in the value of the
7959 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7961 Construct this value
7962 exactly as the @env{PATH} environment variable: a list of directory
7963 names separated by colons (semicolons when working with the NT version).
7966 Normally, define this value as a logical name containing a comma separated
7967 list of directory names.
7969 This variable can also be defined by means of an environment string
7970 (an argument to the HP C exec* set of functions).
7974 DEFINE ANOTHER_PATH FOO:[BAG]
7975 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7978 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7979 first, followed by the standard Ada
7980 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7981 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7982 (Text_IO, Sequential_IO, etc)
7983 instead of the standard Ada packages. Thus, in order to get the standard Ada
7984 packages by default, ADA_INCLUDE_PATH must be redefined.
7988 The content of the @file{ada_source_path} file which is part of the GNAT
7989 installation tree and is used to store standard libraries such as the
7990 GNAT Run Time Library (RTL) source files.
7992 @ref{Installing a library}
7997 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7998 inhibits the use of the directory
7999 containing the source file named in the command line. You can still
8000 have this directory on your search path, but in this case it must be
8001 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8003 Specifying the switch @option{-nostdinc}
8004 inhibits the search of the default location for the GNAT Run Time
8005 Library (RTL) source files.
8007 The compiler outputs its object files and ALI files in the current
8010 Caution: The object file can be redirected with the @option{-o} switch;
8011 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8012 so the @file{ALI} file will not go to the right place. Therefore, you should
8013 avoid using the @option{-o} switch.
8017 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8018 children make up the GNAT RTL, together with the simple @code{System.IO}
8019 package used in the @code{"Hello World"} example. The sources for these units
8020 are needed by the compiler and are kept together in one directory. Not
8021 all of the bodies are needed, but all of the sources are kept together
8022 anyway. In a normal installation, you need not specify these directory
8023 names when compiling or binding. Either the environment variables or
8024 the built-in defaults cause these files to be found.
8026 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8027 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8028 consisting of child units of @code{GNAT}. This is a collection of generally
8029 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8030 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8032 Besides simplifying access to the RTL, a major use of search paths is
8033 in compiling sources from multiple directories. This can make
8034 development environments much more flexible.
8036 @node Order of Compilation Issues
8037 @section Order of Compilation Issues
8040 If, in our earlier example, there was a spec for the @code{hello}
8041 procedure, it would be contained in the file @file{hello.ads}; yet this
8042 file would not have to be explicitly compiled. This is the result of the
8043 model we chose to implement library management. Some of the consequences
8044 of this model are as follows:
8048 There is no point in compiling specs (except for package
8049 specs with no bodies) because these are compiled as needed by clients. If
8050 you attempt a useless compilation, you will receive an error message.
8051 It is also useless to compile subunits because they are compiled as needed
8055 There are no order of compilation requirements: performing a
8056 compilation never obsoletes anything. The only way you can obsolete
8057 something and require recompilations is to modify one of the
8058 source files on which it depends.
8061 There is no library as such, apart from the ALI files
8062 (@pxref{The Ada Library Information Files}, for information on the format
8063 of these files). For now we find it convenient to create separate ALI files,
8064 but eventually the information therein may be incorporated into the object
8068 When you compile a unit, the source files for the specs of all units
8069 that it @code{with}'s, all its subunits, and the bodies of any generics it
8070 instantiates must be available (reachable by the search-paths mechanism
8071 described above), or you will receive a fatal error message.
8078 The following are some typical Ada compilation command line examples:
8081 @item $ gcc -c xyz.adb
8082 Compile body in file @file{xyz.adb} with all default options.
8085 @item $ gcc -c -O2 -gnata xyz-def.adb
8088 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8091 Compile the child unit package in file @file{xyz-def.adb} with extensive
8092 optimizations, and pragma @code{Assert}/@code{Debug} statements
8095 @item $ gcc -c -gnatc abc-def.adb
8096 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8100 @node Binding Using gnatbind
8101 @chapter Binding Using @code{gnatbind}
8105 * Running gnatbind::
8106 * Switches for gnatbind::
8107 * Command-Line Access::
8108 * Search Paths for gnatbind::
8109 * Examples of gnatbind Usage::
8113 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8114 to bind compiled GNAT objects.
8116 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8117 driver (see @ref{The GNAT Driver and Project Files}).
8119 The @code{gnatbind} program performs four separate functions:
8123 Checks that a program is consistent, in accordance with the rules in
8124 Chapter 10 of the Ada Reference Manual. In particular, error
8125 messages are generated if a program uses inconsistent versions of a
8129 Checks that an acceptable order of elaboration exists for the program
8130 and issues an error message if it cannot find an order of elaboration
8131 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8134 Generates a main program incorporating the given elaboration order.
8135 This program is a small Ada package (body and spec) that
8136 must be subsequently compiled
8137 using the GNAT compiler. The necessary compilation step is usually
8138 performed automatically by @command{gnatlink}. The two most important
8139 functions of this program
8140 are to call the elaboration routines of units in an appropriate order
8141 and to call the main program.
8144 Determines the set of object files required by the given main program.
8145 This information is output in the forms of comments in the generated program,
8146 to be read by the @command{gnatlink} utility used to link the Ada application.
8149 @node Running gnatbind
8150 @section Running @code{gnatbind}
8153 The form of the @code{gnatbind} command is
8156 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8157 @c Expanding @ovar macro inline (explanation in macro def comments)
8158 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8162 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8163 unit body. @code{gnatbind} constructs an Ada
8164 package in two files whose names are
8165 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8166 For example, if given the
8167 parameter @file{hello.ali}, for a main program contained in file
8168 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8169 and @file{b~hello.adb}.
8171 When doing consistency checking, the binder takes into consideration
8172 any source files it can locate. For example, if the binder determines
8173 that the given main program requires the package @code{Pack}, whose
8175 file is @file{pack.ali} and whose corresponding source spec file is
8176 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8177 (using the same search path conventions as previously described for the
8178 @command{gcc} command). If it can locate this source file, it checks that
8180 or source checksums of the source and its references to in @file{ALI} files
8181 match. In other words, any @file{ALI} files that mentions this spec must have
8182 resulted from compiling this version of the source file (or in the case
8183 where the source checksums match, a version close enough that the
8184 difference does not matter).
8186 @cindex Source files, use by binder
8187 The effect of this consistency checking, which includes source files, is
8188 that the binder ensures that the program is consistent with the latest
8189 version of the source files that can be located at bind time. Editing a
8190 source file without compiling files that depend on the source file cause
8191 error messages to be generated by the binder.
8193 For example, suppose you have a main program @file{hello.adb} and a
8194 package @code{P}, from file @file{p.ads} and you perform the following
8199 Enter @code{gcc -c hello.adb} to compile the main program.
8202 Enter @code{gcc -c p.ads} to compile package @code{P}.
8205 Edit file @file{p.ads}.
8208 Enter @code{gnatbind hello}.
8212 At this point, the file @file{p.ali} contains an out-of-date time stamp
8213 because the file @file{p.ads} has been edited. The attempt at binding
8214 fails, and the binder generates the following error messages:
8217 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8218 error: "p.ads" has been modified and must be recompiled
8222 Now both files must be recompiled as indicated, and then the bind can
8223 succeed, generating a main program. You need not normally be concerned
8224 with the contents of this file, but for reference purposes a sample
8225 binder output file is given in @ref{Example of Binder Output File}.
8227 In most normal usage, the default mode of @command{gnatbind} which is to
8228 generate the main package in Ada, as described in the previous section.
8229 In particular, this means that any Ada programmer can read and understand
8230 the generated main program. It can also be debugged just like any other
8231 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8232 @command{gnatbind} and @command{gnatlink}.
8234 @node Switches for gnatbind
8235 @section Switches for @command{gnatbind}
8238 The following switches are available with @code{gnatbind}; details will
8239 be presented in subsequent sections.
8242 * Consistency-Checking Modes::
8243 * Binder Error Message Control::
8244 * Elaboration Control::
8246 * Dynamic Allocation Control::
8247 * Binding with Non-Ada Main Programs::
8248 * Binding Programs with No Main Subprogram::
8255 @cindex @option{--version} @command{gnatbind}
8256 Display Copyright and version, then exit disregarding all other options.
8259 @cindex @option{--help} @command{gnatbind}
8260 If @option{--version} was not used, display usage, then exit disregarding
8264 @cindex @option{-a} @command{gnatbind}
8265 Indicates that, if supported by the platform, the adainit procedure should
8266 be treated as an initialisation routine by the linker (a constructor). This
8267 is intended to be used by the Project Manager to automatically initialize
8268 shared Stand-Alone Libraries.
8270 @item ^-aO^/OBJECT_SEARCH^
8271 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8272 Specify directory to be searched for ALI files.
8274 @item ^-aI^/SOURCE_SEARCH^
8275 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8276 Specify directory to be searched for source file.
8278 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8279 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8280 Output ALI list (to standard output or to the named file).
8282 @item ^-b^/REPORT_ERRORS=BRIEF^
8283 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8284 Generate brief messages to @file{stderr} even if verbose mode set.
8286 @item ^-c^/NOOUTPUT^
8287 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8288 Check only, no generation of binder output file.
8290 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8291 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8292 This switch can be used to change the default task stack size value
8293 to a specified size @var{nn}, which is expressed in bytes by default, or
8294 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8296 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8297 in effect, to completing all task specs with
8298 @smallexample @c ada
8299 pragma Storage_Size (nn);
8301 When they do not already have such a pragma.
8303 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8304 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8305 This switch can be used to change the default secondary stack size value
8306 to a specified size @var{nn}, which is expressed in bytes by default, or
8307 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8310 The secondary stack is used to deal with functions that return a variable
8311 sized result, for example a function returning an unconstrained
8312 String. There are two ways in which this secondary stack is allocated.
8314 For most targets, the secondary stack is growing on demand and is allocated
8315 as a chain of blocks in the heap. The -D option is not very
8316 relevant. It only give some control over the size of the allocated
8317 blocks (whose size is the minimum of the default secondary stack size value,
8318 and the actual size needed for the current allocation request).
8320 For certain targets, notably VxWorks 653,
8321 the secondary stack is allocated by carving off a fixed ratio chunk of the
8322 primary task stack. The -D option is used to define the
8323 size of the environment task's secondary stack.
8325 @item ^-e^/ELABORATION_DEPENDENCIES^
8326 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8327 Output complete list of elaboration-order dependencies.
8329 @item ^-E^/STORE_TRACEBACKS^
8330 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8331 Store tracebacks in exception occurrences when the target supports it.
8333 @c The following may get moved to an appendix
8334 This option is currently supported on the following targets:
8335 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8337 See also the packages @code{GNAT.Traceback} and
8338 @code{GNAT.Traceback.Symbolic} for more information.
8340 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8341 @command{gcc} option.
8344 @item ^-F^/FORCE_ELABS_FLAGS^
8345 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8346 Force the checks of elaboration flags. @command{gnatbind} does not normally
8347 generate checks of elaboration flags for the main executable, except when
8348 a Stand-Alone Library is used. However, there are cases when this cannot be
8349 detected by gnatbind. An example is importing an interface of a Stand-Alone
8350 Library through a pragma Import and only specifying through a linker switch
8351 this Stand-Alone Library. This switch is used to guarantee that elaboration
8352 flag checks are generated.
8355 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8356 Output usage (help) information
8358 @item ^-H32^/32_MALLOC^
8359 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8360 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8361 For further details see @ref{Dynamic Allocation Control}.
8363 @item ^-H64^/64_MALLOC^
8364 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8365 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8366 @cindex @code{__gnat_malloc}
8367 For further details see @ref{Dynamic Allocation Control}.
8370 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8371 Specify directory to be searched for source and ALI files.
8373 @item ^-I-^/NOCURRENT_DIRECTORY^
8374 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8375 Do not look for sources in the current directory where @code{gnatbind} was
8376 invoked, and do not look for ALI files in the directory containing the
8377 ALI file named in the @code{gnatbind} command line.
8379 @item ^-l^/ORDER_OF_ELABORATION^
8380 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8381 Output chosen elaboration order.
8383 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8384 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8385 Bind the units for library building. In this case the adainit and
8386 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8387 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8388 ^@var{xxx}final^@var{XXX}FINAL^.
8389 Implies ^-n^/NOCOMPILE^.
8391 (@xref{GNAT and Libraries}, for more details.)
8394 On OpenVMS, these init and final procedures are exported in uppercase
8395 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8396 the init procedure will be "TOTOINIT" and the exported name of the final
8397 procedure will be "TOTOFINAL".
8400 @item ^-Mxyz^/RENAME_MAIN=xyz^
8401 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8402 Rename generated main program from main to xyz. This option is
8403 supported on cross environments only.
8405 @item ^-m^/ERROR_LIMIT=^@var{n}
8406 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8407 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8408 in the range 1..999999. The default value if no switch is
8409 given is 9999. If the number of warnings reaches this limit, then a
8410 message is output and further warnings are suppressed, the bind
8411 continues in this case. If the number of errors reaches this
8412 limit, then a message is output and the bind is abandoned.
8413 A value of zero means that no limit is enforced. The equal
8417 Furthermore, under Windows, the sources pointed to by the libraries path
8418 set in the registry are not searched for.
8422 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8426 @cindex @option{-nostdinc} (@command{gnatbind})
8427 Do not look for sources in the system default directory.
8430 @cindex @option{-nostdlib} (@command{gnatbind})
8431 Do not look for library files in the system default directory.
8433 @item --RTS=@var{rts-path}
8434 @cindex @option{--RTS} (@code{gnatbind})
8435 Specifies the default location of the runtime library. Same meaning as the
8436 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8438 @item ^-o ^/OUTPUT=^@var{file}
8439 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8440 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8441 Note that if this option is used, then linking must be done manually,
8442 gnatlink cannot be used.
8444 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8445 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8446 Output object list (to standard output or to the named file).
8448 @item ^-p^/PESSIMISTIC_ELABORATION^
8449 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8450 Pessimistic (worst-case) elaboration order
8453 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8454 Generate binder file suitable for CodePeer.
8457 @cindex @option{^-R^-R^} (@command{gnatbind})
8458 Output closure source list.
8460 @item ^-s^/READ_SOURCES=ALL^
8461 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8462 Require all source files to be present.
8464 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8465 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8466 Specifies the value to be used when detecting uninitialized scalar
8467 objects with pragma Initialize_Scalars.
8468 The @var{xxx} ^string specified with the switch^option^ may be either
8470 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8471 @item ``@option{^lo^LOW^}'' for the lowest possible value
8472 @item ``@option{^hi^HIGH^}'' for the highest possible value
8473 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8474 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8477 In addition, you can specify @option{-Sev} to indicate that the value is
8478 to be set at run time. In this case, the program will look for an environment
8479 @cindex GNAT_INIT_SCALARS
8480 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8481 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8482 If no environment variable is found, or if it does not have a valid value,
8483 then the default is @option{in} (invalid values).
8487 @cindex @option{-static} (@code{gnatbind})
8488 Link against a static GNAT run time.
8491 @cindex @option{-shared} (@code{gnatbind})
8492 Link against a shared GNAT run time when available.
8495 @item ^-t^/NOTIME_STAMP_CHECK^
8496 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8497 Tolerate time stamp and other consistency errors
8499 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8500 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8501 Set the time slice value to @var{n} milliseconds. If the system supports
8502 the specification of a specific time slice value, then the indicated value
8503 is used. If the system does not support specific time slice values, but
8504 does support some general notion of round-robin scheduling, then any
8505 nonzero value will activate round-robin scheduling.
8507 A value of zero is treated specially. It turns off time
8508 slicing, and in addition, indicates to the tasking run time that the
8509 semantics should match as closely as possible the Annex D
8510 requirements of the Ada RM, and in particular sets the default
8511 scheduling policy to @code{FIFO_Within_Priorities}.
8513 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8514 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8515 Enable dynamic stack usage, with @var{n} results stored and displayed
8516 at program termination. A result is generated when a task
8517 terminates. Results that can't be stored are displayed on the fly, at
8518 task termination. This option is currently not supported on Itanium
8519 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8521 @item ^-v^/REPORT_ERRORS=VERBOSE^
8522 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8523 Verbose mode. Write error messages, header, summary output to
8528 @cindex @option{-w} (@code{gnatbind})
8529 Warning mode (@var{x}=s/e for suppress/treat as error)
8533 @item /WARNINGS=NORMAL
8534 @cindex @option{/WARNINGS} (@code{gnatbind})
8535 Normal warnings mode. Warnings are issued but ignored
8537 @item /WARNINGS=SUPPRESS
8538 @cindex @option{/WARNINGS} (@code{gnatbind})
8539 All warning messages are suppressed
8541 @item /WARNINGS=ERROR
8542 @cindex @option{/WARNINGS} (@code{gnatbind})
8543 Warning messages are treated as fatal errors
8546 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8547 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8548 Override default wide character encoding for standard Text_IO files.
8550 @item ^-x^/READ_SOURCES=NONE^
8551 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8552 Exclude source files (check object consistency only).
8555 @item /READ_SOURCES=AVAILABLE
8556 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8557 Default mode, in which sources are checked for consistency only if
8561 @item ^-y^/ENABLE_LEAP_SECONDS^
8562 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8563 Enable leap seconds support in @code{Ada.Calendar} and its children.
8565 @item ^-z^/ZERO_MAIN^
8566 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8572 You may obtain this listing of switches by running @code{gnatbind} with
8576 @node Consistency-Checking Modes
8577 @subsection Consistency-Checking Modes
8580 As described earlier, by default @code{gnatbind} checks
8581 that object files are consistent with one another and are consistent
8582 with any source files it can locate. The following switches control binder
8587 @item ^-s^/READ_SOURCES=ALL^
8588 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8589 Require source files to be present. In this mode, the binder must be
8590 able to locate all source files that are referenced, in order to check
8591 their consistency. In normal mode, if a source file cannot be located it
8592 is simply ignored. If you specify this switch, a missing source
8595 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8596 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8597 Override default wide character encoding for standard Text_IO files.
8598 Normally the default wide character encoding method used for standard
8599 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8600 the main source input (see description of switch
8601 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8602 use of this switch for the binder (which has the same set of
8603 possible arguments) overrides this default as specified.
8605 @item ^-x^/READ_SOURCES=NONE^
8606 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8607 Exclude source files. In this mode, the binder only checks that ALI
8608 files are consistent with one another. Source files are not accessed.
8609 The binder runs faster in this mode, and there is still a guarantee that
8610 the resulting program is self-consistent.
8611 If a source file has been edited since it was last compiled, and you
8612 specify this switch, the binder will not detect that the object
8613 file is out of date with respect to the source file. Note that this is the
8614 mode that is automatically used by @command{gnatmake} because in this
8615 case the checking against sources has already been performed by
8616 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8619 @item /READ_SOURCES=AVAILABLE
8620 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8621 This is the default mode in which source files are checked if they are
8622 available, and ignored if they are not available.
8626 @node Binder Error Message Control
8627 @subsection Binder Error Message Control
8630 The following switches provide control over the generation of error
8631 messages from the binder:
8635 @item ^-v^/REPORT_ERRORS=VERBOSE^
8636 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8637 Verbose mode. In the normal mode, brief error messages are generated to
8638 @file{stderr}. If this switch is present, a header is written
8639 to @file{stdout} and any error messages are directed to @file{stdout}.
8640 All that is written to @file{stderr} is a brief summary message.
8642 @item ^-b^/REPORT_ERRORS=BRIEF^
8643 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8644 Generate brief error messages to @file{stderr} even if verbose mode is
8645 specified. This is relevant only when used with the
8646 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8650 @cindex @option{-m} (@code{gnatbind})
8651 Limits the number of error messages to @var{n}, a decimal integer in the
8652 range 1-999. The binder terminates immediately if this limit is reached.
8655 @cindex @option{-M} (@code{gnatbind})
8656 Renames the generated main program from @code{main} to @code{xxx}.
8657 This is useful in the case of some cross-building environments, where
8658 the actual main program is separate from the one generated
8662 @item ^-ws^/WARNINGS=SUPPRESS^
8663 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8665 Suppress all warning messages.
8667 @item ^-we^/WARNINGS=ERROR^
8668 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8669 Treat any warning messages as fatal errors.
8672 @item /WARNINGS=NORMAL
8673 Standard mode with warnings generated, but warnings do not get treated
8677 @item ^-t^/NOTIME_STAMP_CHECK^
8678 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8679 @cindex Time stamp checks, in binder
8680 @cindex Binder consistency checks
8681 @cindex Consistency checks, in binder
8682 The binder performs a number of consistency checks including:
8686 Check that time stamps of a given source unit are consistent
8688 Check that checksums of a given source unit are consistent
8690 Check that consistent versions of @code{GNAT} were used for compilation
8692 Check consistency of configuration pragmas as required
8696 Normally failure of such checks, in accordance with the consistency
8697 requirements of the Ada Reference Manual, causes error messages to be
8698 generated which abort the binder and prevent the output of a binder
8699 file and subsequent link to obtain an executable.
8701 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8702 into warnings, so that
8703 binding and linking can continue to completion even in the presence of such
8704 errors. The result may be a failed link (due to missing symbols), or a
8705 non-functional executable which has undefined semantics.
8706 @emph{This means that
8707 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8711 @node Elaboration Control
8712 @subsection Elaboration Control
8715 The following switches provide additional control over the elaboration
8716 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8719 @item ^-p^/PESSIMISTIC_ELABORATION^
8720 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8721 Normally the binder attempts to choose an elaboration order that is
8722 likely to minimize the likelihood of an elaboration order error resulting
8723 in raising a @code{Program_Error} exception. This switch reverses the
8724 action of the binder, and requests that it deliberately choose an order
8725 that is likely to maximize the likelihood of an elaboration error.
8726 This is useful in ensuring portability and avoiding dependence on
8727 accidental fortuitous elaboration ordering.
8729 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8731 elaboration checking is used (@option{-gnatE} switch used for compilation).
8732 This is because in the default static elaboration mode, all necessary
8733 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8734 These implicit pragmas are still respected by the binder in
8735 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8736 safe elaboration order is assured.
8738 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8739 production use; it is more for debugging/experimental use.
8742 @node Output Control
8743 @subsection Output Control
8746 The following switches allow additional control over the output
8747 generated by the binder.
8752 @item ^-c^/NOOUTPUT^
8753 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8754 Check only. Do not generate the binder output file. In this mode the
8755 binder performs all error checks but does not generate an output file.
8757 @item ^-e^/ELABORATION_DEPENDENCIES^
8758 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8759 Output complete list of elaboration-order dependencies, showing the
8760 reason for each dependency. This output can be rather extensive but may
8761 be useful in diagnosing problems with elaboration order. The output is
8762 written to @file{stdout}.
8765 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8766 Output usage information. The output is written to @file{stdout}.
8768 @item ^-K^/LINKER_OPTION_LIST^
8769 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8770 Output linker options to @file{stdout}. Includes library search paths,
8771 contents of pragmas Ident and Linker_Options, and libraries added
8774 @item ^-l^/ORDER_OF_ELABORATION^
8775 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8776 Output chosen elaboration order. The output is written to @file{stdout}.
8778 @item ^-O^/OBJECT_LIST^
8779 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8780 Output full names of all the object files that must be linked to provide
8781 the Ada component of the program. The output is written to @file{stdout}.
8782 This list includes the files explicitly supplied and referenced by the user
8783 as well as implicitly referenced run-time unit files. The latter are
8784 omitted if the corresponding units reside in shared libraries. The
8785 directory names for the run-time units depend on the system configuration.
8787 @item ^-o ^/OUTPUT=^@var{file}
8788 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8789 Set name of output file to @var{file} instead of the normal
8790 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8791 binder generated body filename.
8792 Note that if this option is used, then linking must be done manually.
8793 It is not possible to use gnatlink in this case, since it cannot locate
8796 @item ^-r^/RESTRICTION_LIST^
8797 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8798 Generate list of @code{pragma Restrictions} that could be applied to
8799 the current unit. This is useful for code audit purposes, and also may
8800 be used to improve code generation in some cases.
8804 @node Dynamic Allocation Control
8805 @subsection Dynamic Allocation Control
8808 The heap control switches -- @option{-H32} and @option{-H64} --
8809 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8810 They only affect compiler-generated allocations via @code{__gnat_malloc};
8811 explicit calls to @code{malloc} and related functions from the C
8812 run-time library are unaffected.
8816 Allocate memory on 32-bit heap
8819 Allocate memory on 64-bit heap. This is the default
8820 unless explicitly overridden by a @code{'Size} clause on the access type.
8825 See also @ref{Access types and 32/64-bit allocation}.
8829 These switches are only effective on VMS platforms.
8833 @node Binding with Non-Ada Main Programs
8834 @subsection Binding with Non-Ada Main Programs
8837 In our description so far we have assumed that the main
8838 program is in Ada, and that the task of the binder is to generate a
8839 corresponding function @code{main} that invokes this Ada main
8840 program. GNAT also supports the building of executable programs where
8841 the main program is not in Ada, but some of the called routines are
8842 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8843 The following switch is used in this situation:
8847 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8848 No main program. The main program is not in Ada.
8852 In this case, most of the functions of the binder are still required,
8853 but instead of generating a main program, the binder generates a file
8854 containing the following callable routines:
8859 You must call this routine to initialize the Ada part of the program by
8860 calling the necessary elaboration routines. A call to @code{adainit} is
8861 required before the first call to an Ada subprogram.
8863 Note that it is assumed that the basic execution environment must be setup
8864 to be appropriate for Ada execution at the point where the first Ada
8865 subprogram is called. In particular, if the Ada code will do any
8866 floating-point operations, then the FPU must be setup in an appropriate
8867 manner. For the case of the x86, for example, full precision mode is
8868 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8869 that the FPU is in the right state.
8873 You must call this routine to perform any library-level finalization
8874 required by the Ada subprograms. A call to @code{adafinal} is required
8875 after the last call to an Ada subprogram, and before the program
8880 If the @option{^-n^/NOMAIN^} switch
8881 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8882 @cindex Binder, multiple input files
8883 is given, more than one ALI file may appear on
8884 the command line for @code{gnatbind}. The normal @dfn{closure}
8885 calculation is performed for each of the specified units. Calculating
8886 the closure means finding out the set of units involved by tracing
8887 @code{with} references. The reason it is necessary to be able to
8888 specify more than one ALI file is that a given program may invoke two or
8889 more quite separate groups of Ada units.
8891 The binder takes the name of its output file from the last specified ALI
8892 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8893 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8894 The output is an Ada unit in source form that can be compiled with GNAT.
8895 This compilation occurs automatically as part of the @command{gnatlink}
8898 Currently the GNAT run time requires a FPU using 80 bits mode
8899 precision. Under targets where this is not the default it is required to
8900 call GNAT.Float_Control.Reset before using floating point numbers (this
8901 include float computation, float input and output) in the Ada code. A
8902 side effect is that this could be the wrong mode for the foreign code
8903 where floating point computation could be broken after this call.
8905 @node Binding Programs with No Main Subprogram
8906 @subsection Binding Programs with No Main Subprogram
8909 It is possible to have an Ada program which does not have a main
8910 subprogram. This program will call the elaboration routines of all the
8911 packages, then the finalization routines.
8913 The following switch is used to bind programs organized in this manner:
8916 @item ^-z^/ZERO_MAIN^
8917 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8918 Normally the binder checks that the unit name given on the command line
8919 corresponds to a suitable main subprogram. When this switch is used,
8920 a list of ALI files can be given, and the execution of the program
8921 consists of elaboration of these units in an appropriate order. Note
8922 that the default wide character encoding method for standard Text_IO
8923 files is always set to Brackets if this switch is set (you can use
8925 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8928 @node Command-Line Access
8929 @section Command-Line Access
8932 The package @code{Ada.Command_Line} provides access to the command-line
8933 arguments and program name. In order for this interface to operate
8934 correctly, the two variables
8946 are declared in one of the GNAT library routines. These variables must
8947 be set from the actual @code{argc} and @code{argv} values passed to the
8948 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8949 generates the C main program to automatically set these variables.
8950 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8951 set these variables. If they are not set, the procedures in
8952 @code{Ada.Command_Line} will not be available, and any attempt to use
8953 them will raise @code{Constraint_Error}. If command line access is
8954 required, your main program must set @code{gnat_argc} and
8955 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8958 @node Search Paths for gnatbind
8959 @section Search Paths for @code{gnatbind}
8962 The binder takes the name of an ALI file as its argument and needs to
8963 locate source files as well as other ALI files to verify object consistency.
8965 For source files, it follows exactly the same search rules as @command{gcc}
8966 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8967 directories searched are:
8971 The directory containing the ALI file named in the command line, unless
8972 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8975 All directories specified by @option{^-I^/SEARCH^}
8976 switches on the @code{gnatbind}
8977 command line, in the order given.
8980 @findex ADA_PRJ_OBJECTS_FILE
8981 Each of the directories listed in the text file whose name is given
8982 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8985 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8986 driver when project files are used. It should not normally be set
8990 @findex ADA_OBJECTS_PATH
8991 Each of the directories listed in the value of the
8992 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8994 Construct this value
8995 exactly as the @env{PATH} environment variable: a list of directory
8996 names separated by colons (semicolons when working with the NT version
9000 Normally, define this value as a logical name containing a comma separated
9001 list of directory names.
9003 This variable can also be defined by means of an environment string
9004 (an argument to the HP C exec* set of functions).
9008 DEFINE ANOTHER_PATH FOO:[BAG]
9009 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9012 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9013 first, followed by the standard Ada
9014 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9015 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9016 (Text_IO, Sequential_IO, etc)
9017 instead of the standard Ada packages. Thus, in order to get the standard Ada
9018 packages by default, ADA_OBJECTS_PATH must be redefined.
9022 The content of the @file{ada_object_path} file which is part of the GNAT
9023 installation tree and is used to store standard libraries such as the
9024 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9027 @ref{Installing a library}
9032 In the binder the switch @option{^-I^/SEARCH^}
9033 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9034 is used to specify both source and
9035 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9036 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9037 instead if you want to specify
9038 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9039 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9040 if you want to specify library paths
9041 only. This means that for the binder
9042 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9043 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9044 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9045 The binder generates the bind file (a C language source file) in the
9046 current working directory.
9052 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9053 children make up the GNAT Run-Time Library, together with the package
9054 GNAT and its children, which contain a set of useful additional
9055 library functions provided by GNAT. The sources for these units are
9056 needed by the compiler and are kept together in one directory. The ALI
9057 files and object files generated by compiling the RTL are needed by the
9058 binder and the linker and are kept together in one directory, typically
9059 different from the directory containing the sources. In a normal
9060 installation, you need not specify these directory names when compiling
9061 or binding. Either the environment variables or the built-in defaults
9062 cause these files to be found.
9064 Besides simplifying access to the RTL, a major use of search paths is
9065 in compiling sources from multiple directories. This can make
9066 development environments much more flexible.
9068 @node Examples of gnatbind Usage
9069 @section Examples of @code{gnatbind} Usage
9072 This section contains a number of examples of using the GNAT binding
9073 utility @code{gnatbind}.
9076 @item gnatbind hello
9077 The main program @code{Hello} (source program in @file{hello.adb}) is
9078 bound using the standard switch settings. The generated main program is
9079 @file{b~hello.adb}. This is the normal, default use of the binder.
9082 @item gnatbind hello -o mainprog.adb
9085 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9087 The main program @code{Hello} (source program in @file{hello.adb}) is
9088 bound using the standard switch settings. The generated main program is
9089 @file{mainprog.adb} with the associated spec in
9090 @file{mainprog.ads}. Note that you must specify the body here not the
9091 spec. Note that if this option is used, then linking must be done manually,
9092 since gnatlink will not be able to find the generated file.
9095 @c ------------------------------------
9096 @node Linking Using gnatlink
9097 @chapter Linking Using @command{gnatlink}
9098 @c ------------------------------------
9102 This chapter discusses @command{gnatlink}, a tool that links
9103 an Ada program and builds an executable file. This utility
9104 invokes the system linker ^(via the @command{gcc} command)^^
9105 with a correct list of object files and library references.
9106 @command{gnatlink} automatically determines the list of files and
9107 references for the Ada part of a program. It uses the binder file
9108 generated by the @command{gnatbind} to determine this list.
9110 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9111 driver (see @ref{The GNAT Driver and Project Files}).
9114 * Running gnatlink::
9115 * Switches for gnatlink::
9118 @node Running gnatlink
9119 @section Running @command{gnatlink}
9122 The form of the @command{gnatlink} command is
9125 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9126 @c @ovar{non-Ada objects} @ovar{linker options}
9127 @c Expanding @ovar macro inline (explanation in macro def comments)
9128 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9129 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9134 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9136 or linker options) may be in any order, provided that no non-Ada object may
9137 be mistaken for a main @file{ALI} file.
9138 Any file name @file{F} without the @file{.ali}
9139 extension will be taken as the main @file{ALI} file if a file exists
9140 whose name is the concatenation of @file{F} and @file{.ali}.
9143 @file{@var{mainprog}.ali} references the ALI file of the main program.
9144 The @file{.ali} extension of this file can be omitted. From this
9145 reference, @command{gnatlink} locates the corresponding binder file
9146 @file{b~@var{mainprog}.adb} and, using the information in this file along
9147 with the list of non-Ada objects and linker options, constructs a
9148 linker command file to create the executable.
9150 The arguments other than the @command{gnatlink} switches and the main
9151 @file{ALI} file are passed to the linker uninterpreted.
9152 They typically include the names of
9153 object files for units written in other languages than Ada and any library
9154 references required to resolve references in any of these foreign language
9155 units, or in @code{Import} pragmas in any Ada units.
9157 @var{linker options} is an optional list of linker specific
9159 The default linker called by gnatlink is @command{gcc} which in
9160 turn calls the appropriate system linker.
9162 One useful option for the linker is @option{-s}: it reduces the size of the
9163 executable by removing all symbol table and relocation information from the
9166 Standard options for the linker such as @option{-lmy_lib} or
9167 @option{-Ldir} can be added as is.
9168 For options that are not recognized by
9169 @command{gcc} as linker options, use the @command{gcc} switches
9170 @option{-Xlinker} or @option{-Wl,}.
9172 Refer to the GCC documentation for
9175 Here is an example showing how to generate a linker map:
9178 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9181 Using @var{linker options} it is possible to set the program stack and
9184 See @ref{Setting Stack Size from gnatlink} and
9185 @ref{Setting Heap Size from gnatlink}.
9188 @command{gnatlink} determines the list of objects required by the Ada
9189 program and prepends them to the list of objects passed to the linker.
9190 @command{gnatlink} also gathers any arguments set by the use of
9191 @code{pragma Linker_Options} and adds them to the list of arguments
9192 presented to the linker.
9195 @command{gnatlink} accepts the following types of extra files on the command
9196 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9197 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9198 handled according to their extension.
9201 @node Switches for gnatlink
9202 @section Switches for @command{gnatlink}
9205 The following switches are available with the @command{gnatlink} utility:
9211 @cindex @option{--version} @command{gnatlink}
9212 Display Copyright and version, then exit disregarding all other options.
9215 @cindex @option{--help} @command{gnatlink}
9216 If @option{--version} was not used, display usage, then exit disregarding
9219 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9220 @cindex Command line length
9221 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9222 On some targets, the command line length is limited, and @command{gnatlink}
9223 will generate a separate file for the linker if the list of object files
9225 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9226 to be generated even if
9227 the limit is not exceeded. This is useful in some cases to deal with
9228 special situations where the command line length is exceeded.
9231 @cindex Debugging information, including
9232 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9233 The option to include debugging information causes the Ada bind file (in
9234 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9235 @option{^-g^/DEBUG^}.
9236 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9237 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9238 Without @option{^-g^/DEBUG^}, the binder removes these files by
9239 default. The same procedure apply if a C bind file was generated using
9240 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9241 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9243 @item ^-n^/NOCOMPILE^
9244 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9245 Do not compile the file generated by the binder. This may be used when
9246 a link is rerun with different options, but there is no need to recompile
9250 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9251 Causes additional information to be output, including a full list of the
9252 included object files. This switch option is most useful when you want
9253 to see what set of object files are being used in the link step.
9255 @item ^-v -v^/VERBOSE/VERBOSE^
9256 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9257 Very verbose mode. Requests that the compiler operate in verbose mode when
9258 it compiles the binder file, and that the system linker run in verbose mode.
9260 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9261 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9262 @var{exec-name} specifies an alternate name for the generated
9263 executable program. If this switch is omitted, the executable has the same
9264 name as the main unit. For example, @code{gnatlink try.ali} creates
9265 an executable called @file{^try^TRY.EXE^}.
9268 @item -b @var{target}
9269 @cindex @option{-b} (@command{gnatlink})
9270 Compile your program to run on @var{target}, which is the name of a
9271 system configuration. You must have a GNAT cross-compiler built if
9272 @var{target} is not the same as your host system.
9275 @cindex @option{-B} (@command{gnatlink})
9276 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9277 from @var{dir} instead of the default location. Only use this switch
9278 when multiple versions of the GNAT compiler are available.
9279 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9280 for further details. You would normally use the @option{-b} or
9281 @option{-V} switch instead.
9284 When linking an executable, create a map file. The name of the map file
9285 has the same name as the executable with extension ".map".
9288 When linking an executable, create a map file. The name of the map file is
9291 @item --GCC=@var{compiler_name}
9292 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9293 Program used for compiling the binder file. The default is
9294 @command{gcc}. You need to use quotes around @var{compiler_name} if
9295 @code{compiler_name} contains spaces or other separator characters.
9296 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9297 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9298 inserted after your command name. Thus in the above example the compiler
9299 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9300 A limitation of this syntax is that the name and path name of the executable
9301 itself must not include any embedded spaces. If the compiler executable is
9302 different from the default one (gcc or <prefix>-gcc), then the back-end
9303 switches in the ALI file are not used to compile the binder generated source.
9304 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9305 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9306 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9307 is taken into account. However, all the additional switches are also taken
9309 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9310 @option{--GCC="bar -x -y -z -t"}.
9312 @item --LINK=@var{name}
9313 @cindex @option{--LINK=} (@command{gnatlink})
9314 @var{name} is the name of the linker to be invoked. This is especially
9315 useful in mixed language programs since languages such as C++ require
9316 their own linker to be used. When this switch is omitted, the default
9317 name for the linker is @command{gcc}. When this switch is used, the
9318 specified linker is called instead of @command{gcc} with exactly the same
9319 parameters that would have been passed to @command{gcc} so if the desired
9320 linker requires different parameters it is necessary to use a wrapper
9321 script that massages the parameters before invoking the real linker. It
9322 may be useful to control the exact invocation by using the verbose
9328 @item /DEBUG=TRACEBACK
9329 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9330 This qualifier causes sufficient information to be included in the
9331 executable file to allow a traceback, but does not include the full
9332 symbol information needed by the debugger.
9334 @item /IDENTIFICATION="<string>"
9335 @code{"<string>"} specifies the string to be stored in the image file
9336 identification field in the image header.
9337 It overrides any pragma @code{Ident} specified string.
9339 @item /NOINHIBIT-EXEC
9340 Generate the executable file even if there are linker warnings.
9342 @item /NOSTART_FILES
9343 Don't link in the object file containing the ``main'' transfer address.
9344 Used when linking with a foreign language main program compiled with an
9348 Prefer linking with object libraries over sharable images, even without
9354 @node The GNAT Make Program gnatmake
9355 @chapter The GNAT Make Program @command{gnatmake}
9359 * Running gnatmake::
9360 * Switches for gnatmake::
9361 * Mode Switches for gnatmake::
9362 * Notes on the Command Line::
9363 * How gnatmake Works::
9364 * Examples of gnatmake Usage::
9367 A typical development cycle when working on an Ada program consists of
9368 the following steps:
9372 Edit some sources to fix bugs.
9378 Compile all sources affected.
9388 The third step can be tricky, because not only do the modified files
9389 @cindex Dependency rules
9390 have to be compiled, but any files depending on these files must also be
9391 recompiled. The dependency rules in Ada can be quite complex, especially
9392 in the presence of overloading, @code{use} clauses, generics and inlined
9395 @command{gnatmake} automatically takes care of the third and fourth steps
9396 of this process. It determines which sources need to be compiled,
9397 compiles them, and binds and links the resulting object files.
9399 Unlike some other Ada make programs, the dependencies are always
9400 accurately recomputed from the new sources. The source based approach of
9401 the GNAT compilation model makes this possible. This means that if
9402 changes to the source program cause corresponding changes in
9403 dependencies, they will always be tracked exactly correctly by
9406 @node Running gnatmake
9407 @section Running @command{gnatmake}
9410 The usual form of the @command{gnatmake} command is
9413 @c $ gnatmake @ovar{switches} @var{file_name}
9414 @c @ovar{file_names} @ovar{mode_switches}
9415 @c Expanding @ovar macro inline (explanation in macro def comments)
9416 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9417 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9421 The only required argument is one @var{file_name}, which specifies
9422 a compilation unit that is a main program. Several @var{file_names} can be
9423 specified: this will result in several executables being built.
9424 If @code{switches} are present, they can be placed before the first
9425 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9426 If @var{mode_switches} are present, they must always be placed after
9427 the last @var{file_name} and all @code{switches}.
9429 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9430 extension may be omitted from the @var{file_name} arguments. However, if
9431 you are using non-standard extensions, then it is required that the
9432 extension be given. A relative or absolute directory path can be
9433 specified in a @var{file_name}, in which case, the input source file will
9434 be searched for in the specified directory only. Otherwise, the input
9435 source file will first be searched in the directory where
9436 @command{gnatmake} was invoked and if it is not found, it will be search on
9437 the source path of the compiler as described in
9438 @ref{Search Paths and the Run-Time Library (RTL)}.
9440 All @command{gnatmake} output (except when you specify
9441 @option{^-M^/DEPENDENCIES_LIST^}) is to
9442 @file{stderr}. The output produced by the
9443 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9446 @node Switches for gnatmake
9447 @section Switches for @command{gnatmake}
9450 You may specify any of the following switches to @command{gnatmake}:
9456 @cindex @option{--version} @command{gnatmake}
9457 Display Copyright and version, then exit disregarding all other options.
9460 @cindex @option{--help} @command{gnatmake}
9461 If @option{--version} was not used, display usage, then exit disregarding
9465 @item --GCC=@var{compiler_name}
9466 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9467 Program used for compiling. The default is `@command{gcc}'. You need to use
9468 quotes around @var{compiler_name} if @code{compiler_name} contains
9469 spaces or other separator characters. As an example @option{--GCC="foo -x
9470 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9471 compiler. A limitation of this syntax is that the name and path name of
9472 the executable itself must not include any embedded spaces. Note that
9473 switch @option{-c} is always inserted after your command name. Thus in the
9474 above example the compiler command that will be used by @command{gnatmake}
9475 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9476 used, only the last @var{compiler_name} is taken into account. However,
9477 all the additional switches are also taken into account. Thus,
9478 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9479 @option{--GCC="bar -x -y -z -t"}.
9481 @item --GNATBIND=@var{binder_name}
9482 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9483 Program used for binding. The default is `@code{gnatbind}'. You need to
9484 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9485 or other separator characters. As an example @option{--GNATBIND="bar -x
9486 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9487 binder. Binder switches that are normally appended by @command{gnatmake}
9488 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9489 A limitation of this syntax is that the name and path name of the executable
9490 itself must not include any embedded spaces.
9492 @item --GNATLINK=@var{linker_name}
9493 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9494 Program used for linking. The default is `@command{gnatlink}'. You need to
9495 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9496 or other separator characters. As an example @option{--GNATLINK="lan -x
9497 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9498 linker. Linker switches that are normally appended by @command{gnatmake} to
9499 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9500 A limitation of this syntax is that the name and path name of the executable
9501 itself must not include any embedded spaces.
9505 @item ^--subdirs^/SUBDIRS^=subdir
9506 Actual object directory of each project file is the subdirectory subdir of the
9507 object directory specified or defaulted in the project file.
9509 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9510 Disallow simultaneous compilations in the same object directory when
9511 project files are used.
9513 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9514 By default, shared library projects are not allowed to import static library
9515 projects. When this switch is used on the command line, this restriction is
9518 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9519 Specify a source info file. This switch is active only when project files
9520 are used. If the source info file is specified as a relative path, then it is
9521 relative to the object directory of the main project. If the source info file
9522 does not exist, then after the Project Manager has successfully parsed and
9523 processed the project files and found the sources, it creates the source info
9524 file. If the source info file already exists and can be read successfully,
9525 then the Project Manager will get all the needed information about the sources
9526 from the source info file and will not look for them. This reduces the time
9527 to process the project files, especially when looking for sources that take a
9528 long time. If the source info file exists but cannot be parsed successfully,
9529 the Project Manager will attempt to recreate it. If the Project Manager fails
9530 to create the source info file, a message is issued, but gnatmake does not
9531 fail. @command{gnatmake} "trusts" the source info file. This means that
9532 if the source files have changed (addition, deletion, moving to a different
9533 source directory), then the source info file need to be deleted and recreated.
9536 @item --create-map-file
9537 When linking an executable, create a map file. The name of the map file
9538 has the same name as the executable with extension ".map".
9540 @item --create-map-file=mapfile
9541 When linking an executable, create a map file. The name of the map file is
9546 @item ^-a^/ALL_FILES^
9547 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9548 Consider all files in the make process, even the GNAT internal system
9549 files (for example, the predefined Ada library files), as well as any
9550 locked files. Locked files are files whose ALI file is write-protected.
9552 @command{gnatmake} does not check these files,
9553 because the assumption is that the GNAT internal files are properly up
9554 to date, and also that any write protected ALI files have been properly
9555 installed. Note that if there is an installation problem, such that one
9556 of these files is not up to date, it will be properly caught by the
9558 You may have to specify this switch if you are working on GNAT
9559 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9560 in conjunction with @option{^-f^/FORCE_COMPILE^}
9561 if you need to recompile an entire application,
9562 including run-time files, using special configuration pragmas,
9563 such as a @code{Normalize_Scalars} pragma.
9566 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9569 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9572 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9575 @item ^-b^/ACTIONS=BIND^
9576 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9577 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9578 compilation and binding, but no link.
9579 Can be combined with @option{^-l^/ACTIONS=LINK^}
9580 to do binding and linking. When not combined with
9581 @option{^-c^/ACTIONS=COMPILE^}
9582 all the units in the closure of the main program must have been previously
9583 compiled and must be up to date. The root unit specified by @var{file_name}
9584 may be given without extension, with the source extension or, if no GNAT
9585 Project File is specified, with the ALI file extension.
9587 @item ^-c^/ACTIONS=COMPILE^
9588 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9589 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9590 is also specified. Do not perform linking, except if both
9591 @option{^-b^/ACTIONS=BIND^} and
9592 @option{^-l^/ACTIONS=LINK^} are also specified.
9593 If the root unit specified by @var{file_name} is not a main unit, this is the
9594 default. Otherwise @command{gnatmake} will attempt binding and linking
9595 unless all objects are up to date and the executable is more recent than
9599 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9600 Use a temporary mapping file. A mapping file is a way to communicate
9601 to the compiler two mappings: from unit names to file names (without
9602 any directory information) and from file names to path names (with
9603 full directory information). A mapping file can make the compiler's
9604 file searches faster, especially if there are many source directories,
9605 or the sources are read over a slow network connection. If
9606 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9607 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9608 is initially populated based on the project file. If
9609 @option{^-C^/MAPPING^} is used without
9610 @option{^-P^/PROJECT_FILE^},
9611 the mapping file is initially empty. Each invocation of the compiler
9612 will add any newly accessed sources to the mapping file.
9614 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9615 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9616 Use a specific mapping file. The file, specified as a path name (absolute or
9617 relative) by this switch, should already exist, otherwise the switch is
9618 ineffective. The specified mapping file will be communicated to the compiler.
9619 This switch is not compatible with a project file
9620 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9621 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9623 @item ^-d^/DISPLAY_PROGRESS^
9624 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9625 Display progress for each source, up to date or not, as a single line
9628 completed x out of y (zz%)
9631 If the file needs to be compiled this is displayed after the invocation of
9632 the compiler. These lines are displayed even in quiet output mode.
9634 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9635 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9636 Put all object files and ALI file in directory @var{dir}.
9637 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9638 and ALI files go in the current working directory.
9640 This switch cannot be used when using a project file.
9643 @cindex @option{-eI} (@command{gnatmake})
9644 Indicates that the main source is a multi-unit source and the rank of the unit
9645 in the source file is nnn. nnn needs to be a positive number and a valid
9646 index in the source. This switch cannot be used when @command{gnatmake} is
9647 invoked for several mains.
9651 @cindex @option{-eL} (@command{gnatmake})
9652 @cindex symbolic links
9653 Follow all symbolic links when processing project files.
9654 This should be used if your project uses symbolic links for files or
9655 directories, but is not needed in other cases.
9657 @cindex naming scheme
9658 This also assumes that no directory matches the naming scheme for files (for
9659 instance that you do not have a directory called "sources.ads" when using the
9660 default GNAT naming scheme).
9662 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9663 save a lot of system calls (several per source file and object file), which
9664 can result in a significant speed up to load and manipulate a project file,
9665 especially when using source files from a remote system.
9669 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9670 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9671 Output the commands for the compiler, the binder and the linker
9672 on ^standard output^SYS$OUTPUT^,
9673 instead of ^standard error^SYS$ERROR^.
9675 @item ^-f^/FORCE_COMPILE^
9676 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9677 Force recompilations. Recompile all sources, even though some object
9678 files may be up to date, but don't recompile predefined or GNAT internal
9679 files or locked files (files with a write-protected ALI file),
9680 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9682 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9683 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9684 When using project files, if some errors or warnings are detected during
9685 parsing and verbose mode is not in effect (no use of switch
9686 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9687 file, rather than its simple file name.
9690 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9691 Enable debugging. This switch is simply passed to the compiler and to the
9694 @item ^-i^/IN_PLACE^
9695 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9696 In normal mode, @command{gnatmake} compiles all object files and ALI files
9697 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9698 then instead object files and ALI files that already exist are overwritten
9699 in place. This means that once a large project is organized into separate
9700 directories in the desired manner, then @command{gnatmake} will automatically
9701 maintain and update this organization. If no ALI files are found on the
9702 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9703 the new object and ALI files are created in the
9704 directory containing the source being compiled. If another organization
9705 is desired, where objects and sources are kept in different directories,
9706 a useful technique is to create dummy ALI files in the desired directories.
9707 When detecting such a dummy file, @command{gnatmake} will be forced to
9708 recompile the corresponding source file, and it will be put the resulting
9709 object and ALI files in the directory where it found the dummy file.
9711 @item ^-j^/PROCESSES=^@var{n}
9712 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9713 @cindex Parallel make
9714 Use @var{n} processes to carry out the (re)compilations. On a
9715 multiprocessor machine compilations will occur in parallel. In the
9716 event of compilation errors, messages from various compilations might
9717 get interspersed (but @command{gnatmake} will give you the full ordered
9718 list of failing compiles at the end). If this is problematic, rerun
9719 the make process with n set to 1 to get a clean list of messages.
9721 @item ^-k^/CONTINUE_ON_ERROR^
9722 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9723 Keep going. Continue as much as possible after a compilation error. To
9724 ease the programmer's task in case of compilation errors, the list of
9725 sources for which the compile fails is given when @command{gnatmake}
9728 If @command{gnatmake} is invoked with several @file{file_names} and with this
9729 switch, if there are compilation errors when building an executable,
9730 @command{gnatmake} will not attempt to build the following executables.
9732 @item ^-l^/ACTIONS=LINK^
9733 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9734 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9735 and linking. Linking will not be performed if combined with
9736 @option{^-c^/ACTIONS=COMPILE^}
9737 but not with @option{^-b^/ACTIONS=BIND^}.
9738 When not combined with @option{^-b^/ACTIONS=BIND^}
9739 all the units in the closure of the main program must have been previously
9740 compiled and must be up to date, and the main program needs to have been bound.
9741 The root unit specified by @var{file_name}
9742 may be given without extension, with the source extension or, if no GNAT
9743 Project File is specified, with the ALI file extension.
9745 @item ^-m^/MINIMAL_RECOMPILATION^
9746 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9747 Specify that the minimum necessary amount of recompilations
9748 be performed. In this mode @command{gnatmake} ignores time
9749 stamp differences when the only
9750 modifications to a source file consist in adding/removing comments,
9751 empty lines, spaces or tabs. This means that if you have changed the
9752 comments in a source file or have simply reformatted it, using this
9753 switch will tell @command{gnatmake} not to recompile files that depend on it
9754 (provided other sources on which these files depend have undergone no
9755 semantic modifications). Note that the debugging information may be
9756 out of date with respect to the sources if the @option{-m} switch causes
9757 a compilation to be switched, so the use of this switch represents a
9758 trade-off between compilation time and accurate debugging information.
9760 @item ^-M^/DEPENDENCIES_LIST^
9761 @cindex Dependencies, producing list
9762 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9763 Check if all objects are up to date. If they are, output the object
9764 dependences to @file{stdout} in a form that can be directly exploited in
9765 a @file{Makefile}. By default, each source file is prefixed with its
9766 (relative or absolute) directory name. This name is whatever you
9767 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9768 and @option{^-I^/SEARCH^} switches. If you use
9769 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9770 @option{^-q^/QUIET^}
9771 (see below), only the source file names,
9772 without relative paths, are output. If you just specify the
9773 @option{^-M^/DEPENDENCIES_LIST^}
9774 switch, dependencies of the GNAT internal system files are omitted. This
9775 is typically what you want. If you also specify
9776 the @option{^-a^/ALL_FILES^} switch,
9777 dependencies of the GNAT internal files are also listed. Note that
9778 dependencies of the objects in external Ada libraries (see switch
9779 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9782 @item ^-n^/DO_OBJECT_CHECK^
9783 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9784 Don't compile, bind, or link. Checks if all objects are up to date.
9785 If they are not, the full name of the first file that needs to be
9786 recompiled is printed.
9787 Repeated use of this option, followed by compiling the indicated source
9788 file, will eventually result in recompiling all required units.
9790 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9791 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9792 Output executable name. The name of the final executable program will be
9793 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9794 name for the executable will be the name of the input file in appropriate form
9795 for an executable file on the host system.
9797 This switch cannot be used when invoking @command{gnatmake} with several
9800 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9801 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9802 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9803 automatically missing object directories, library directories and exec
9806 @item ^-P^/PROJECT_FILE=^@var{project}
9807 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9808 Use project file @var{project}. Only one such switch can be used.
9809 @xref{gnatmake and Project Files}.
9812 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9813 Quiet. When this flag is not set, the commands carried out by
9814 @command{gnatmake} are displayed.
9816 @item ^-s^/SWITCH_CHECK/^
9817 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9818 Recompile if compiler switches have changed since last compilation.
9819 All compiler switches but -I and -o are taken into account in the
9821 orders between different ``first letter'' switches are ignored, but
9822 orders between same switches are taken into account. For example,
9823 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9824 is equivalent to @option{-O -g}.
9826 This switch is recommended when Integrated Preprocessing is used.
9829 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9830 Unique. Recompile at most the main files. It implies -c. Combined with
9831 -f, it is equivalent to calling the compiler directly. Note that using
9832 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9833 (@pxref{Project Files and Main Subprograms}).
9835 @item ^-U^/ALL_PROJECTS^
9836 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9837 When used without a project file or with one or several mains on the command
9838 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9839 on the command line, all sources of all project files are checked and compiled
9840 if not up to date, and libraries are rebuilt, if necessary.
9843 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9844 Verbose. Display the reason for all recompilations @command{gnatmake}
9845 decides are necessary, with the highest verbosity level.
9847 @item ^-vl^/LOW_VERBOSITY^
9848 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9849 Verbosity level Low. Display fewer lines than in verbosity Medium.
9851 @item ^-vm^/MEDIUM_VERBOSITY^
9852 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9853 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9855 @item ^-vh^/HIGH_VERBOSITY^
9856 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9857 Verbosity level High. Equivalent to ^-v^/REASONS^.
9859 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9860 Indicate the verbosity of the parsing of GNAT project files.
9861 @xref{Switches Related to Project Files}.
9863 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9864 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9865 Indicate that sources that are not part of any Project File may be compiled.
9866 Normally, when using Project Files, only sources that are part of a Project
9867 File may be compile. When this switch is used, a source outside of all Project
9868 Files may be compiled. The ALI file and the object file will be put in the
9869 object directory of the main Project. The compilation switches used will only
9870 be those specified on the command line. Even when
9871 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9872 command line need to be sources of a project file.
9874 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9875 Indicate that external variable @var{name} has the value @var{value}.
9876 The Project Manager will use this value for occurrences of
9877 @code{external(name)} when parsing the project file.
9878 @xref{Switches Related to Project Files}.
9881 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9882 No main subprogram. Bind and link the program even if the unit name
9883 given on the command line is a package name. The resulting executable
9884 will execute the elaboration routines of the package and its closure,
9885 then the finalization routines.
9890 @item @command{gcc} @asis{switches}
9892 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9893 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9896 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9897 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9898 automatically treated as a compiler switch, and passed on to all
9899 compilations that are carried out.
9904 Source and library search path switches:
9908 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9909 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9910 When looking for source files also look in directory @var{dir}.
9911 The order in which source files search is undertaken is
9912 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9914 @item ^-aL^/SKIP_MISSING=^@var{dir}
9915 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9916 Consider @var{dir} as being an externally provided Ada library.
9917 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9918 files have been located in directory @var{dir}. This allows you to have
9919 missing bodies for the units in @var{dir} and to ignore out of date bodies
9920 for the same units. You still need to specify
9921 the location of the specs for these units by using the switches
9922 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9923 or @option{^-I^/SEARCH=^@var{dir}}.
9924 Note: this switch is provided for compatibility with previous versions
9925 of @command{gnatmake}. The easier method of causing standard libraries
9926 to be excluded from consideration is to write-protect the corresponding
9929 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9930 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9931 When searching for library and object files, look in directory
9932 @var{dir}. The order in which library files are searched is described in
9933 @ref{Search Paths for gnatbind}.
9935 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9936 @cindex Search paths, for @command{gnatmake}
9937 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9938 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9939 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9941 @item ^-I^/SEARCH=^@var{dir}
9942 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9943 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9944 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9946 @item ^-I-^/NOCURRENT_DIRECTORY^
9947 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9948 @cindex Source files, suppressing search
9949 Do not look for source files in the directory containing the source
9950 file named in the command line.
9951 Do not look for ALI or object files in the directory
9952 where @command{gnatmake} was invoked.
9954 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9955 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9956 @cindex Linker libraries
9957 Add directory @var{dir} to the list of directories in which the linker
9958 will search for libraries. This is equivalent to
9959 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9961 Furthermore, under Windows, the sources pointed to by the libraries path
9962 set in the registry are not searched for.
9966 @cindex @option{-nostdinc} (@command{gnatmake})
9967 Do not look for source files in the system default directory.
9970 @cindex @option{-nostdlib} (@command{gnatmake})
9971 Do not look for library files in the system default directory.
9973 @item --RTS=@var{rts-path}
9974 @cindex @option{--RTS} (@command{gnatmake})
9975 Specifies the default location of the runtime library. GNAT looks for the
9977 in the following directories, and stops as soon as a valid runtime is found
9978 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9979 @file{ada_object_path} present):
9982 @item <current directory>/$rts_path
9984 @item <default-search-dir>/$rts_path
9986 @item <default-search-dir>/rts-$rts_path
9990 The selected path is handled like a normal RTS path.
9994 @node Mode Switches for gnatmake
9995 @section Mode Switches for @command{gnatmake}
9998 The mode switches (referred to as @code{mode_switches}) allow the
9999 inclusion of switches that are to be passed to the compiler itself, the
10000 binder or the linker. The effect of a mode switch is to cause all
10001 subsequent switches up to the end of the switch list, or up to the next
10002 mode switch, to be interpreted as switches to be passed on to the
10003 designated component of GNAT.
10007 @item -cargs @var{switches}
10008 @cindex @option{-cargs} (@command{gnatmake})
10009 Compiler switches. Here @var{switches} is a list of switches
10010 that are valid switches for @command{gcc}. They will be passed on to
10011 all compile steps performed by @command{gnatmake}.
10013 @item -bargs @var{switches}
10014 @cindex @option{-bargs} (@command{gnatmake})
10015 Binder switches. Here @var{switches} is a list of switches
10016 that are valid switches for @code{gnatbind}. They will be passed on to
10017 all bind steps performed by @command{gnatmake}.
10019 @item -largs @var{switches}
10020 @cindex @option{-largs} (@command{gnatmake})
10021 Linker switches. Here @var{switches} is a list of switches
10022 that are valid switches for @command{gnatlink}. They will be passed on to
10023 all link steps performed by @command{gnatmake}.
10025 @item -margs @var{switches}
10026 @cindex @option{-margs} (@command{gnatmake})
10027 Make switches. The switches are directly interpreted by @command{gnatmake},
10028 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10029 or @option{-largs}.
10032 @node Notes on the Command Line
10033 @section Notes on the Command Line
10036 This section contains some additional useful notes on the operation
10037 of the @command{gnatmake} command.
10041 @cindex Recompilation, by @command{gnatmake}
10042 If @command{gnatmake} finds no ALI files, it recompiles the main program
10043 and all other units required by the main program.
10044 This means that @command{gnatmake}
10045 can be used for the initial compile, as well as during subsequent steps of
10046 the development cycle.
10049 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10050 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10051 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10055 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10056 is used to specify both source and
10057 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10058 instead if you just want to specify
10059 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10060 if you want to specify library paths
10064 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10065 This may conveniently be used to exclude standard libraries from
10066 consideration and in particular it means that the use of the
10067 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10068 unless @option{^-a^/ALL_FILES^} is also specified.
10071 @command{gnatmake} has been designed to make the use of Ada libraries
10072 particularly convenient. Assume you have an Ada library organized
10073 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10074 of your Ada compilation units,
10075 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10076 specs of these units, but no bodies. Then to compile a unit
10077 stored in @code{main.adb}, which uses this Ada library you would just type
10081 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10084 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10085 /SKIP_MISSING=@i{[OBJ_DIR]} main
10090 Using @command{gnatmake} along with the
10091 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10092 switch provides a mechanism for avoiding unnecessary recompilations. Using
10094 you can update the comments/format of your
10095 source files without having to recompile everything. Note, however, that
10096 adding or deleting lines in a source files may render its debugging
10097 info obsolete. If the file in question is a spec, the impact is rather
10098 limited, as that debugging info will only be useful during the
10099 elaboration phase of your program. For bodies the impact can be more
10100 significant. In all events, your debugger will warn you if a source file
10101 is more recent than the corresponding object, and alert you to the fact
10102 that the debugging information may be out of date.
10105 @node How gnatmake Works
10106 @section How @command{gnatmake} Works
10109 Generally @command{gnatmake} automatically performs all necessary
10110 recompilations and you don't need to worry about how it works. However,
10111 it may be useful to have some basic understanding of the @command{gnatmake}
10112 approach and in particular to understand how it uses the results of
10113 previous compilations without incorrectly depending on them.
10115 First a definition: an object file is considered @dfn{up to date} if the
10116 corresponding ALI file exists and if all the source files listed in the
10117 dependency section of this ALI file have time stamps matching those in
10118 the ALI file. This means that neither the source file itself nor any
10119 files that it depends on have been modified, and hence there is no need
10120 to recompile this file.
10122 @command{gnatmake} works by first checking if the specified main unit is up
10123 to date. If so, no compilations are required for the main unit. If not,
10124 @command{gnatmake} compiles the main program to build a new ALI file that
10125 reflects the latest sources. Then the ALI file of the main unit is
10126 examined to find all the source files on which the main program depends,
10127 and @command{gnatmake} recursively applies the above procedure on all these
10130 This process ensures that @command{gnatmake} only trusts the dependencies
10131 in an existing ALI file if they are known to be correct. Otherwise it
10132 always recompiles to determine a new, guaranteed accurate set of
10133 dependencies. As a result the program is compiled ``upside down'' from what may
10134 be more familiar as the required order of compilation in some other Ada
10135 systems. In particular, clients are compiled before the units on which
10136 they depend. The ability of GNAT to compile in any order is critical in
10137 allowing an order of compilation to be chosen that guarantees that
10138 @command{gnatmake} will recompute a correct set of new dependencies if
10141 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10142 imported by several of the executables, it will be recompiled at most once.
10144 Note: when using non-standard naming conventions
10145 (@pxref{Using Other File Names}), changing through a configuration pragmas
10146 file the version of a source and invoking @command{gnatmake} to recompile may
10147 have no effect, if the previous version of the source is still accessible
10148 by @command{gnatmake}. It may be necessary to use the switch
10149 ^-f^/FORCE_COMPILE^.
10151 @node Examples of gnatmake Usage
10152 @section Examples of @command{gnatmake} Usage
10155 @item gnatmake hello.adb
10156 Compile all files necessary to bind and link the main program
10157 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10158 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10160 @item gnatmake main1 main2 main3
10161 Compile all files necessary to bind and link the main programs
10162 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10163 (containing unit @code{Main2}) and @file{main3.adb}
10164 (containing unit @code{Main3}) and bind and link the resulting object files
10165 to generate three executable files @file{^main1^MAIN1.EXE^},
10166 @file{^main2^MAIN2.EXE^}
10167 and @file{^main3^MAIN3.EXE^}.
10170 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10174 @item gnatmake Main_Unit /QUIET
10175 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10176 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10178 Compile all files necessary to bind and link the main program unit
10179 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10180 be done with optimization level 2 and the order of elaboration will be
10181 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10182 displaying commands it is executing.
10185 @c *************************
10186 @node Improving Performance
10187 @chapter Improving Performance
10188 @cindex Improving performance
10191 This chapter presents several topics related to program performance.
10192 It first describes some of the tradeoffs that need to be considered
10193 and some of the techniques for making your program run faster.
10194 It then documents the @command{gnatelim} tool and unused subprogram/data
10195 elimination feature, which can reduce the size of program executables.
10199 * Performance Considerations::
10200 * Text_IO Suggestions::
10201 * Reducing Size of Ada Executables with gnatelim::
10202 * Reducing Size of Executables with unused subprogram/data elimination::
10206 @c *****************************
10207 @node Performance Considerations
10208 @section Performance Considerations
10211 The GNAT system provides a number of options that allow a trade-off
10216 performance of the generated code
10219 speed of compilation
10222 minimization of dependences and recompilation
10225 the degree of run-time checking.
10229 The defaults (if no options are selected) aim at improving the speed
10230 of compilation and minimizing dependences, at the expense of performance
10231 of the generated code:
10238 no inlining of subprogram calls
10241 all run-time checks enabled except overflow and elaboration checks
10245 These options are suitable for most program development purposes. This
10246 chapter describes how you can modify these choices, and also provides
10247 some guidelines on debugging optimized code.
10250 * Controlling Run-Time Checks::
10251 * Use of Restrictions::
10252 * Optimization Levels::
10253 * Debugging Optimized Code::
10254 * Inlining of Subprograms::
10255 * Vectorization of loops::
10256 * Other Optimization Switches::
10257 * Optimization and Strict Aliasing::
10260 * Coverage Analysis::
10264 @node Controlling Run-Time Checks
10265 @subsection Controlling Run-Time Checks
10268 By default, GNAT generates all run-time checks, except integer overflow
10269 checks, stack overflow checks, and checks for access before elaboration on
10270 subprogram calls. The latter are not required in default mode, because all
10271 necessary checking is done at compile time.
10272 @cindex @option{-gnatp} (@command{gcc})
10273 @cindex @option{-gnato} (@command{gcc})
10274 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10275 be modified. @xref{Run-Time Checks}.
10277 Our experience is that the default is suitable for most development
10280 We treat integer overflow specially because these
10281 are quite expensive and in our experience are not as important as other
10282 run-time checks in the development process. Note that division by zero
10283 is not considered an overflow check, and divide by zero checks are
10284 generated where required by default.
10286 Elaboration checks are off by default, and also not needed by default, since
10287 GNAT uses a static elaboration analysis approach that avoids the need for
10288 run-time checking. This manual contains a full chapter discussing the issue
10289 of elaboration checks, and if the default is not satisfactory for your use,
10290 you should read this chapter.
10292 For validity checks, the minimal checks required by the Ada Reference
10293 Manual (for case statements and assignments to array elements) are on
10294 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10295 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10296 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10297 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10298 are also suppressed entirely if @option{-gnatp} is used.
10300 @cindex Overflow checks
10301 @cindex Checks, overflow
10304 @cindex pragma Suppress
10305 @cindex pragma Unsuppress
10306 Note that the setting of the switches controls the default setting of
10307 the checks. They may be modified using either @code{pragma Suppress} (to
10308 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10309 checks) in the program source.
10311 @node Use of Restrictions
10312 @subsection Use of Restrictions
10315 The use of pragma Restrictions allows you to control which features are
10316 permitted in your program. Apart from the obvious point that if you avoid
10317 relatively expensive features like finalization (enforceable by the use
10318 of pragma Restrictions (No_Finalization), the use of this pragma does not
10319 affect the generated code in most cases.
10321 One notable exception to this rule is that the possibility of task abort
10322 results in some distributed overhead, particularly if finalization or
10323 exception handlers are used. The reason is that certain sections of code
10324 have to be marked as non-abortable.
10326 If you use neither the @code{abort} statement, nor asynchronous transfer
10327 of control (@code{select @dots{} then abort}), then this distributed overhead
10328 is removed, which may have a general positive effect in improving
10329 overall performance. Especially code involving frequent use of tasking
10330 constructs and controlled types will show much improved performance.
10331 The relevant restrictions pragmas are
10333 @smallexample @c ada
10334 pragma Restrictions (No_Abort_Statements);
10335 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10339 It is recommended that these restriction pragmas be used if possible. Note
10340 that this also means that you can write code without worrying about the
10341 possibility of an immediate abort at any point.
10343 @node Optimization Levels
10344 @subsection Optimization Levels
10345 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10348 Without any optimization ^option,^qualifier,^
10349 the compiler's goal is to reduce the cost of
10350 compilation and to make debugging produce the expected results.
10351 Statements are independent: if you stop the program with a breakpoint between
10352 statements, you can then assign a new value to any variable or change
10353 the program counter to any other statement in the subprogram and get exactly
10354 the results you would expect from the source code.
10356 Turning on optimization makes the compiler attempt to improve the
10357 performance and/or code size at the expense of compilation time and
10358 possibly the ability to debug the program.
10360 If you use multiple
10361 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10362 the last such option is the one that is effective.
10365 The default is optimization off. This results in the fastest compile
10366 times, but GNAT makes absolutely no attempt to optimize, and the
10367 generated programs are considerably larger and slower than when
10368 optimization is enabled. You can use the
10370 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10371 @option{-O2}, @option{-O3}, and @option{-Os})
10374 @code{OPTIMIZE} qualifier
10376 to @command{gcc} to control the optimization level:
10379 @item ^-O0^/OPTIMIZE=NONE^
10380 No optimization (the default);
10381 generates unoptimized code but has
10382 the fastest compilation time.
10384 Note that many other compilers do fairly extensive optimization
10385 even if ``no optimization'' is specified. With gcc, it is
10386 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10387 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10388 really does mean no optimization at all. This difference between
10389 gcc and other compilers should be kept in mind when doing
10390 performance comparisons.
10392 @item ^-O1^/OPTIMIZE=SOME^
10393 Moderate optimization;
10394 optimizes reasonably well but does not
10395 degrade compilation time significantly.
10397 @item ^-O2^/OPTIMIZE=ALL^
10399 @itemx /OPTIMIZE=DEVELOPMENT
10402 generates highly optimized code and has
10403 the slowest compilation time.
10405 @item ^-O3^/OPTIMIZE=INLINING^
10406 Full optimization as in @option{-O2};
10407 also uses more aggressive automatic inlining of subprograms within a unit
10408 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10410 @item ^-Os^/OPTIMIZE=SPACE^
10411 Optimize space usage (code and data) of resulting program.
10415 Higher optimization levels perform more global transformations on the
10416 program and apply more expensive analysis algorithms in order to generate
10417 faster and more compact code. The price in compilation time, and the
10418 resulting improvement in execution time,
10419 both depend on the particular application and the hardware environment.
10420 You should experiment to find the best level for your application.
10422 Since the precise set of optimizations done at each level will vary from
10423 release to release (and sometime from target to target), it is best to think
10424 of the optimization settings in general terms.
10425 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10426 the GNU Compiler Collection (GCC)}, for details about
10427 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10428 individually enable or disable specific optimizations.
10430 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10431 been tested extensively at all optimization levels. There are some bugs
10432 which appear only with optimization turned on, but there have also been
10433 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10434 level of optimization does not improve the reliability of the code
10435 generator, which in practice is highly reliable at all optimization
10438 Note regarding the use of @option{-O3}: The use of this optimization level
10439 is generally discouraged with GNAT, since it often results in larger
10440 executables which may run more slowly. See further discussion of this point
10441 in @ref{Inlining of Subprograms}.
10443 @node Debugging Optimized Code
10444 @subsection Debugging Optimized Code
10445 @cindex Debugging optimized code
10446 @cindex Optimization and debugging
10449 Although it is possible to do a reasonable amount of debugging at
10451 nonzero optimization levels,
10452 the higher the level the more likely that
10455 @option{/OPTIMIZE} settings other than @code{NONE},
10456 such settings will make it more likely that
10458 source-level constructs will have been eliminated by optimization.
10459 For example, if a loop is strength-reduced, the loop
10460 control variable may be completely eliminated and thus cannot be
10461 displayed in the debugger.
10462 This can only happen at @option{-O2} or @option{-O3}.
10463 Explicit temporary variables that you code might be eliminated at
10464 ^level^setting^ @option{-O1} or higher.
10466 The use of the @option{^-g^/DEBUG^} switch,
10467 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10468 which is needed for source-level debugging,
10469 affects the size of the program executable on disk,
10470 and indeed the debugging information can be quite large.
10471 However, it has no effect on the generated code (and thus does not
10472 degrade performance)
10474 Since the compiler generates debugging tables for a compilation unit before
10475 it performs optimizations, the optimizing transformations may invalidate some
10476 of the debugging data. You therefore need to anticipate certain
10477 anomalous situations that may arise while debugging optimized code.
10478 These are the most common cases:
10482 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10484 the PC bouncing back and forth in the code. This may result from any of
10485 the following optimizations:
10489 @i{Common subexpression elimination:} using a single instance of code for a
10490 quantity that the source computes several times. As a result you
10491 may not be able to stop on what looks like a statement.
10494 @i{Invariant code motion:} moving an expression that does not change within a
10495 loop, to the beginning of the loop.
10498 @i{Instruction scheduling:} moving instructions so as to
10499 overlap loads and stores (typically) with other code, or in
10500 general to move computations of values closer to their uses. Often
10501 this causes you to pass an assignment statement without the assignment
10502 happening and then later bounce back to the statement when the
10503 value is actually needed. Placing a breakpoint on a line of code
10504 and then stepping over it may, therefore, not always cause all the
10505 expected side-effects.
10509 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10510 two identical pieces of code are merged and the program counter suddenly
10511 jumps to a statement that is not supposed to be executed, simply because
10512 it (and the code following) translates to the same thing as the code
10513 that @emph{was} supposed to be executed. This effect is typically seen in
10514 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10515 a @code{break} in a C @code{^switch^switch^} statement.
10518 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10519 There are various reasons for this effect:
10523 In a subprogram prologue, a parameter may not yet have been moved to its
10527 A variable may be dead, and its register re-used. This is
10528 probably the most common cause.
10531 As mentioned above, the assignment of a value to a variable may
10535 A variable may be eliminated entirely by value propagation or
10536 other means. In this case, GCC may incorrectly generate debugging
10537 information for the variable
10541 In general, when an unexpected value appears for a local variable or parameter
10542 you should first ascertain if that value was actually computed by
10543 your program, as opposed to being incorrectly reported by the debugger.
10545 array elements in an object designated by an access value
10546 are generally less of a problem, once you have ascertained that the access
10548 Typically, this means checking variables in the preceding code and in the
10549 calling subprogram to verify that the value observed is explainable from other
10550 values (one must apply the procedure recursively to those
10551 other values); or re-running the code and stopping a little earlier
10552 (perhaps before the call) and stepping to better see how the variable obtained
10553 the value in question; or continuing to step @emph{from} the point of the
10554 strange value to see if code motion had simply moved the variable's
10559 In light of such anomalies, a recommended technique is to use @option{-O0}
10560 early in the software development cycle, when extensive debugging capabilities
10561 are most needed, and then move to @option{-O1} and later @option{-O2} as
10562 the debugger becomes less critical.
10563 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10564 a release management issue.
10566 Note that if you use @option{-g} you can then use the @command{strip} program
10567 on the resulting executable,
10568 which removes both debugging information and global symbols.
10571 @node Inlining of Subprograms
10572 @subsection Inlining of Subprograms
10575 A call to a subprogram in the current unit is inlined if all the
10576 following conditions are met:
10580 The optimization level is at least @option{-O1}.
10583 The called subprogram is suitable for inlining: It must be small enough
10584 and not contain something that @command{gcc} cannot support in inlined
10588 @cindex pragma Inline
10590 Any one of the following applies: @code{pragma Inline} is applied to the
10591 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10592 subprogram is local to the unit and called once from within it; the
10593 subprogram is small and optimization level @option{-O2} is specified;
10594 optimization level @option{-O3}) is specified.
10598 Calls to subprograms in @code{with}'ed units are normally not inlined.
10599 To achieve actual inlining (that is, replacement of the call by the code
10600 in the body of the subprogram), the following conditions must all be true.
10604 The optimization level is at least @option{-O1}.
10607 The called subprogram is suitable for inlining: It must be small enough
10608 and not contain something that @command{gcc} cannot support in inlined
10612 The call appears in a body (not in a package spec).
10615 There is a @code{pragma Inline} for the subprogram.
10618 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10621 Even if all these conditions are met, it may not be possible for
10622 the compiler to inline the call, due to the length of the body,
10623 or features in the body that make it impossible for the compiler
10624 to do the inlining.
10626 Note that specifying the @option{-gnatn} switch causes additional
10627 compilation dependencies. Consider the following:
10629 @smallexample @c ada
10649 With the default behavior (no @option{-gnatn} switch specified), the
10650 compilation of the @code{Main} procedure depends only on its own source,
10651 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10652 means that editing the body of @code{R} does not require recompiling
10655 On the other hand, the call @code{R.Q} is not inlined under these
10656 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10657 is compiled, the call will be inlined if the body of @code{Q} is small
10658 enough, but now @code{Main} depends on the body of @code{R} in
10659 @file{r.adb} as well as on the spec. This means that if this body is edited,
10660 the main program must be recompiled. Note that this extra dependency
10661 occurs whether or not the call is in fact inlined by @command{gcc}.
10663 The use of front end inlining with @option{-gnatN} generates similar
10664 additional dependencies.
10666 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10667 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10668 can be used to prevent
10669 all inlining. This switch overrides all other conditions and ensures
10670 that no inlining occurs. The extra dependences resulting from
10671 @option{-gnatn} will still be active, even if
10672 this switch is used to suppress the resulting inlining actions.
10674 @cindex @option{-fno-inline-functions} (@command{gcc})
10675 Note: The @option{-fno-inline-functions} switch can be used to prevent
10676 automatic inlining of subprograms if @option{-O3} is used.
10678 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10679 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10680 automatic inlining of small subprograms if @option{-O2} is used.
10682 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10683 Note: The @option{-fno-inline-functions-called-once} switch
10684 can be used to prevent inlining of subprograms local to the unit
10685 and called once from within it if @option{-O1} is used.
10687 Note regarding the use of @option{-O3}: There is no difference in inlining
10688 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10689 pragma @code{Inline} assuming the use of @option{-gnatn}
10690 or @option{-gnatN} (the switches that activate inlining). If you have used
10691 pragma @code{Inline} in appropriate cases, then it is usually much better
10692 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10693 in this case only has the effect of inlining subprograms you did not
10694 think should be inlined. We often find that the use of @option{-O3} slows
10695 down code by performing excessive inlining, leading to increased instruction
10696 cache pressure from the increased code size. So the bottom line here is
10697 that you should not automatically assume that @option{-O3} is better than
10698 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10699 it actually improves performance.
10701 @node Vectorization of loops
10702 @subsection Vectorization of loops
10703 @cindex Optimization Switches
10705 You can take advantage of the auto-vectorizer present in the @command{gcc}
10706 back end to vectorize loops with GNAT. The corresponding command line switch
10707 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10708 and other aggressive optimizations helpful for vectorization also are enabled
10709 by default at this level, using @option{-O3} directly is recommended.
10711 You also need to make sure that the target architecture features a supported
10712 SIMD instruction set. For example, for the x86 architecture, you should at
10713 least specify @option{-msse2} to get significant vectorization (but you don't
10714 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10715 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10717 The preferred loop form for vectorization is the @code{for} iteration scheme.
10718 Loops with a @code{while} iteration scheme can also be vectorized if they are
10719 very simple, but the vectorizer will quickly give up otherwise. With either
10720 iteration scheme, the flow of control must be straight, in particular no
10721 @code{exit} statement may appear in the loop body. The loop may however
10722 contain a single nested loop, if it can be vectorized when considered alone:
10724 @smallexample @c ada
10726 A : array (1..4, 1..4) of Long_Float;
10727 S : array (1..4) of Long_Float;
10731 for I in A'Range(1) loop
10732 for J in A'Range(2) loop
10733 S (I) := S (I) + A (I, J);
10740 The vectorizable operations depend on the targeted SIMD instruction set, but
10741 the adding and some of the multiplying operators are generally supported, as
10742 well as the logical operators for modular types. Note that, in the former
10743 case, enabling overflow checks, for example with @option{-gnato}, totally
10744 disables vectorization. The other checks are not supposed to have the same
10745 definitive effect, although compiling with @option{-gnatp} might well reveal
10746 cases where some checks do thwart vectorization.
10748 Type conversions may also prevent vectorization if they involve semantics that
10749 are not directly supported by the code generator or the SIMD instruction set.
10750 A typical example is direct conversion from floating-point to integer types.
10751 The solution in this case is to use the following idiom:
10753 @smallexample @c ada
10754 Integer (S'Truncation (F))
10758 if @code{S} is the subtype of floating-point object @code{F}.
10760 In most cases, the vectorizable loops are loops that iterate over arrays.
10761 All kinds of array types are supported, i.e. constrained array types with
10764 @smallexample @c ada
10765 type Array_Type is array (1 .. 4) of Long_Float;
10769 constrained array types with dynamic bounds:
10771 @smallexample @c ada
10772 type Array_Type is array (1 .. Q.N) of Long_Float;
10774 type Array_Type is array (Q.K .. 4) of Long_Float;
10776 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10780 or unconstrained array types:
10782 @smallexample @c ada
10783 type Array_Type is array (Positive range <>) of Long_Float;
10787 The quality of the generated code decreases when the dynamic aspect of the
10788 array type increases, the worst code being generated for unconstrained array
10789 types. This is so because, the less information the compiler has about the
10790 bounds of the array, the more fallback code it needs to generate in order to
10791 fix things up at run time.
10793 You can obtain information about the vectorization performed by the compiler
10794 by specifying @option{-ftree-vectorizer-verbose=N}. For more details of
10795 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10796 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10798 @node Other Optimization Switches
10799 @subsection Other Optimization Switches
10800 @cindex Optimization Switches
10802 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10803 @command{gcc} optimization switches are potentially usable. These switches
10804 have not been extensively tested with GNAT but can generally be expected
10805 to work. Examples of switches in this category are @option{-funroll-loops}
10806 and the various target-specific @option{-m} options (in particular, it has
10807 been observed that @option{-march=xxx} can significantly improve performance
10808 on appropriate machines). For full details of these switches, see
10809 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10810 the GNU Compiler Collection (GCC)}.
10812 @node Optimization and Strict Aliasing
10813 @subsection Optimization and Strict Aliasing
10815 @cindex Strict Aliasing
10816 @cindex No_Strict_Aliasing
10819 The strong typing capabilities of Ada allow an optimizer to generate
10820 efficient code in situations where other languages would be forced to
10821 make worst case assumptions preventing such optimizations. Consider
10822 the following example:
10824 @smallexample @c ada
10827 type Int1 is new Integer;
10828 type Int2 is new Integer;
10829 type Int1A is access Int1;
10830 type Int2A is access Int2;
10837 for J in Data'Range loop
10838 if Data (J) = Int1V.all then
10839 Int2V.all := Int2V.all + 1;
10848 In this example, since the variable @code{Int1V} can only access objects
10849 of type @code{Int1}, and @code{Int2V} can only access objects of type
10850 @code{Int2}, there is no possibility that the assignment to
10851 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10852 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10853 for all iterations of the loop and avoid the extra memory reference
10854 required to dereference it each time through the loop.
10856 This kind of optimization, called strict aliasing analysis, is
10857 triggered by specifying an optimization level of @option{-O2} or
10858 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10859 when access values are involved.
10861 However, although this optimization is always correct in terms of
10862 the formal semantics of the Ada Reference Manual, difficulties can
10863 arise if features like @code{Unchecked_Conversion} are used to break
10864 the typing system. Consider the following complete program example:
10866 @smallexample @c ada
10869 type int1 is new integer;
10870 type int2 is new integer;
10871 type a1 is access int1;
10872 type a2 is access int2;
10877 function to_a2 (Input : a1) return a2;
10880 with Unchecked_Conversion;
10882 function to_a2 (Input : a1) return a2 is
10884 new Unchecked_Conversion (a1, a2);
10886 return to_a2u (Input);
10892 with Text_IO; use Text_IO;
10894 v1 : a1 := new int1;
10895 v2 : a2 := to_a2 (v1);
10899 put_line (int1'image (v1.all));
10905 This program prints out 0 in @option{-O0} or @option{-O1}
10906 mode, but it prints out 1 in @option{-O2} mode. That's
10907 because in strict aliasing mode, the compiler can and
10908 does assume that the assignment to @code{v2.all} could not
10909 affect the value of @code{v1.all}, since different types
10912 This behavior is not a case of non-conformance with the standard, since
10913 the Ada RM specifies that an unchecked conversion where the resulting
10914 bit pattern is not a correct value of the target type can result in an
10915 abnormal value and attempting to reference an abnormal value makes the
10916 execution of a program erroneous. That's the case here since the result
10917 does not point to an object of type @code{int2}. This means that the
10918 effect is entirely unpredictable.
10920 However, although that explanation may satisfy a language
10921 lawyer, in practice an applications programmer expects an
10922 unchecked conversion involving pointers to create true
10923 aliases and the behavior of printing 1 seems plain wrong.
10924 In this case, the strict aliasing optimization is unwelcome.
10926 Indeed the compiler recognizes this possibility, and the
10927 unchecked conversion generates a warning:
10930 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10931 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10932 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10936 Unfortunately the problem is recognized when compiling the body of
10937 package @code{p2}, but the actual "bad" code is generated while
10938 compiling the body of @code{m} and this latter compilation does not see
10939 the suspicious @code{Unchecked_Conversion}.
10941 As implied by the warning message, there are approaches you can use to
10942 avoid the unwanted strict aliasing optimization in a case like this.
10944 One possibility is to simply avoid the use of @option{-O2}, but
10945 that is a bit drastic, since it throws away a number of useful
10946 optimizations that do not involve strict aliasing assumptions.
10948 A less drastic approach is to compile the program using the
10949 option @option{-fno-strict-aliasing}. Actually it is only the
10950 unit containing the dereferencing of the suspicious pointer
10951 that needs to be compiled. So in this case, if we compile
10952 unit @code{m} with this switch, then we get the expected
10953 value of zero printed. Analyzing which units might need
10954 the switch can be painful, so a more reasonable approach
10955 is to compile the entire program with options @option{-O2}
10956 and @option{-fno-strict-aliasing}. If the performance is
10957 satisfactory with this combination of options, then the
10958 advantage is that the entire issue of possible "wrong"
10959 optimization due to strict aliasing is avoided.
10961 To avoid the use of compiler switches, the configuration
10962 pragma @code{No_Strict_Aliasing} with no parameters may be
10963 used to specify that for all access types, the strict
10964 aliasing optimization should be suppressed.
10966 However, these approaches are still overkill, in that they causes
10967 all manipulations of all access values to be deoptimized. A more
10968 refined approach is to concentrate attention on the specific
10969 access type identified as problematic.
10971 First, if a careful analysis of uses of the pointer shows
10972 that there are no possible problematic references, then
10973 the warning can be suppressed by bracketing the
10974 instantiation of @code{Unchecked_Conversion} to turn
10977 @smallexample @c ada
10978 pragma Warnings (Off);
10980 new Unchecked_Conversion (a1, a2);
10981 pragma Warnings (On);
10985 Of course that approach is not appropriate for this particular
10986 example, since indeed there is a problematic reference. In this
10987 case we can take one of two other approaches.
10989 The first possibility is to move the instantiation of unchecked
10990 conversion to the unit in which the type is declared. In
10991 this example, we would move the instantiation of
10992 @code{Unchecked_Conversion} from the body of package
10993 @code{p2} to the spec of package @code{p1}. Now the
10994 warning disappears. That's because any use of the
10995 access type knows there is a suspicious unchecked
10996 conversion, and the strict aliasing optimization
10997 is automatically suppressed for the type.
10999 If it is not practical to move the unchecked conversion to the same unit
11000 in which the destination access type is declared (perhaps because the
11001 source type is not visible in that unit), you may use pragma
11002 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11003 same declarative sequence as the declaration of the access type:
11005 @smallexample @c ada
11006 type a2 is access int2;
11007 pragma No_Strict_Aliasing (a2);
11011 Here again, the compiler now knows that the strict aliasing optimization
11012 should be suppressed for any reference to type @code{a2} and the
11013 expected behavior is obtained.
11015 Finally, note that although the compiler can generate warnings for
11016 simple cases of unchecked conversions, there are tricker and more
11017 indirect ways of creating type incorrect aliases which the compiler
11018 cannot detect. Examples are the use of address overlays and unchecked
11019 conversions involving composite types containing access types as
11020 components. In such cases, no warnings are generated, but there can
11021 still be aliasing problems. One safe coding practice is to forbid the
11022 use of address clauses for type overlaying, and to allow unchecked
11023 conversion only for primitive types. This is not really a significant
11024 restriction since any possible desired effect can be achieved by
11025 unchecked conversion of access values.
11027 The aliasing analysis done in strict aliasing mode can certainly
11028 have significant benefits. We have seen cases of large scale
11029 application code where the time is increased by up to 5% by turning
11030 this optimization off. If you have code that includes significant
11031 usage of unchecked conversion, you might want to just stick with
11032 @option{-O1} and avoid the entire issue. If you get adequate
11033 performance at this level of optimization level, that's probably
11034 the safest approach. If tests show that you really need higher
11035 levels of optimization, then you can experiment with @option{-O2}
11036 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11037 has on size and speed of the code. If you really need to use
11038 @option{-O2} with strict aliasing in effect, then you should
11039 review any uses of unchecked conversion of access types,
11040 particularly if you are getting the warnings described above.
11043 @node Coverage Analysis
11044 @subsection Coverage Analysis
11047 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11048 the user to determine the distribution of execution time across a program,
11049 @pxref{Profiling} for details of usage.
11053 @node Text_IO Suggestions
11054 @section @code{Text_IO} Suggestions
11055 @cindex @code{Text_IO} and performance
11058 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11059 the requirement of maintaining page and line counts. If performance
11060 is critical, a recommendation is to use @code{Stream_IO} instead of
11061 @code{Text_IO} for volume output, since this package has less overhead.
11063 If @code{Text_IO} must be used, note that by default output to the standard
11064 output and standard error files is unbuffered (this provides better
11065 behavior when output statements are used for debugging, or if the
11066 progress of a program is observed by tracking the output, e.g. by
11067 using the Unix @command{tail -f} command to watch redirected output.
11069 If you are generating large volumes of output with @code{Text_IO} and
11070 performance is an important factor, use a designated file instead
11071 of the standard output file, or change the standard output file to
11072 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11076 @node Reducing Size of Ada Executables with gnatelim
11077 @section Reducing Size of Ada Executables with @code{gnatelim}
11081 This section describes @command{gnatelim}, a tool which detects unused
11082 subprograms and helps the compiler to create a smaller executable for your
11087 * Running gnatelim::
11088 * Processing Precompiled Libraries::
11089 * Correcting the List of Eliminate Pragmas::
11090 * Making Your Executables Smaller::
11091 * Summary of the gnatelim Usage Cycle::
11094 @node About gnatelim
11095 @subsection About @code{gnatelim}
11098 When a program shares a set of Ada
11099 packages with other programs, it may happen that this program uses
11100 only a fraction of the subprograms defined in these packages. The code
11101 created for these unused subprograms increases the size of the executable.
11103 @code{gnatelim} tracks unused subprograms in an Ada program and
11104 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11105 subprograms that are declared but never called. By placing the list of
11106 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11107 recompiling your program, you may decrease the size of its executable,
11108 because the compiler will not generate the code for 'eliminated' subprograms.
11109 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11110 information about this pragma.
11112 @code{gnatelim} needs as its input data the name of the main subprogram.
11114 If a set of source files is specified as @code{gnatelim} arguments, it
11115 treats these files as a complete set of sources making up a program to
11116 analyse, and analyses only these sources.
11118 After a full successful build of the main subprogram @code{gnatelim} can be
11119 called without specifying sources to analyse, in this case it computes
11120 the source closure of the main unit from the @file{ALI} files.
11122 The following command will create the set of @file{ALI} files needed for
11126 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11129 Note that @code{gnatelim} does not need object files.
11131 @node Running gnatelim
11132 @subsection Running @code{gnatelim}
11135 @code{gnatelim} has the following command-line interface:
11138 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11142 @var{main_unit_name} should be a name of a source file that contains the main
11143 subprogram of a program (partition).
11145 Each @var{filename} is the name (including the extension) of a source
11146 file to process. ``Wildcards'' are allowed, and
11147 the file name may contain path information.
11149 @samp{@var{gcc_switches}} is a list of switches for
11150 @command{gcc}. They will be passed on to all compiler invocations made by
11151 @command{gnatelim} to generate the ASIS trees. Here you can provide
11152 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11153 use the @option{-gnatec} switch to set the configuration file,
11154 use the @option{-gnat05} switch if sources should be compiled in
11157 @code{gnatelim} has the following switches:
11161 @item ^-files^/FILES^=@var{filename}
11162 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11163 Take the argument source files from the specified file. This file should be an
11164 ordinary text file containing file names separated by spaces or
11165 line breaks. You can use this switch more than once in the same call to
11166 @command{gnatelim}. You also can combine this switch with
11167 an explicit list of files.
11170 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11171 Duplicate all the output sent to @file{stderr} into a log file. The log file
11172 is named @file{gnatelim.log} and is located in the current directory.
11174 @item ^-log^/LOGFILE^=@var{filename}
11175 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11176 Duplicate all the output sent to @file{stderr} into a specified log file.
11178 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11179 @item ^--no-elim-dispatch^/NO_DISPATCH^
11180 Do not generate pragmas for dispatching operations.
11182 @item ^--ignore^/IGNORE^=@var{filename}
11183 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11184 Do not generate pragmas for subprograms declared in the sources
11185 listed in a specified file
11187 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11188 @item ^-o^/OUTPUT^=@var{report_file}
11189 Put @command{gnatelim} output into a specified file. If this file already exists,
11190 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11194 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11195 Quiet mode: by default @code{gnatelim} outputs to the standard error
11196 stream the number of program units left to be processed. This option turns
11199 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11201 Print out execution time.
11203 @item ^-v^/VERBOSE^
11204 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11205 Verbose mode: @code{gnatelim} version information is printed as Ada
11206 comments to the standard output stream. Also, in addition to the number of
11207 program units left @code{gnatelim} will output the name of the current unit
11210 @item ^-wq^/WARNINGS=QUIET^
11211 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11212 Quiet warning mode - some warnings are suppressed. In particular warnings that
11213 indicate that the analysed set of sources is incomplete to make up a
11214 partition and that some subprogram bodies are missing are not generated.
11218 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11219 driver (see @ref{The GNAT Driver and Project Files}).
11221 @node Processing Precompiled Libraries
11222 @subsection Processing Precompiled Libraries
11225 If some program uses a precompiled Ada library, it can be processed by
11226 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11227 Eliminate pragma for a subprogram if the body of this subprogram has not
11228 been analysed, this is a typical case for subprograms from precompiled
11229 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11230 warnings about missing source files and non-analyzed subprogram bodies
11231 that can be generated when processing precompiled Ada libraries.
11233 @node Correcting the List of Eliminate Pragmas
11234 @subsection Correcting the List of Eliminate Pragmas
11237 In some rare cases @code{gnatelim} may try to eliminate
11238 subprograms that are actually called in the program. In this case, the
11239 compiler will generate an error message of the form:
11242 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11246 You will need to manually remove the wrong @code{Eliminate} pragmas from
11247 the configuration file indicated in the error message. You should recompile
11248 your program from scratch after that, because you need a consistent
11249 configuration file(s) during the entire compilation.
11251 @node Making Your Executables Smaller
11252 @subsection Making Your Executables Smaller
11255 In order to get a smaller executable for your program you now have to
11256 recompile the program completely with the configuration file containing
11257 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11258 @file{gnat.adc} file located in your current directory, just do:
11261 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11265 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11266 recompile everything
11267 with the set of pragmas @code{Eliminate} that you have obtained with
11268 @command{gnatelim}).
11270 Be aware that the set of @code{Eliminate} pragmas is specific to each
11271 program. It is not recommended to merge sets of @code{Eliminate}
11272 pragmas created for different programs in one configuration file.
11274 @node Summary of the gnatelim Usage Cycle
11275 @subsection Summary of the @code{gnatelim} Usage Cycle
11278 Here is a quick summary of the steps to be taken in order to reduce
11279 the size of your executables with @code{gnatelim}. You may use
11280 other GNAT options to control the optimization level,
11281 to produce the debugging information, to set search path, etc.
11285 Create a complete set of @file{ALI} files (if the program has not been
11289 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11293 Generate a list of @code{Eliminate} pragmas in default configuration file
11294 @file{gnat.adc} in the current directory
11297 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11300 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11305 Recompile the application
11308 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11313 @node Reducing Size of Executables with unused subprogram/data elimination
11314 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11315 @findex unused subprogram/data elimination
11318 This section describes how you can eliminate unused subprograms and data from
11319 your executable just by setting options at compilation time.
11322 * About unused subprogram/data elimination::
11323 * Compilation options::
11324 * Example of unused subprogram/data elimination::
11327 @node About unused subprogram/data elimination
11328 @subsection About unused subprogram/data elimination
11331 By default, an executable contains all code and data of its composing objects
11332 (directly linked or coming from statically linked libraries), even data or code
11333 never used by this executable.
11335 This feature will allow you to eliminate such unused code from your
11336 executable, making it smaller (in disk and in memory).
11338 This functionality is available on all Linux platforms except for the IA-64
11339 architecture and on all cross platforms using the ELF binary file format.
11340 In both cases GNU binutils version 2.16 or later are required to enable it.
11342 @node Compilation options
11343 @subsection Compilation options
11346 The operation of eliminating the unused code and data from the final executable
11347 is directly performed by the linker.
11349 In order to do this, it has to work with objects compiled with the
11351 @option{-ffunction-sections} @option{-fdata-sections}.
11352 @cindex @option{-ffunction-sections} (@command{gcc})
11353 @cindex @option{-fdata-sections} (@command{gcc})
11354 These options are usable with C and Ada files.
11355 They will place respectively each
11356 function or data in a separate section in the resulting object file.
11358 Once the objects and static libraries are created with these options, the
11359 linker can perform the dead code elimination. You can do this by setting
11360 the @option{-Wl,--gc-sections} option to gcc command or in the
11361 @option{-largs} section of @command{gnatmake}. This will perform a
11362 garbage collection of code and data never referenced.
11364 If the linker performs a partial link (@option{-r} ld linker option), then you
11365 will need to provide one or several entry point using the
11366 @option{-e} / @option{--entry} ld option.
11368 Note that objects compiled without the @option{-ffunction-sections} and
11369 @option{-fdata-sections} options can still be linked with the executable.
11370 However, no dead code elimination will be performed on those objects (they will
11373 The GNAT static library is now compiled with -ffunction-sections and
11374 -fdata-sections on some platforms. This allows you to eliminate the unused code
11375 and data of the GNAT library from your executable.
11377 @node Example of unused subprogram/data elimination
11378 @subsection Example of unused subprogram/data elimination
11381 Here is a simple example:
11383 @smallexample @c ada
11392 Used_Data : Integer;
11393 Unused_Data : Integer;
11395 procedure Used (Data : Integer);
11396 procedure Unused (Data : Integer);
11399 package body Aux is
11400 procedure Used (Data : Integer) is
11405 procedure Unused (Data : Integer) is
11407 Unused_Data := Data;
11413 @code{Unused} and @code{Unused_Data} are never referenced in this code
11414 excerpt, and hence they may be safely removed from the final executable.
11419 $ nm test | grep used
11420 020015f0 T aux__unused
11421 02005d88 B aux__unused_data
11422 020015cc T aux__used
11423 02005d84 B aux__used_data
11425 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11426 -largs -Wl,--gc-sections
11428 $ nm test | grep used
11429 02005350 T aux__used
11430 0201ffe0 B aux__used_data
11434 It can be observed that the procedure @code{Unused} and the object
11435 @code{Unused_Data} are removed by the linker when using the
11436 appropriate options.
11438 @c ********************************
11439 @node Renaming Files Using gnatchop
11440 @chapter Renaming Files Using @code{gnatchop}
11444 This chapter discusses how to handle files with multiple units by using
11445 the @code{gnatchop} utility. This utility is also useful in renaming
11446 files to meet the standard GNAT default file naming conventions.
11449 * Handling Files with Multiple Units::
11450 * Operating gnatchop in Compilation Mode::
11451 * Command Line for gnatchop::
11452 * Switches for gnatchop::
11453 * Examples of gnatchop Usage::
11456 @node Handling Files with Multiple Units
11457 @section Handling Files with Multiple Units
11460 The basic compilation model of GNAT requires that a file submitted to the
11461 compiler have only one unit and there be a strict correspondence
11462 between the file name and the unit name.
11464 The @code{gnatchop} utility allows both of these rules to be relaxed,
11465 allowing GNAT to process files which contain multiple compilation units
11466 and files with arbitrary file names. @code{gnatchop}
11467 reads the specified file and generates one or more output files,
11468 containing one unit per file. The unit and the file name correspond,
11469 as required by GNAT.
11471 If you want to permanently restructure a set of ``foreign'' files so that
11472 they match the GNAT rules, and do the remaining development using the
11473 GNAT structure, you can simply use @command{gnatchop} once, generate the
11474 new set of files and work with them from that point on.
11476 Alternatively, if you want to keep your files in the ``foreign'' format,
11477 perhaps to maintain compatibility with some other Ada compilation
11478 system, you can set up a procedure where you use @command{gnatchop} each
11479 time you compile, regarding the source files that it writes as temporary
11480 files that you throw away.
11482 Note that if your file containing multiple units starts with a byte order
11483 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11484 will each start with a copy of this BOM, meaning that they can be compiled
11485 automatically in UTF-8 mode without needing to specify an explicit encoding.
11487 @node Operating gnatchop in Compilation Mode
11488 @section Operating gnatchop in Compilation Mode
11491 The basic function of @code{gnatchop} is to take a file with multiple units
11492 and split it into separate files. The boundary between files is reasonably
11493 clear, except for the issue of comments and pragmas. In default mode, the
11494 rule is that any pragmas between units belong to the previous unit, except
11495 that configuration pragmas always belong to the following unit. Any comments
11496 belong to the following unit. These rules
11497 almost always result in the right choice of
11498 the split point without needing to mark it explicitly and most users will
11499 find this default to be what they want. In this default mode it is incorrect to
11500 submit a file containing only configuration pragmas, or one that ends in
11501 configuration pragmas, to @code{gnatchop}.
11503 However, using a special option to activate ``compilation mode'',
11505 can perform another function, which is to provide exactly the semantics
11506 required by the RM for handling of configuration pragmas in a compilation.
11507 In the absence of configuration pragmas (at the main file level), this
11508 option has no effect, but it causes such configuration pragmas to be handled
11509 in a quite different manner.
11511 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11512 only configuration pragmas, then this file is appended to the
11513 @file{gnat.adc} file in the current directory. This behavior provides
11514 the required behavior described in the RM for the actions to be taken
11515 on submitting such a file to the compiler, namely that these pragmas
11516 should apply to all subsequent compilations in the same compilation
11517 environment. Using GNAT, the current directory, possibly containing a
11518 @file{gnat.adc} file is the representation
11519 of a compilation environment. For more information on the
11520 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11522 Second, in compilation mode, if @code{gnatchop}
11523 is given a file that starts with
11524 configuration pragmas, and contains one or more units, then these
11525 configuration pragmas are prepended to each of the chopped files. This
11526 behavior provides the required behavior described in the RM for the
11527 actions to be taken on compiling such a file, namely that the pragmas
11528 apply to all units in the compilation, but not to subsequently compiled
11531 Finally, if configuration pragmas appear between units, they are appended
11532 to the previous unit. This results in the previous unit being illegal,
11533 since the compiler does not accept configuration pragmas that follow
11534 a unit. This provides the required RM behavior that forbids configuration
11535 pragmas other than those preceding the first compilation unit of a
11538 For most purposes, @code{gnatchop} will be used in default mode. The
11539 compilation mode described above is used only if you need exactly
11540 accurate behavior with respect to compilations, and you have files
11541 that contain multiple units and configuration pragmas. In this
11542 circumstance the use of @code{gnatchop} with the compilation mode
11543 switch provides the required behavior, and is for example the mode
11544 in which GNAT processes the ACVC tests.
11546 @node Command Line for gnatchop
11547 @section Command Line for @code{gnatchop}
11550 The @code{gnatchop} command has the form:
11553 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11554 @c @ovar{directory}
11555 @c Expanding @ovar macro inline (explanation in macro def comments)
11556 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11557 @r{[}@var{directory}@r{]}
11561 The only required argument is the file name of the file to be chopped.
11562 There are no restrictions on the form of this file name. The file itself
11563 contains one or more Ada units, in normal GNAT format, concatenated
11564 together. As shown, more than one file may be presented to be chopped.
11566 When run in default mode, @code{gnatchop} generates one output file in
11567 the current directory for each unit in each of the files.
11569 @var{directory}, if specified, gives the name of the directory to which
11570 the output files will be written. If it is not specified, all files are
11571 written to the current directory.
11573 For example, given a
11574 file called @file{hellofiles} containing
11576 @smallexample @c ada
11581 with Text_IO; use Text_IO;
11584 Put_Line ("Hello");
11594 $ gnatchop ^hellofiles^HELLOFILES.^
11598 generates two files in the current directory, one called
11599 @file{hello.ads} containing the single line that is the procedure spec,
11600 and the other called @file{hello.adb} containing the remaining text. The
11601 original file is not affected. The generated files can be compiled in
11605 When gnatchop is invoked on a file that is empty or that contains only empty
11606 lines and/or comments, gnatchop will not fail, but will not produce any
11609 For example, given a
11610 file called @file{toto.txt} containing
11612 @smallexample @c ada
11624 $ gnatchop ^toto.txt^TOT.TXT^
11628 will not produce any new file and will result in the following warnings:
11631 toto.txt:1:01: warning: empty file, contains no compilation units
11632 no compilation units found
11633 no source files written
11636 @node Switches for gnatchop
11637 @section Switches for @code{gnatchop}
11640 @command{gnatchop} recognizes the following switches:
11646 @cindex @option{--version} @command{gnatchop}
11647 Display Copyright and version, then exit disregarding all other options.
11650 @cindex @option{--help} @command{gnatchop}
11651 If @option{--version} was not used, display usage, then exit disregarding
11654 @item ^-c^/COMPILATION^
11655 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11656 Causes @code{gnatchop} to operate in compilation mode, in which
11657 configuration pragmas are handled according to strict RM rules. See
11658 previous section for a full description of this mode.
11661 @item -gnat@var{xxx}
11662 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11663 used to parse the given file. Not all @var{xxx} options make sense,
11664 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11665 process a source file that uses Latin-2 coding for identifiers.
11669 Causes @code{gnatchop} to generate a brief help summary to the standard
11670 output file showing usage information.
11672 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11673 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11674 Limit generated file names to the specified number @code{mm}
11676 This is useful if the
11677 resulting set of files is required to be interoperable with systems
11678 which limit the length of file names.
11680 If no value is given, or
11681 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11682 a default of 39, suitable for OpenVMS Alpha
11683 Systems, is assumed
11686 No space is allowed between the @option{-k} and the numeric value. The numeric
11687 value may be omitted in which case a default of @option{-k8},
11689 with DOS-like file systems, is used. If no @option{-k} switch
11691 there is no limit on the length of file names.
11694 @item ^-p^/PRESERVE^
11695 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11696 Causes the file ^modification^creation^ time stamp of the input file to be
11697 preserved and used for the time stamp of the output file(s). This may be
11698 useful for preserving coherency of time stamps in an environment where
11699 @code{gnatchop} is used as part of a standard build process.
11702 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11703 Causes output of informational messages indicating the set of generated
11704 files to be suppressed. Warnings and error messages are unaffected.
11706 @item ^-r^/REFERENCE^
11707 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11708 @findex Source_Reference
11709 Generate @code{Source_Reference} pragmas. Use this switch if the output
11710 files are regarded as temporary and development is to be done in terms
11711 of the original unchopped file. This switch causes
11712 @code{Source_Reference} pragmas to be inserted into each of the
11713 generated files to refers back to the original file name and line number.
11714 The result is that all error messages refer back to the original
11716 In addition, the debugging information placed into the object file (when
11717 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11719 also refers back to this original file so that tools like profilers and
11720 debuggers will give information in terms of the original unchopped file.
11722 If the original file to be chopped itself contains
11723 a @code{Source_Reference}
11724 pragma referencing a third file, then gnatchop respects
11725 this pragma, and the generated @code{Source_Reference} pragmas
11726 in the chopped file refer to the original file, with appropriate
11727 line numbers. This is particularly useful when @code{gnatchop}
11728 is used in conjunction with @code{gnatprep} to compile files that
11729 contain preprocessing statements and multiple units.
11731 @item ^-v^/VERBOSE^
11732 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11733 Causes @code{gnatchop} to operate in verbose mode. The version
11734 number and copyright notice are output, as well as exact copies of
11735 the gnat1 commands spawned to obtain the chop control information.
11737 @item ^-w^/OVERWRITE^
11738 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11739 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11740 fatal error if there is already a file with the same name as a
11741 file it would otherwise output, in other words if the files to be
11742 chopped contain duplicated units. This switch bypasses this
11743 check, and causes all but the last instance of such duplicated
11744 units to be skipped.
11747 @item --GCC=@var{xxxx}
11748 @cindex @option{--GCC=} (@code{gnatchop})
11749 Specify the path of the GNAT parser to be used. When this switch is used,
11750 no attempt is made to add the prefix to the GNAT parser executable.
11754 @node Examples of gnatchop Usage
11755 @section Examples of @code{gnatchop} Usage
11759 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11762 @item gnatchop -w hello_s.ada prerelease/files
11765 Chops the source file @file{hello_s.ada}. The output files will be
11766 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11768 files with matching names in that directory (no files in the current
11769 directory are modified).
11771 @item gnatchop ^archive^ARCHIVE.^
11772 Chops the source file @file{^archive^ARCHIVE.^}
11773 into the current directory. One
11774 useful application of @code{gnatchop} is in sending sets of sources
11775 around, for example in email messages. The required sources are simply
11776 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11778 @command{gnatchop} is used at the other end to reconstitute the original
11781 @item gnatchop file1 file2 file3 direc
11782 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11783 the resulting files in the directory @file{direc}. Note that if any units
11784 occur more than once anywhere within this set of files, an error message
11785 is generated, and no files are written. To override this check, use the
11786 @option{^-w^/OVERWRITE^} switch,
11787 in which case the last occurrence in the last file will
11788 be the one that is output, and earlier duplicate occurrences for a given
11789 unit will be skipped.
11792 @node Configuration Pragmas
11793 @chapter Configuration Pragmas
11794 @cindex Configuration pragmas
11795 @cindex Pragmas, configuration
11798 Configuration pragmas include those pragmas described as
11799 such in the Ada Reference Manual, as well as
11800 implementation-dependent pragmas that are configuration pragmas.
11801 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11802 for details on these additional GNAT-specific configuration pragmas.
11803 Most notably, the pragma @code{Source_File_Name}, which allows
11804 specifying non-default names for source files, is a configuration
11805 pragma. The following is a complete list of configuration pragmas
11806 recognized by GNAT:
11817 Assume_No_Invalid_Values
11822 Compile_Time_Warning
11824 Component_Alignment
11825 Convention_Identifier
11828 Default_Storage_Pool
11834 External_Name_Casing
11837 Float_Representation
11850 Priority_Specific_Dispatching
11853 Propagate_Exceptions
11856 Restricted_Run_Time
11858 Restrictions_Warnings
11860 Short_Circuit_And_Or
11862 Source_File_Name_Project
11865 Suppress_Exception_Locations
11866 Task_Dispatching_Policy
11872 Wide_Character_Encoding
11877 * Handling of Configuration Pragmas::
11878 * The Configuration Pragmas Files::
11881 @node Handling of Configuration Pragmas
11882 @section Handling of Configuration Pragmas
11884 Configuration pragmas may either appear at the start of a compilation
11885 unit, or they can appear in a configuration pragma file to apply to
11886 all compilations performed in a given compilation environment.
11888 GNAT also provides the @code{gnatchop} utility to provide an automatic
11889 way to handle configuration pragmas following the semantics for
11890 compilations (that is, files with multiple units), described in the RM.
11891 See @ref{Operating gnatchop in Compilation Mode} for details.
11892 However, for most purposes, it will be more convenient to edit the
11893 @file{gnat.adc} file that contains configuration pragmas directly,
11894 as described in the following section.
11896 In the case of @code{Restrictions} pragmas appearing as configuration
11897 pragmas in individual compilation units, the exact handling depends on
11898 the type of restriction.
11900 Restrictions that require partition-wide consistency (like
11901 @code{No_Tasking}) are
11902 recognized wherever they appear
11903 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11904 unit. This makes sense since the binder will in any case insist on seeing
11905 consistent use, so any unit not conforming to any restrictions that are
11906 anywhere in the partition will be rejected, and you might as well find
11907 that out at compile time rather than at bind time.
11909 For restrictions that do not require partition-wide consistency, e.g.
11910 SPARK or No_Implementation_Attributes, in general the restriction applies
11911 only to the unit in which the pragma appears, and not to any other units.
11913 The exception is No_Elaboration_Code which always applies to the entire
11914 object file from a compilation, i.e. to the body, spec, and all subunits.
11915 This restriction can be specified in a configuration pragma file, or it
11916 can be on the body and/or the spec (in eithe case it applies to all the
11917 relevant units). It can appear on a subunit only if it has previously
11918 appeared in the body of spec.
11920 @node The Configuration Pragmas Files
11921 @section The Configuration Pragmas Files
11922 @cindex @file{gnat.adc}
11925 In GNAT a compilation environment is defined by the current
11926 directory at the time that a compile command is given. This current
11927 directory is searched for a file whose name is @file{gnat.adc}. If
11928 this file is present, it is expected to contain one or more
11929 configuration pragmas that will be applied to the current compilation.
11930 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11933 Configuration pragmas may be entered into the @file{gnat.adc} file
11934 either by running @code{gnatchop} on a source file that consists only of
11935 configuration pragmas, or more conveniently by
11936 direct editing of the @file{gnat.adc} file, which is a standard format
11939 In addition to @file{gnat.adc}, additional files containing configuration
11940 pragmas may be applied to the current compilation using the switch
11941 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11942 contains only configuration pragmas. These configuration pragmas are
11943 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11944 is present and switch @option{-gnatA} is not used).
11946 It is allowed to specify several switches @option{-gnatec}, all of which
11947 will be taken into account.
11949 If you are using project file, a separate mechanism is provided using
11950 project attributes, see @ref{Specifying Configuration Pragmas} for more
11954 Of special interest to GNAT OpenVMS Alpha is the following
11955 configuration pragma:
11957 @smallexample @c ada
11959 pragma Extend_System (Aux_DEC);
11964 In the presence of this pragma, GNAT adds to the definition of the
11965 predefined package SYSTEM all the additional types and subprograms that are
11966 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11969 @node Handling Arbitrary File Naming Conventions Using gnatname
11970 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11971 @cindex Arbitrary File Naming Conventions
11974 * Arbitrary File Naming Conventions::
11975 * Running gnatname::
11976 * Switches for gnatname::
11977 * Examples of gnatname Usage::
11980 @node Arbitrary File Naming Conventions
11981 @section Arbitrary File Naming Conventions
11984 The GNAT compiler must be able to know the source file name of a compilation
11985 unit. When using the standard GNAT default file naming conventions
11986 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11987 does not need additional information.
11990 When the source file names do not follow the standard GNAT default file naming
11991 conventions, the GNAT compiler must be given additional information through
11992 a configuration pragmas file (@pxref{Configuration Pragmas})
11994 When the non-standard file naming conventions are well-defined,
11995 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11996 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11997 if the file naming conventions are irregular or arbitrary, a number
11998 of pragma @code{Source_File_Name} for individual compilation units
12000 To help maintain the correspondence between compilation unit names and
12001 source file names within the compiler,
12002 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12005 @node Running gnatname
12006 @section Running @code{gnatname}
12009 The usual form of the @code{gnatname} command is
12012 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12013 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12014 @c Expanding @ovar macro inline (explanation in macro def comments)
12015 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12016 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12020 All of the arguments are optional. If invoked without any argument,
12021 @code{gnatname} will display its usage.
12024 When used with at least one naming pattern, @code{gnatname} will attempt to
12025 find all the compilation units in files that follow at least one of the
12026 naming patterns. To find these compilation units,
12027 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12031 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12032 Each Naming Pattern is enclosed between double quotes (or single
12033 quotes on Windows).
12034 A Naming Pattern is a regular expression similar to the wildcard patterns
12035 used in file names by the Unix shells or the DOS prompt.
12038 @code{gnatname} may be called with several sections of directories/patterns.
12039 Sections are separated by switch @code{--and}. In each section, there must be
12040 at least one pattern. If no directory is specified in a section, the current
12041 directory (or the project directory is @code{-P} is used) is implied.
12042 The options other that the directory switches and the patterns apply globally
12043 even if they are in different sections.
12046 Examples of Naming Patterns are
12055 For a more complete description of the syntax of Naming Patterns,
12056 see the second kind of regular expressions described in @file{g-regexp.ads}
12057 (the ``Glob'' regular expressions).
12060 When invoked with no switch @code{-P}, @code{gnatname} will create a
12061 configuration pragmas file @file{gnat.adc} in the current working directory,
12062 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12065 @node Switches for gnatname
12066 @section Switches for @code{gnatname}
12069 Switches for @code{gnatname} must precede any specified Naming Pattern.
12072 You may specify any of the following switches to @code{gnatname}:
12078 @cindex @option{--version} @command{gnatname}
12079 Display Copyright and version, then exit disregarding all other options.
12082 @cindex @option{--help} @command{gnatname}
12083 If @option{--version} was not used, display usage, then exit disregarding
12087 Start another section of directories/patterns.
12089 @item ^-c^/CONFIG_FILE=^@file{file}
12090 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12091 Create a configuration pragmas file @file{file} (instead of the default
12094 There may be zero, one or more space between @option{-c} and
12097 @file{file} may include directory information. @file{file} must be
12098 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12099 When a switch @option{^-c^/CONFIG_FILE^} is
12100 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12102 @item ^-d^/SOURCE_DIRS=^@file{dir}
12103 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12104 Look for source files in directory @file{dir}. There may be zero, one or more
12105 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12106 When a switch @option{^-d^/SOURCE_DIRS^}
12107 is specified, the current working directory will not be searched for source
12108 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12109 or @option{^-D^/DIR_FILES^} switch.
12110 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12111 If @file{dir} is a relative path, it is relative to the directory of
12112 the configuration pragmas file specified with switch
12113 @option{^-c^/CONFIG_FILE^},
12114 or to the directory of the project file specified with switch
12115 @option{^-P^/PROJECT_FILE^} or,
12116 if neither switch @option{^-c^/CONFIG_FILE^}
12117 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12118 current working directory. The directory
12119 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12121 @item ^-D^/DIRS_FILE=^@file{file}
12122 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12123 Look for source files in all directories listed in text file @file{file}.
12124 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12126 @file{file} must be an existing, readable text file.
12127 Each nonempty line in @file{file} must be a directory.
12128 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12129 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12132 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12133 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12134 Foreign patterns. Using this switch, it is possible to add sources of languages
12135 other than Ada to the list of sources of a project file.
12136 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12139 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12142 will look for Ada units in all files with the @file{.ada} extension,
12143 and will add to the list of file for project @file{prj.gpr} the C files
12144 with extension @file{.^c^C^}.
12147 @cindex @option{^-h^/HELP^} (@code{gnatname})
12148 Output usage (help) information. The output is written to @file{stdout}.
12150 @item ^-P^/PROJECT_FILE=^@file{proj}
12151 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12152 Create or update project file @file{proj}. There may be zero, one or more space
12153 between @option{-P} and @file{proj}. @file{proj} may include directory
12154 information. @file{proj} must be writable.
12155 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12156 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12157 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12159 @item ^-v^/VERBOSE^
12160 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12161 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12162 This includes name of the file written, the name of the directories to search
12163 and, for each file in those directories whose name matches at least one of
12164 the Naming Patterns, an indication of whether the file contains a unit,
12165 and if so the name of the unit.
12167 @item ^-v -v^/VERBOSE /VERBOSE^
12168 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12169 Very Verbose mode. In addition to the output produced in verbose mode,
12170 for each file in the searched directories whose name matches none of
12171 the Naming Patterns, an indication is given that there is no match.
12173 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12174 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12175 Excluded patterns. Using this switch, it is possible to exclude some files
12176 that would match the name patterns. For example,
12178 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12181 will look for Ada units in all files with the @file{.ada} extension,
12182 except those whose names end with @file{_nt.ada}.
12186 @node Examples of gnatname Usage
12187 @section Examples of @code{gnatname} Usage
12191 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12197 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12202 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12203 and be writable. In addition, the directory
12204 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12205 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12208 Note the optional spaces after @option{-c} and @option{-d}.
12213 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12214 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12217 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12218 /EXCLUDED_PATTERN=*_nt_body.ada
12219 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12220 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12224 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12225 even in conjunction with one or several switches
12226 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12227 are used in this example.
12229 @c *****************************************
12230 @c * G N A T P r o j e c t M a n a g e r *
12231 @c *****************************************
12233 @c ------ macros for projects.texi
12234 @c These macros are needed when building the gprbuild documentation, but
12235 @c should have no effect in the gnat user's guide
12237 @macro CODESAMPLE{TXT}
12245 @macro PROJECTFILE{TXT}
12249 @c simulates a newline when in a @CODESAMPLE
12260 @macro TIPHTML{TXT}
12264 @macro IMPORTANT{TXT}
12279 @include projects.texi
12281 @c *****************************************
12282 @c * Cross-referencing tools
12283 @c *****************************************
12285 @node The Cross-Referencing Tools gnatxref and gnatfind
12286 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12291 The compiler generates cross-referencing information (unless
12292 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12293 This information indicates where in the source each entity is declared and
12294 referenced. Note that entities in package Standard are not included, but
12295 entities in all other predefined units are included in the output.
12297 Before using any of these two tools, you need to compile successfully your
12298 application, so that GNAT gets a chance to generate the cross-referencing
12301 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12302 information to provide the user with the capability to easily locate the
12303 declaration and references to an entity. These tools are quite similar,
12304 the difference being that @code{gnatfind} is intended for locating
12305 definitions and/or references to a specified entity or entities, whereas
12306 @code{gnatxref} is oriented to generating a full report of all
12309 To use these tools, you must not compile your application using the
12310 @option{-gnatx} switch on the @command{gnatmake} command line
12311 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12312 information will not be generated.
12314 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12315 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12318 * Switches for gnatxref::
12319 * Switches for gnatfind::
12320 * Project Files for gnatxref and gnatfind::
12321 * Regular Expressions in gnatfind and gnatxref::
12322 * Examples of gnatxref Usage::
12323 * Examples of gnatfind Usage::
12326 @node Switches for gnatxref
12327 @section @code{gnatxref} Switches
12330 The command invocation for @code{gnatxref} is:
12332 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12333 @c Expanding @ovar macro inline (explanation in macro def comments)
12334 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12343 identifies the source files for which a report is to be generated. The
12344 ``with''ed units will be processed too. You must provide at least one file.
12346 These file names are considered to be regular expressions, so for instance
12347 specifying @file{source*.adb} is the same as giving every file in the current
12348 directory whose name starts with @file{source} and whose extension is
12351 You shouldn't specify any directory name, just base names. @command{gnatxref}
12352 and @command{gnatfind} will be able to locate these files by themselves using
12353 the source path. If you specify directories, no result is produced.
12358 The switches can be:
12362 @cindex @option{--version} @command{gnatxref}
12363 Display Copyright and version, then exit disregarding all other options.
12366 @cindex @option{--help} @command{gnatxref}
12367 If @option{--version} was not used, display usage, then exit disregarding
12370 @item ^-a^/ALL_FILES^
12371 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12372 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12373 the read-only files found in the library search path. Otherwise, these files
12374 will be ignored. This option can be used to protect Gnat sources or your own
12375 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12376 much faster, and their output much smaller. Read-only here refers to access
12377 or permissions status in the file system for the current user.
12380 @cindex @option{-aIDIR} (@command{gnatxref})
12381 When looking for source files also look in directory DIR. The order in which
12382 source file search is undertaken is the same as for @command{gnatmake}.
12385 @cindex @option{-aODIR} (@command{gnatxref})
12386 When searching for library and object files, look in directory
12387 DIR. The order in which library files are searched is the same as for
12388 @command{gnatmake}.
12391 @cindex @option{-nostdinc} (@command{gnatxref})
12392 Do not look for sources in the system default directory.
12395 @cindex @option{-nostdlib} (@command{gnatxref})
12396 Do not look for library files in the system default directory.
12398 @item --ext=@var{extension}
12399 @cindex @option{--ext} (@command{gnatxref})
12400 Specify an alternate ali file extension. The default is @code{ali} and other
12401 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12402 switch. Note that if this switch overrides the default, which means that only
12403 the new extension will be considered.
12405 @item --RTS=@var{rts-path}
12406 @cindex @option{--RTS} (@command{gnatxref})
12407 Specifies the default location of the runtime library. Same meaning as the
12408 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12410 @item ^-d^/DERIVED_TYPES^
12411 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12412 If this switch is set @code{gnatxref} will output the parent type
12413 reference for each matching derived types.
12415 @item ^-f^/FULL_PATHNAME^
12416 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12417 If this switch is set, the output file names will be preceded by their
12418 directory (if the file was found in the search path). If this switch is
12419 not set, the directory will not be printed.
12421 @item ^-g^/IGNORE_LOCALS^
12422 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12423 If this switch is set, information is output only for library-level
12424 entities, ignoring local entities. The use of this switch may accelerate
12425 @code{gnatfind} and @code{gnatxref}.
12428 @cindex @option{-IDIR} (@command{gnatxref})
12429 Equivalent to @samp{-aODIR -aIDIR}.
12432 @cindex @option{-pFILE} (@command{gnatxref})
12433 Specify a project file to use @xref{GNAT Project Manager}.
12434 If you need to use the @file{.gpr}
12435 project files, you should use gnatxref through the GNAT driver
12436 (@command{gnat xref -Pproject}).
12438 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12439 project file in the current directory.
12441 If a project file is either specified or found by the tools, then the content
12442 of the source directory and object directory lines are added as if they
12443 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12444 and @samp{^-aO^OBJECT_SEARCH^}.
12446 Output only unused symbols. This may be really useful if you give your
12447 main compilation unit on the command line, as @code{gnatxref} will then
12448 display every unused entity and 'with'ed package.
12452 Instead of producing the default output, @code{gnatxref} will generate a
12453 @file{tags} file that can be used by vi. For examples how to use this
12454 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12455 to the standard output, thus you will have to redirect it to a file.
12461 All these switches may be in any order on the command line, and may even
12462 appear after the file names. They need not be separated by spaces, thus
12463 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12464 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12466 @node Switches for gnatfind
12467 @section @code{gnatfind} Switches
12470 The command line for @code{gnatfind} is:
12473 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12474 @c @r{[}@var{file1} @var{file2} @dots{}]
12475 @c Expanding @ovar macro inline (explanation in macro def comments)
12476 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12477 @r{[}@var{file1} @var{file2} @dots{}@r{]}
12485 An entity will be output only if it matches the regular expression found
12486 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12488 Omitting the pattern is equivalent to specifying @samp{*}, which
12489 will match any entity. Note that if you do not provide a pattern, you
12490 have to provide both a sourcefile and a line.
12492 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12493 for matching purposes. At the current time there is no support for
12494 8-bit codes other than Latin-1, or for wide characters in identifiers.
12497 @code{gnatfind} will look for references, bodies or declarations
12498 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12499 and column @var{column}. See @ref{Examples of gnatfind Usage}
12500 for syntax examples.
12503 is a decimal integer identifying the line number containing
12504 the reference to the entity (or entities) to be located.
12507 is a decimal integer identifying the exact location on the
12508 line of the first character of the identifier for the
12509 entity reference. Columns are numbered from 1.
12511 @item file1 file2 @dots{}
12512 The search will be restricted to these source files. If none are given, then
12513 the search will be done for every library file in the search path.
12514 These file must appear only after the pattern or sourcefile.
12516 These file names are considered to be regular expressions, so for instance
12517 specifying @file{source*.adb} is the same as giving every file in the current
12518 directory whose name starts with @file{source} and whose extension is
12521 The location of the spec of the entity will always be displayed, even if it
12522 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
12523 occurrences of the entity in the separate units of the ones given on the
12524 command line will also be displayed.
12526 Note that if you specify at least one file in this part, @code{gnatfind} may
12527 sometimes not be able to find the body of the subprograms.
12532 At least one of 'sourcefile' or 'pattern' has to be present on
12535 The following switches are available:
12539 @cindex @option{--version} @command{gnatfind}
12540 Display Copyright and version, then exit disregarding all other options.
12543 @cindex @option{--help} @command{gnatfind}
12544 If @option{--version} was not used, display usage, then exit disregarding
12547 @item ^-a^/ALL_FILES^
12548 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12549 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12550 the read-only files found in the library search path. Otherwise, these files
12551 will be ignored. This option can be used to protect Gnat sources or your own
12552 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12553 much faster, and their output much smaller. Read-only here refers to access
12554 or permission status in the file system for the current user.
12557 @cindex @option{-aIDIR} (@command{gnatfind})
12558 When looking for source files also look in directory DIR. The order in which
12559 source file search is undertaken is the same as for @command{gnatmake}.
12562 @cindex @option{-aODIR} (@command{gnatfind})
12563 When searching for library and object files, look in directory
12564 DIR. The order in which library files are searched is the same as for
12565 @command{gnatmake}.
12568 @cindex @option{-nostdinc} (@command{gnatfind})
12569 Do not look for sources in the system default directory.
12572 @cindex @option{-nostdlib} (@command{gnatfind})
12573 Do not look for library files in the system default directory.
12575 @item --ext=@var{extension}
12576 @cindex @option{--ext} (@command{gnatfind})
12577 Specify an alternate ali file extension. The default is @code{ali} and other
12578 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12579 switch. Note that if this switch overrides the default, which means that only
12580 the new extension will be considered.
12582 @item --RTS=@var{rts-path}
12583 @cindex @option{--RTS} (@command{gnatfind})
12584 Specifies the default location of the runtime library. Same meaning as the
12585 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12587 @item ^-d^/DERIVED_TYPE_INFORMATION^
12588 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12589 If this switch is set, then @code{gnatfind} will output the parent type
12590 reference for each matching derived types.
12592 @item ^-e^/EXPRESSIONS^
12593 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12594 By default, @code{gnatfind} accept the simple regular expression set for
12595 @samp{pattern}. If this switch is set, then the pattern will be
12596 considered as full Unix-style regular expression.
12598 @item ^-f^/FULL_PATHNAME^
12599 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12600 If this switch is set, the output file names will be preceded by their
12601 directory (if the file was found in the search path). If this switch is
12602 not set, the directory will not be printed.
12604 @item ^-g^/IGNORE_LOCALS^
12605 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12606 If this switch is set, information is output only for library-level
12607 entities, ignoring local entities. The use of this switch may accelerate
12608 @code{gnatfind} and @code{gnatxref}.
12611 @cindex @option{-IDIR} (@command{gnatfind})
12612 Equivalent to @samp{-aODIR -aIDIR}.
12615 @cindex @option{-pFILE} (@command{gnatfind})
12616 Specify a project file (@pxref{GNAT Project Manager}) to use.
12617 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12618 project file in the current directory.
12620 If a project file is either specified or found by the tools, then the content
12621 of the source directory and object directory lines are added as if they
12622 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12623 @samp{^-aO^/OBJECT_SEARCH^}.
12625 @item ^-r^/REFERENCES^
12626 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12627 By default, @code{gnatfind} will output only the information about the
12628 declaration, body or type completion of the entities. If this switch is
12629 set, the @code{gnatfind} will locate every reference to the entities in
12630 the files specified on the command line (or in every file in the search
12631 path if no file is given on the command line).
12633 @item ^-s^/PRINT_LINES^
12634 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12635 If this switch is set, then @code{gnatfind} will output the content
12636 of the Ada source file lines were the entity was found.
12638 @item ^-t^/TYPE_HIERARCHY^
12639 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12640 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12641 the specified type. It act like -d option but recursively from parent
12642 type to parent type. When this switch is set it is not possible to
12643 specify more than one file.
12648 All these switches may be in any order on the command line, and may even
12649 appear after the file names. They need not be separated by spaces, thus
12650 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12651 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12653 As stated previously, gnatfind will search in every directory in the
12654 search path. You can force it to look only in the current directory if
12655 you specify @code{*} at the end of the command line.
12657 @node Project Files for gnatxref and gnatfind
12658 @section Project Files for @command{gnatxref} and @command{gnatfind}
12661 Project files allow a programmer to specify how to compile its
12662 application, where to find sources, etc. These files are used
12664 primarily by GPS, but they can also be used
12667 @code{gnatxref} and @code{gnatfind}.
12669 A project file name must end with @file{.gpr}. If a single one is
12670 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12671 extract the information from it. If multiple project files are found, none of
12672 them is read, and you have to use the @samp{-p} switch to specify the one
12675 The following lines can be included, even though most of them have default
12676 values which can be used in most cases.
12677 The lines can be entered in any order in the file.
12678 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12679 each line. If you have multiple instances, only the last one is taken into
12684 [default: @code{"^./^[]^"}]
12685 specifies a directory where to look for source files. Multiple @code{src_dir}
12686 lines can be specified and they will be searched in the order they
12690 [default: @code{"^./^[]^"}]
12691 specifies a directory where to look for object and library files. Multiple
12692 @code{obj_dir} lines can be specified, and they will be searched in the order
12695 @item comp_opt=SWITCHES
12696 [default: @code{""}]
12697 creates a variable which can be referred to subsequently by using
12698 the @code{$@{comp_opt@}} notation. This is intended to store the default
12699 switches given to @command{gnatmake} and @command{gcc}.
12701 @item bind_opt=SWITCHES
12702 [default: @code{""}]
12703 creates a variable which can be referred to subsequently by using
12704 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12705 switches given to @command{gnatbind}.
12707 @item link_opt=SWITCHES
12708 [default: @code{""}]
12709 creates a variable which can be referred to subsequently by using
12710 the @samp{$@{link_opt@}} notation. This is intended to store the default
12711 switches given to @command{gnatlink}.
12713 @item main=EXECUTABLE
12714 [default: @code{""}]
12715 specifies the name of the executable for the application. This variable can
12716 be referred to in the following lines by using the @samp{$@{main@}} notation.
12719 @item comp_cmd=COMMAND
12720 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12723 @item comp_cmd=COMMAND
12724 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12726 specifies the command used to compile a single file in the application.
12729 @item make_cmd=COMMAND
12730 [default: @code{"GNAT MAKE $@{main@}
12731 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12732 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12733 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12736 @item make_cmd=COMMAND
12737 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12738 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12739 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12741 specifies the command used to recompile the whole application.
12743 @item run_cmd=COMMAND
12744 [default: @code{"$@{main@}"}]
12745 specifies the command used to run the application.
12747 @item debug_cmd=COMMAND
12748 [default: @code{"gdb $@{main@}"}]
12749 specifies the command used to debug the application
12754 @command{gnatxref} and @command{gnatfind} only take into account the
12755 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12757 @node Regular Expressions in gnatfind and gnatxref
12758 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12761 As specified in the section about @command{gnatfind}, the pattern can be a
12762 regular expression. Actually, there are to set of regular expressions
12763 which are recognized by the program:
12766 @item globbing patterns
12767 These are the most usual regular expression. They are the same that you
12768 generally used in a Unix shell command line, or in a DOS session.
12770 Here is a more formal grammar:
12777 term ::= elmt -- matches elmt
12778 term ::= elmt elmt -- concatenation (elmt then elmt)
12779 term ::= * -- any string of 0 or more characters
12780 term ::= ? -- matches any character
12781 term ::= [char @{char@}] -- matches any character listed
12782 term ::= [char - char] -- matches any character in range
12786 @item full regular expression
12787 The second set of regular expressions is much more powerful. This is the
12788 type of regular expressions recognized by utilities such a @file{grep}.
12790 The following is the form of a regular expression, expressed in Ada
12791 reference manual style BNF is as follows
12798 regexp ::= term @{| term@} -- alternation (term or term @dots{})
12800 term ::= item @{item@} -- concatenation (item then item)
12802 item ::= elmt -- match elmt
12803 item ::= elmt * -- zero or more elmt's
12804 item ::= elmt + -- one or more elmt's
12805 item ::= elmt ? -- matches elmt or nothing
12808 elmt ::= nschar -- matches given character
12809 elmt ::= [nschar @{nschar@}] -- matches any character listed
12810 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12811 elmt ::= [char - char] -- matches chars in given range
12812 elmt ::= \ char -- matches given character
12813 elmt ::= . -- matches any single character
12814 elmt ::= ( regexp ) -- parens used for grouping
12816 char ::= any character, including special characters
12817 nschar ::= any character except ()[].*+?^^^
12821 Following are a few examples:
12825 will match any of the two strings @samp{abcde} and @samp{fghi},
12828 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12829 @samp{abcccd}, and so on,
12832 will match any string which has only lowercase characters in it (and at
12833 least one character.
12838 @node Examples of gnatxref Usage
12839 @section Examples of @code{gnatxref} Usage
12841 @subsection General Usage
12844 For the following examples, we will consider the following units:
12846 @smallexample @c ada
12852 3: procedure Foo (B : in Integer);
12859 1: package body Main is
12860 2: procedure Foo (B : in Integer) is
12871 2: procedure Print (B : Integer);
12880 The first thing to do is to recompile your application (for instance, in
12881 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12882 the cross-referencing information.
12883 You can then issue any of the following commands:
12885 @item gnatxref main.adb
12886 @code{gnatxref} generates cross-reference information for main.adb
12887 and every unit 'with'ed by main.adb.
12889 The output would be:
12897 Decl: main.ads 3:20
12898 Body: main.adb 2:20
12899 Ref: main.adb 4:13 5:13 6:19
12902 Ref: main.adb 6:8 7:8
12912 Decl: main.ads 3:15
12913 Body: main.adb 2:15
12916 Body: main.adb 1:14
12919 Ref: main.adb 6:12 7:12
12923 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12924 its body is in main.adb, line 1, column 14 and is not referenced any where.
12926 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12927 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12929 @item gnatxref package1.adb package2.ads
12930 @code{gnatxref} will generates cross-reference information for
12931 package1.adb, package2.ads and any other package 'with'ed by any
12937 @subsection Using gnatxref with vi
12939 @code{gnatxref} can generate a tags file output, which can be used
12940 directly from @command{vi}. Note that the standard version of @command{vi}
12941 will not work properly with overloaded symbols. Consider using another
12942 free implementation of @command{vi}, such as @command{vim}.
12945 $ gnatxref -v gnatfind.adb > tags
12949 will generate the tags file for @code{gnatfind} itself (if the sources
12950 are in the search path!).
12952 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12953 (replacing @var{entity} by whatever you are looking for), and vi will
12954 display a new file with the corresponding declaration of entity.
12957 @node Examples of gnatfind Usage
12958 @section Examples of @code{gnatfind} Usage
12962 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12963 Find declarations for all entities xyz referenced at least once in
12964 main.adb. The references are search in every library file in the search
12967 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12970 The output will look like:
12972 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12973 ^directory/^[directory]^main.adb:24:10: xyz <= body
12974 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12978 that is to say, one of the entities xyz found in main.adb is declared at
12979 line 12 of main.ads (and its body is in main.adb), and another one is
12980 declared at line 45 of foo.ads
12982 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12983 This is the same command as the previous one, instead @code{gnatfind} will
12984 display the content of the Ada source file lines.
12986 The output will look like:
12989 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12991 ^directory/^[directory]^main.adb:24:10: xyz <= body
12993 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12998 This can make it easier to find exactly the location your are looking
13001 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13002 Find references to all entities containing an x that are
13003 referenced on line 123 of main.ads.
13004 The references will be searched only in main.ads and foo.adb.
13006 @item gnatfind main.ads:123
13007 Find declarations and bodies for all entities that are referenced on
13008 line 123 of main.ads.
13010 This is the same as @code{gnatfind "*":main.adb:123}.
13012 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13013 Find the declaration for the entity referenced at column 45 in
13014 line 123 of file main.adb in directory mydir. Note that it
13015 is usual to omit the identifier name when the column is given,
13016 since the column position identifies a unique reference.
13018 The column has to be the beginning of the identifier, and should not
13019 point to any character in the middle of the identifier.
13023 @c *********************************
13024 @node The GNAT Pretty-Printer gnatpp
13025 @chapter The GNAT Pretty-Printer @command{gnatpp}
13027 @cindex Pretty-Printer
13030 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13031 for source reformatting / pretty-printing.
13032 It takes an Ada source file as input and generates a reformatted
13034 You can specify various style directives via switches; e.g.,
13035 identifier case conventions, rules of indentation, and comment layout.
13037 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13038 tree for the input source and thus requires the input to be syntactically and
13039 semantically legal.
13040 If this condition is not met, @command{gnatpp} will terminate with an
13041 error message; no output file will be generated.
13043 If the source files presented to @command{gnatpp} contain
13044 preprocessing directives, then the output file will
13045 correspond to the generated source after all
13046 preprocessing is carried out. There is no way
13047 using @command{gnatpp} to obtain pretty printed files that
13048 include the preprocessing directives.
13050 If the compilation unit
13051 contained in the input source depends semantically upon units located
13052 outside the current directory, you have to provide the source search path
13053 when invoking @command{gnatpp}, if these units are contained in files with
13054 names that do not follow the GNAT file naming rules, you have to provide
13055 the configuration file describing the corresponding naming scheme;
13056 see the description of the @command{gnatpp}
13057 switches below. Another possibility is to use a project file and to
13058 call @command{gnatpp} through the @command{gnat} driver
13059 (see @ref{The GNAT Driver and Project Files}).
13061 The @command{gnatpp} command has the form
13064 @c $ gnatpp @ovar{switches} @var{filename}
13065 @c Expanding @ovar macro inline (explanation in macro def comments)
13066 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13073 @var{switches} is an optional sequence of switches defining such properties as
13074 the formatting rules, the source search path, and the destination for the
13078 @var{filename} is the name (including the extension) of the source file to
13079 reformat; ``wildcards'' or several file names on the same gnatpp command are
13080 allowed. The file name may contain path information; it does not have to
13081 follow the GNAT file naming rules
13084 @samp{@var{gcc_switches}} is a list of switches for
13085 @command{gcc}. They will be passed on to all compiler invocations made by
13086 @command{gnatelim} to generate the ASIS trees. Here you can provide
13087 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13088 use the @option{-gnatec} switch to set the configuration file,
13089 use the @option{-gnat05} switch if sources should be compiled in
13094 * Switches for gnatpp::
13095 * Formatting Rules::
13098 @node Switches for gnatpp
13099 @section Switches for @command{gnatpp}
13102 The following subsections describe the various switches accepted by
13103 @command{gnatpp}, organized by category.
13106 You specify a switch by supplying a name and generally also a value.
13107 In many cases the values for a switch with a given name are incompatible with
13109 (for example the switch that controls the casing of a reserved word may have
13110 exactly one value: upper case, lower case, or
13111 mixed case) and thus exactly one such switch can be in effect for an
13112 invocation of @command{gnatpp}.
13113 If more than one is supplied, the last one is used.
13114 However, some values for the same switch are mutually compatible.
13115 You may supply several such switches to @command{gnatpp}, but then
13116 each must be specified in full, with both the name and the value.
13117 Abbreviated forms (the name appearing once, followed by each value) are
13119 For example, to set
13120 the alignment of the assignment delimiter both in declarations and in
13121 assignment statements, you must write @option{-A2A3}
13122 (or @option{-A2 -A3}), but not @option{-A23}.
13126 In many cases the set of options for a given qualifier are incompatible with
13127 each other (for example the qualifier that controls the casing of a reserved
13128 word may have exactly one option, which specifies either upper case, lower
13129 case, or mixed case), and thus exactly one such option can be in effect for
13130 an invocation of @command{gnatpp}.
13131 If more than one is supplied, the last one is used.
13132 However, some qualifiers have options that are mutually compatible,
13133 and then you may then supply several such options when invoking
13137 In most cases, it is obvious whether or not the
13138 ^values for a switch with a given name^options for a given qualifier^
13139 are compatible with each other.
13140 When the semantics might not be evident, the summaries below explicitly
13141 indicate the effect.
13144 * Alignment Control::
13146 * Construct Layout Control::
13147 * General Text Layout Control::
13148 * Other Formatting Options::
13149 * Setting the Source Search Path::
13150 * Output File Control::
13151 * Other gnatpp Switches::
13154 @node Alignment Control
13155 @subsection Alignment Control
13156 @cindex Alignment control in @command{gnatpp}
13159 Programs can be easier to read if certain constructs are vertically aligned.
13160 By default all alignments are set ON.
13161 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13162 OFF, and then use one or more of the other
13163 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13164 to activate alignment for specific constructs.
13167 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13171 Set all alignments to ON
13174 @item ^-A0^/ALIGN=OFF^
13175 Set all alignments to OFF
13177 @item ^-A1^/ALIGN=COLONS^
13178 Align @code{:} in declarations
13180 @item ^-A2^/ALIGN=DECLARATIONS^
13181 Align @code{:=} in initializations in declarations
13183 @item ^-A3^/ALIGN=STATEMENTS^
13184 Align @code{:=} in assignment statements
13186 @item ^-A4^/ALIGN=ARROWS^
13187 Align @code{=>} in associations
13189 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13190 Align @code{at} keywords in the component clauses in record
13191 representation clauses
13195 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13198 @node Casing Control
13199 @subsection Casing Control
13200 @cindex Casing control in @command{gnatpp}
13203 @command{gnatpp} allows you to specify the casing for reserved words,
13204 pragma names, attribute designators and identifiers.
13205 For identifiers you may define a
13206 general rule for name casing but also override this rule
13207 via a set of dictionary files.
13209 Three types of casing are supported: lower case, upper case, and mixed case.
13210 Lower and upper case are self-explanatory (but since some letters in
13211 Latin1 and other GNAT-supported character sets
13212 exist only in lower-case form, an upper case conversion will have no
13214 ``Mixed case'' means that the first letter, and also each letter immediately
13215 following an underscore, are converted to their uppercase forms;
13216 all the other letters are converted to their lowercase forms.
13219 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13220 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13221 Attribute designators are lower case
13223 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13224 Attribute designators are upper case
13226 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13227 Attribute designators are mixed case (this is the default)
13229 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13230 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13231 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13232 lower case (this is the default)
13234 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13235 Keywords are upper case
13237 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13238 @item ^-nD^/NAME_CASING=AS_DECLARED^
13239 Name casing for defining occurrences are as they appear in the source file
13240 (this is the default)
13242 @item ^-nU^/NAME_CASING=UPPER_CASE^
13243 Names are in upper case
13245 @item ^-nL^/NAME_CASING=LOWER_CASE^
13246 Names are in lower case
13248 @item ^-nM^/NAME_CASING=MIXED_CASE^
13249 Names are in mixed case
13251 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13252 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13253 Enumeration literal casing for defining occurrences are as they appear in the
13254 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13256 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13257 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
13260 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13261 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13264 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13265 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13268 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13269 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13270 Names introduced by type and subtype declarations are always
13271 cased as they appear in the declaration in the source file.
13272 Overrides ^-n^/NAME_CASING^ casing setting.
13274 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13275 Names introduced by type and subtype declarations are always in
13276 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13278 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13279 Names introduced by type and subtype declarations are always in
13280 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13282 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13283 Names introduced by type and subtype declarations are always in
13284 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13286 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13287 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13288 Pragma names are lower case
13290 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13291 Pragma names are upper case
13293 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13294 Pragma names are mixed case (this is the default)
13296 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13297 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13298 Use @var{file} as a @emph{dictionary file} that defines
13299 the casing for a set of specified names,
13300 thereby overriding the effect on these names by
13301 any explicit or implicit
13302 ^-n^/NAME_CASING^ switch.
13303 To supply more than one dictionary file,
13304 use ^several @option{-D} switches^a list of files as options^.
13307 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13308 to define the casing for the Ada predefined names and
13309 the names declared in the GNAT libraries.
13311 @item ^-D-^/SPECIFIC_CASING^
13312 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13313 Do not use the default dictionary file;
13314 instead, use the casing
13315 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13320 The structure of a dictionary file, and details on the conventions
13321 used in the default dictionary file, are defined in @ref{Name Casing}.
13323 The @option{^-D-^/SPECIFIC_CASING^} and
13324 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13327 @node Construct Layout Control
13328 @subsection Construct Layout Control
13329 @cindex Layout control in @command{gnatpp}
13332 This group of @command{gnatpp} switches controls the layout of comments and
13333 complex syntactic constructs. See @ref{Formatting Comments} for details
13337 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13338 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13339 All the comments remain unchanged
13341 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13342 GNAT-style comment line indentation (this is the default).
13344 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13345 Reference-manual comment line indentation.
13347 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13348 GNAT-style comment beginning
13350 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13351 Reformat comment blocks
13353 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13354 Keep unchanged special form comments
13356 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13357 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13358 GNAT-style layout (this is the default)
13360 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13363 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13366 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13368 All the VT characters are removed from the comment text. All the HT characters
13369 are expanded with the sequences of space characters to get to the next tab
13372 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13373 @item ^--no-separate-is^/NO_SEPARATE_IS^
13374 Do not place the keyword @code{is} on a separate line in a subprogram body in
13375 case if the spec occupies more then one line.
13377 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13378 @item ^--separate-label^/SEPARATE_LABEL^
13379 Place statement label(s) on a separate line, with the following statement
13382 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13383 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13384 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13385 keyword @code{then} in IF statements on a separate line.
13387 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13388 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13389 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13390 keyword @code{then} in IF statements on a separate line. This option is
13391 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13393 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13394 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13395 Start each USE clause in a context clause from a separate line.
13397 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13398 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13399 Use a separate line for a loop or block statement name, but do not use an extra
13400 indentation level for the statement itself.
13406 The @option{-c1} and @option{-c2} switches are incompatible.
13407 The @option{-c3} and @option{-c4} switches are compatible with each other and
13408 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13409 the other comment formatting switches.
13411 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13416 For the @option{/COMMENTS_LAYOUT} qualifier:
13419 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13421 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13422 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13426 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13427 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13430 @node General Text Layout Control
13431 @subsection General Text Layout Control
13434 These switches allow control over line length and indentation.
13437 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13438 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13439 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13441 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13442 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13443 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13445 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13446 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13447 Indentation level for continuation lines (relative to the line being
13448 continued), @var{nnn} from 1@dots{}9.
13450 value is one less then the (normal) indentation level, unless the
13451 indentation is set to 1 (in which case the default value for continuation
13452 line indentation is also 1)
13455 @node Other Formatting Options
13456 @subsection Other Formatting Options
13459 These switches control the inclusion of missing end/exit labels, and
13460 the indentation level in @b{case} statements.
13463 @item ^-e^/NO_MISSED_LABELS^
13464 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13465 Do not insert missing end/exit labels. An end label is the name of
13466 a construct that may optionally be repeated at the end of the
13467 construct's declaration;
13468 e.g., the names of packages, subprograms, and tasks.
13469 An exit label is the name of a loop that may appear as target
13470 of an exit statement within the loop.
13471 By default, @command{gnatpp} inserts these end/exit labels when
13472 they are absent from the original source. This option suppresses such
13473 insertion, so that the formatted source reflects the original.
13475 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13476 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13477 Insert a Form Feed character after a pragma Page.
13479 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13480 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13481 Do not use an additional indentation level for @b{case} alternatives
13482 and variants if there are @var{nnn} or more (the default
13484 If @var{nnn} is 0, an additional indentation level is
13485 used for @b{case} alternatives and variants regardless of their number.
13487 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
13488 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
13489 If the number of parameter associations is greater than @var{nnn} and if at
13490 least one association uses named notation, start each association from
13491 a new line. If @var{nnn} is 0, no check for the number of associations
13492 is made, this is the default.
13494 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
13495 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
13496 If the number of parameter specifications is greater than @var{nnn}
13497 (or equal to @var{nnn} in case of a function), start each specification from
13498 a new line. The default for @var{nnn} is 3.
13501 @node Setting the Source Search Path
13502 @subsection Setting the Source Search Path
13505 To define the search path for the input source file, @command{gnatpp}
13506 uses the same switches as the GNAT compiler, with the same effects.
13509 @item ^-I^/SEARCH=^@var{dir}
13510 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13511 The same as the corresponding gcc switch
13513 @item ^-I-^/NOCURRENT_DIRECTORY^
13514 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13515 The same as the corresponding gcc switch
13517 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13518 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13519 The same as the corresponding gcc switch
13521 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13522 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13523 The same as the corresponding gcc switch
13527 @node Output File Control
13528 @subsection Output File Control
13531 By default the output is sent to the file whose name is obtained by appending
13532 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13533 (if the file with this name already exists, it is unconditionally overwritten).
13534 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13535 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13537 The output may be redirected by the following switches:
13540 @item ^-pipe^/STANDARD_OUTPUT^
13541 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13542 Send the output to @code{Standard_Output}
13544 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13545 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13546 Write the output into @var{output_file}.
13547 If @var{output_file} already exists, @command{gnatpp} terminates without
13548 reading or processing the input file.
13550 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13551 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13552 Write the output into @var{output_file}, overwriting the existing file
13553 (if one is present).
13555 @item ^-r^/REPLACE^
13556 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13557 Replace the input source file with the reformatted output, and copy the
13558 original input source into the file whose name is obtained by appending the
13559 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13560 If a file with this name already exists, @command{gnatpp} terminates without
13561 reading or processing the input file.
13563 @item ^-rf^/OVERRIDING_REPLACE^
13564 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13565 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13566 already exists, it is overwritten.
13568 @item ^-rnb^/REPLACE_NO_BACKUP^
13569 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13570 Replace the input source file with the reformatted output without
13571 creating any backup copy of the input source.
13573 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13574 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13575 Specifies the format of the reformatted output file. The @var{xxx}
13576 ^string specified with the switch^option^ may be either
13578 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13579 @item ``@option{^crlf^CRLF^}''
13580 the same as @option{^crlf^CRLF^}
13581 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13582 @item ``@option{^lf^LF^}''
13583 the same as @option{^unix^UNIX^}
13586 @item ^-W^/RESULT_ENCODING=^@var{e}
13587 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13588 Specify the wide character encoding method used to write the code in the
13590 @var{e} is one of the following:
13598 Upper half encoding
13600 @item ^s^SHIFT_JIS^
13610 Brackets encoding (default value)
13616 Options @option{^-pipe^/STANDARD_OUTPUT^},
13617 @option{^-o^/OUTPUT^} and
13618 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13619 contains only one file to reformat.
13621 @option{^--eol^/END_OF_LINE^}
13623 @option{^-W^/RESULT_ENCODING^}
13624 cannot be used together
13625 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13627 @node Other gnatpp Switches
13628 @subsection Other @code{gnatpp} Switches
13631 The additional @command{gnatpp} switches are defined in this subsection.
13634 @item ^-files @var{filename}^/FILES=@var{filename}^
13635 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13636 Take the argument source files from the specified file. This file should be an
13637 ordinary text file containing file names separated by spaces or
13638 line breaks. You can use this switch more than once in the same call to
13639 @command{gnatpp}. You also can combine this switch with an explicit list of
13642 @item ^-v^/VERBOSE^
13643 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13645 @command{gnatpp} generates version information and then
13646 a trace of the actions it takes to produce or obtain the ASIS tree.
13648 @item ^-w^/WARNINGS^
13649 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13651 @command{gnatpp} generates a warning whenever it cannot provide
13652 a required layout in the result source.
13655 @node Formatting Rules
13656 @section Formatting Rules
13659 The following subsections show how @command{gnatpp} treats ``white space'',
13660 comments, program layout, and name casing.
13661 They provide the detailed descriptions of the switches shown above.
13664 * White Space and Empty Lines::
13665 * Formatting Comments::
13666 * Construct Layout::
13670 @node White Space and Empty Lines
13671 @subsection White Space and Empty Lines
13674 @command{gnatpp} does not have an option to control space characters.
13675 It will add or remove spaces according to the style illustrated by the
13676 examples in the @cite{Ada Reference Manual}.
13678 The only format effectors
13679 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13680 that will appear in the output file are platform-specific line breaks,
13681 and also format effectors within (but not at the end of) comments.
13682 In particular, each horizontal tab character that is not inside
13683 a comment will be treated as a space and thus will appear in the
13684 output file as zero or more spaces depending on
13685 the reformatting of the line in which it appears.
13686 The only exception is a Form Feed character, which is inserted after a
13687 pragma @code{Page} when @option{-ff} is set.
13689 The output file will contain no lines with trailing ``white space'' (spaces,
13692 Empty lines in the original source are preserved
13693 only if they separate declarations or statements.
13694 In such contexts, a
13695 sequence of two or more empty lines is replaced by exactly one empty line.
13696 Note that a blank line will be removed if it separates two ``comment blocks''
13697 (a comment block is a sequence of whole-line comments).
13698 In order to preserve a visual separation between comment blocks, use an
13699 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13700 Likewise, if for some reason you wish to have a sequence of empty lines,
13701 use a sequence of empty comments instead.
13703 @node Formatting Comments
13704 @subsection Formatting Comments
13707 Comments in Ada code are of two kinds:
13710 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13711 ``white space'') on a line
13714 an @emph{end-of-line comment}, which follows some other Ada lexical element
13719 The indentation of a whole-line comment is that of either
13720 the preceding or following line in
13721 the formatted source, depending on switch settings as will be described below.
13723 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13724 between the end of the preceding Ada lexical element and the beginning
13725 of the comment as appear in the original source,
13726 unless either the comment has to be split to
13727 satisfy the line length limitation, or else the next line contains a
13728 whole line comment that is considered a continuation of this end-of-line
13729 comment (because it starts at the same position).
13731 cases, the start of the end-of-line comment is moved right to the nearest
13732 multiple of the indentation level.
13733 This may result in a ``line overflow'' (the right-shifted comment extending
13734 beyond the maximum line length), in which case the comment is split as
13737 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13738 (GNAT-style comment line indentation)
13739 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13740 (reference-manual comment line indentation).
13741 With reference-manual style, a whole-line comment is indented as if it
13742 were a declaration or statement at the same place
13743 (i.e., according to the indentation of the preceding line(s)).
13744 With GNAT style, a whole-line comment that is immediately followed by an
13745 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13746 word @b{begin}, is indented based on the construct that follows it.
13749 @smallexample @c ada
13761 Reference-manual indentation produces:
13763 @smallexample @c ada
13775 while GNAT-style indentation produces:
13777 @smallexample @c ada
13789 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13790 (GNAT style comment beginning) has the following
13795 For each whole-line comment that does not end with two hyphens,
13796 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13797 to ensure that there are at least two spaces between these hyphens and the
13798 first non-blank character of the comment.
13802 For an end-of-line comment, if in the original source the next line is a
13803 whole-line comment that starts at the same position
13804 as the end-of-line comment,
13805 then the whole-line comment (and all whole-line comments
13806 that follow it and that start at the same position)
13807 will start at this position in the output file.
13810 That is, if in the original source we have:
13812 @smallexample @c ada
13815 A := B + C; -- B must be in the range Low1..High1
13816 -- C must be in the range Low2..High2
13817 --B+C will be in the range Low1+Low2..High1+High2
13823 Then in the formatted source we get
13825 @smallexample @c ada
13828 A := B + C; -- B must be in the range Low1..High1
13829 -- C must be in the range Low2..High2
13830 -- B+C will be in the range Low1+Low2..High1+High2
13836 A comment that exceeds the line length limit will be split.
13838 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13839 the line belongs to a reformattable block, splitting the line generates a
13840 @command{gnatpp} warning.
13841 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13842 comments may be reformatted in typical
13843 word processor style (that is, moving words between lines and putting as
13844 many words in a line as possible).
13847 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13848 that has a special format (that is, a character that is neither a letter nor digit
13849 not white space nor line break immediately following the leading @code{--} of
13850 the comment) should be without any change moved from the argument source
13851 into reformatted source. This switch allows to preserve comments that are used
13852 as a special marks in the code (e.g.@: SPARK annotation).
13854 @node Construct Layout
13855 @subsection Construct Layout
13858 In several cases the suggested layout in the Ada Reference Manual includes
13859 an extra level of indentation that many programmers prefer to avoid. The
13860 affected cases include:
13864 @item Record type declaration (RM 3.8)
13866 @item Record representation clause (RM 13.5.1)
13868 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13870 @item Block statement in case if a block has a statement identifier (RM 5.6)
13874 In compact mode (when GNAT style layout or compact layout is set),
13875 the pretty printer uses one level of indentation instead
13876 of two. This is achieved in the record definition and record representation
13877 clause cases by putting the @code{record} keyword on the same line as the
13878 start of the declaration or representation clause, and in the block and loop
13879 case by putting the block or loop header on the same line as the statement
13883 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13884 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13885 layout on the one hand, and uncompact layout
13886 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13887 can be illustrated by the following examples:
13891 @multitable @columnfractions .5 .5
13892 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13895 @smallexample @c ada
13902 @smallexample @c ada
13911 @smallexample @c ada
13913 a at 0 range 0 .. 31;
13914 b at 4 range 0 .. 31;
13918 @smallexample @c ada
13921 a at 0 range 0 .. 31;
13922 b at 4 range 0 .. 31;
13927 @smallexample @c ada
13935 @smallexample @c ada
13945 @smallexample @c ada
13946 Clear : for J in 1 .. 10 loop
13951 @smallexample @c ada
13953 for J in 1 .. 10 loop
13964 GNAT style, compact layout Uncompact layout
13966 type q is record type q is
13967 a : integer; record
13968 b : integer; a : integer;
13969 end record; b : integer;
13972 for q use record for q use
13973 a at 0 range 0 .. 31; record
13974 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
13975 end record; b at 4 range 0 .. 31;
13978 Block : declare Block :
13979 A : Integer := 3; declare
13980 begin A : Integer := 3;
13982 end Block; Proc (A, A);
13985 Clear : for J in 1 .. 10 loop Clear :
13986 A (J) := 0; for J in 1 .. 10 loop
13987 end loop Clear; A (J) := 0;
13994 A further difference between GNAT style layout and compact layout is that
13995 GNAT style layout inserts empty lines as separation for
13996 compound statements, return statements and bodies.
13998 Note that the layout specified by
13999 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14000 for named block and loop statements overrides the layout defined by these
14001 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14002 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14003 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14006 @subsection Name Casing
14009 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14010 the same casing as the corresponding defining identifier.
14012 You control the casing for defining occurrences via the
14013 @option{^-n^/NAME_CASING^} switch.
14015 With @option{-nD} (``as declared'', which is the default),
14018 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14020 defining occurrences appear exactly as in the source file
14021 where they are declared.
14022 The other ^values for this switch^options for this qualifier^ ---
14023 @option{^-nU^UPPER_CASE^},
14024 @option{^-nL^LOWER_CASE^},
14025 @option{^-nM^MIXED_CASE^} ---
14027 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14028 If @command{gnatpp} changes the casing of a defining
14029 occurrence, it analogously changes the casing of all the
14030 usage occurrences of this name.
14032 If the defining occurrence of a name is not in the source compilation unit
14033 currently being processed by @command{gnatpp}, the casing of each reference to
14034 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14035 switch (subject to the dictionary file mechanism described below).
14036 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14038 casing for the defining occurrence of the name.
14040 Some names may need to be spelled with casing conventions that are not
14041 covered by the upper-, lower-, and mixed-case transformations.
14042 You can arrange correct casing by placing such names in a
14043 @emph{dictionary file},
14044 and then supplying a @option{^-D^/DICTIONARY^} switch.
14045 The casing of names from dictionary files overrides
14046 any @option{^-n^/NAME_CASING^} switch.
14048 To handle the casing of Ada predefined names and the names from GNAT libraries,
14049 @command{gnatpp} assumes a default dictionary file.
14050 The name of each predefined entity is spelled with the same casing as is used
14051 for the entity in the @cite{Ada Reference Manual}.
14052 The name of each entity in the GNAT libraries is spelled with the same casing
14053 as is used in the declaration of that entity.
14055 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14056 default dictionary file.
14057 Instead, the casing for predefined and GNAT-defined names will be established
14058 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14059 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14060 will appear as just shown,
14061 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14062 To ensure that even such names are rendered in uppercase,
14063 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14064 (or else, less conveniently, place these names in upper case in a dictionary
14067 A dictionary file is
14068 a plain text file; each line in this file can be either a blank line
14069 (containing only space characters and ASCII.HT characters), an Ada comment
14070 line, or the specification of exactly one @emph{casing schema}.
14072 A casing schema is a string that has the following syntax:
14076 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14078 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14083 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14084 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14086 The casing schema string can be followed by white space and/or an Ada-style
14087 comment; any amount of white space is allowed before the string.
14089 If a dictionary file is passed as
14091 the value of a @option{-D@var{file}} switch
14094 an option to the @option{/DICTIONARY} qualifier
14097 simple name and every identifier, @command{gnatpp} checks if the dictionary
14098 defines the casing for the name or for some of its parts (the term ``subword''
14099 is used below to denote the part of a name which is delimited by ``_'' or by
14100 the beginning or end of the word and which does not contain any ``_'' inside):
14104 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14105 the casing defined by the dictionary; no subwords are checked for this word
14108 for every subword @command{gnatpp} checks if the dictionary contains the
14109 corresponding string of the form @code{*@var{simple_identifier}*},
14110 and if it does, the casing of this @var{simple_identifier} is used
14114 if the whole name does not contain any ``_'' inside, and if for this name
14115 the dictionary contains two entries - one of the form @var{identifier},
14116 and another - of the form *@var{simple_identifier}*, then the first one
14117 is applied to define the casing of this name
14120 if more than one dictionary file is passed as @command{gnatpp} switches, each
14121 dictionary adds new casing exceptions and overrides all the existing casing
14122 exceptions set by the previous dictionaries
14125 when @command{gnatpp} checks if the word or subword is in the dictionary,
14126 this check is not case sensitive
14130 For example, suppose we have the following source to reformat:
14132 @smallexample @c ada
14135 name1 : integer := 1;
14136 name4_name3_name2 : integer := 2;
14137 name2_name3_name4 : Boolean;
14140 name2_name3_name4 := name4_name3_name2 > name1;
14146 And suppose we have two dictionaries:
14163 If @command{gnatpp} is called with the following switches:
14167 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14170 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14175 then we will get the following name casing in the @command{gnatpp} output:
14177 @smallexample @c ada
14180 NAME1 : Integer := 1;
14181 Name4_NAME3_Name2 : Integer := 2;
14182 Name2_NAME3_Name4 : Boolean;
14185 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14190 @c *********************************
14191 @node The GNAT Metric Tool gnatmetric
14192 @chapter The GNAT Metric Tool @command{gnatmetric}
14194 @cindex Metric tool
14197 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14198 for computing various program metrics.
14199 It takes an Ada source file as input and generates a file containing the
14200 metrics data as output. Various switches control which
14201 metrics are computed and output.
14203 @command{gnatmetric} generates and uses the ASIS
14204 tree for the input source and thus requires the input to be syntactically and
14205 semantically legal.
14206 If this condition is not met, @command{gnatmetric} will generate
14207 an error message; no metric information for this file will be
14208 computed and reported.
14210 If the compilation unit contained in the input source depends semantically
14211 upon units in files located outside the current directory, you have to provide
14212 the source search path when invoking @command{gnatmetric}.
14213 If it depends semantically upon units that are contained
14214 in files with names that do not follow the GNAT file naming rules, you have to
14215 provide the configuration file describing the corresponding naming scheme (see
14216 the description of the @command{gnatmetric} switches below.)
14217 Alternatively, you may use a project file and invoke @command{gnatmetric}
14218 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14220 The @command{gnatmetric} command has the form
14223 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14224 @c Expanding @ovar macro inline (explanation in macro def comments)
14225 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14232 @var{switches} specify the metrics to compute and define the destination for
14236 Each @var{filename} is the name (including the extension) of a source
14237 file to process. ``Wildcards'' are allowed, and
14238 the file name may contain path information.
14239 If no @var{filename} is supplied, then the @var{switches} list must contain
14241 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14242 Including both a @option{-files} switch and one or more
14243 @var{filename} arguments is permitted.
14246 @samp{@var{gcc_switches}} is a list of switches for
14247 @command{gcc}. They will be passed on to all compiler invocations made by
14248 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14249 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14250 and use the @option{-gnatec} switch to set the configuration file,
14251 use the @option{-gnat05} switch if sources should be compiled in
14256 * Switches for gnatmetric::
14259 @node Switches for gnatmetric
14260 @section Switches for @command{gnatmetric}
14263 The following subsections describe the various switches accepted by
14264 @command{gnatmetric}, organized by category.
14267 * Output Files Control::
14268 * Disable Metrics For Local Units::
14269 * Specifying a set of metrics to compute::
14270 * Other gnatmetric Switches::
14271 * Generate project-wide metrics::
14274 @node Output Files Control
14275 @subsection Output File Control
14276 @cindex Output file control in @command{gnatmetric}
14279 @command{gnatmetric} has two output formats. It can generate a
14280 textual (human-readable) form, and also XML. By default only textual
14281 output is generated.
14283 When generating the output in textual form, @command{gnatmetric} creates
14284 for each Ada source file a corresponding text file
14285 containing the computed metrics, except for the case when the set of metrics
14286 specified by gnatmetric parameters consists only of metrics that are computed
14287 for the whole set of analyzed sources, but not for each Ada source.
14288 By default, this file is placed in the same directory as where the source
14289 file is located, and its name is obtained
14290 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14293 All the output information generated in XML format is placed in a single
14294 file. By default this file is placed in the current directory and has the
14295 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14297 Some of the computed metrics are summed over the units passed to
14298 @command{gnatmetric}; for example, the total number of lines of code.
14299 By default this information is sent to @file{stdout}, but a file
14300 can be specified with the @option{-og} switch.
14302 The following switches control the @command{gnatmetric} output:
14305 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14307 Generate the XML output
14309 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14311 Generate the XML output and the XML schema file that describes the structure
14312 of the XML metric report, this schema is assigned to the XML file. The schema
14313 file has the same name as the XML output file with @file{.xml} suffix replaced
14316 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14317 @item ^-nt^/NO_TEXT^
14318 Do not generate the output in text form (implies @option{^-x^/XML^})
14320 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14321 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14322 Put text files with detailed metrics into @var{output_dir}
14324 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14325 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14326 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14327 in the name of the output file.
14329 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14330 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14331 Put global metrics into @var{file_name}
14333 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14334 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14335 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14337 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14338 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14339 Use ``short'' source file names in the output. (The @command{gnatmetric}
14340 output includes the name(s) of the Ada source file(s) from which the metrics
14341 are computed. By default each name includes the absolute path. The
14342 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14343 to exclude all directory information from the file names that are output.)
14347 @node Disable Metrics For Local Units
14348 @subsection Disable Metrics For Local Units
14349 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14352 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14354 unit per one source file. It computes line metrics for the whole source
14355 file, and it also computes syntax
14356 and complexity metrics for the file's outermost unit.
14358 By default, @command{gnatmetric} will also compute all metrics for certain
14359 kinds of locally declared program units:
14363 subprogram (and generic subprogram) bodies;
14366 package (and generic package) specs and bodies;
14369 task object and type specifications and bodies;
14372 protected object and type specifications and bodies.
14376 These kinds of entities will be referred to as
14377 @emph{eligible local program units}, or simply @emph{eligible local units},
14378 @cindex Eligible local unit (for @command{gnatmetric})
14379 in the discussion below.
14381 Note that a subprogram declaration, generic instantiation,
14382 or renaming declaration only receives metrics
14383 computation when it appear as the outermost entity
14386 Suppression of metrics computation for eligible local units can be
14387 obtained via the following switch:
14390 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14391 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14392 Do not compute detailed metrics for eligible local program units
14396 @node Specifying a set of metrics to compute
14397 @subsection Specifying a set of metrics to compute
14400 By default all the metrics are computed and reported. The switches
14401 described in this subsection allow you to control, on an individual
14402 basis, whether metrics are computed and
14403 reported. If at least one positive metric
14404 switch is specified (that is, a switch that defines that a given
14405 metric or set of metrics is to be computed), then only
14406 explicitly specified metrics are reported.
14409 * Line Metrics Control::
14410 * Syntax Metrics Control::
14411 * Complexity Metrics Control::
14412 * Coupling Metrics Control::
14415 @node Line Metrics Control
14416 @subsubsection Line Metrics Control
14417 @cindex Line metrics control in @command{gnatmetric}
14420 For any (legal) source file, and for each of its
14421 eligible local program units, @command{gnatmetric} computes the following
14426 the total number of lines;
14429 the total number of code lines (i.e., non-blank lines that are not comments)
14432 the number of comment lines
14435 the number of code lines containing end-of-line comments;
14438 the comment percentage: the ratio between the number of lines that contain
14439 comments and the number of all non-blank lines, expressed as a percentage;
14442 the number of empty lines and lines containing only space characters and/or
14443 format effectors (blank lines)
14446 the average number of code lines in subprogram bodies, task bodies, entry
14447 bodies and statement sequences in package bodies (this metric is only computed
14448 across the whole set of the analyzed units)
14453 @command{gnatmetric} sums the values of the line metrics for all the
14454 files being processed and then generates the cumulative results. The tool
14455 also computes for all the files being processed the average number of code
14458 You can use the following switches to select the specific line metrics
14459 to be computed and reported.
14462 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14465 @cindex @option{--no-lines@var{x}}
14468 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14469 Report all the line metrics
14471 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14472 Do not report any of line metrics
14474 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14475 Report the number of all lines
14477 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14478 Do not report the number of all lines
14480 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14481 Report the number of code lines
14483 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14484 Do not report the number of code lines
14486 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14487 Report the number of comment lines
14489 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14490 Do not report the number of comment lines
14492 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14493 Report the number of code lines containing
14494 end-of-line comments
14496 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14497 Do not report the number of code lines containing
14498 end-of-line comments
14500 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14501 Report the comment percentage in the program text
14503 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14504 Do not report the comment percentage in the program text
14506 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14507 Report the number of blank lines
14509 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14510 Do not report the number of blank lines
14512 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14513 Report the average number of code lines in subprogram bodies, task bodies,
14514 entry bodies and statement sequences in package bodies. The metric is computed
14515 and reported for the whole set of processed Ada sources only.
14517 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14518 Do not report the average number of code lines in subprogram bodies,
14519 task bodies, entry bodies and statement sequences in package bodies.
14523 @node Syntax Metrics Control
14524 @subsubsection Syntax Metrics Control
14525 @cindex Syntax metrics control in @command{gnatmetric}
14528 @command{gnatmetric} computes various syntactic metrics for the
14529 outermost unit and for each eligible local unit:
14532 @item LSLOC (``Logical Source Lines Of Code'')
14533 The total number of declarations and the total number of statements. Note
14534 that the definition of declarations is the one given in the reference
14538 ``Each of the following is defined to be a declaration: any basic_declaration;
14539 an enumeration_literal_specification; a discriminant_specification;
14540 a component_declaration; a loop_parameter_specification; a
14541 parameter_specification; a subprogram_body; an entry_declaration;
14542 an entry_index_specification; a choice_parameter_specification;
14543 a generic_formal_parameter_declaration.''
14545 This means for example that each enumeration literal adds one to the count,
14546 as well as each subprogram parameter.
14548 Thus the results from this metric will be significantly greater than might
14549 be expected from a naive view of counting semicolons.
14551 @item Maximal static nesting level of inner program units
14553 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14554 package, a task unit, a protected unit, a
14555 protected entry, a generic unit, or an explicitly declared subprogram other
14556 than an enumeration literal.''
14558 @item Maximal nesting level of composite syntactic constructs
14559 This corresponds to the notion of the
14560 maximum nesting level in the GNAT built-in style checks
14561 (@pxref{Style Checking})
14565 For the outermost unit in the file, @command{gnatmetric} additionally computes
14566 the following metrics:
14569 @item Public subprograms
14570 This metric is computed for package specs. It is the
14571 number of subprograms and generic subprograms declared in the visible
14572 part (including the visible part of nested packages, protected objects, and
14575 @item All subprograms
14576 This metric is computed for bodies and subunits. The
14577 metric is equal to a total number of subprogram bodies in the compilation
14579 Neither generic instantiations nor renamings-as-a-body nor body stubs
14580 are counted. Any subprogram body is counted, independently of its nesting
14581 level and enclosing constructs. Generic bodies and bodies of protected
14582 subprograms are counted in the same way as ``usual'' subprogram bodies.
14585 This metric is computed for package specs and
14586 generic package declarations. It is the total number of types
14587 that can be referenced from outside this compilation unit, plus the
14588 number of types from all the visible parts of all the visible generic
14589 packages. Generic formal types are not counted. Only types, not subtypes,
14593 Along with the total number of public types, the following
14594 types are counted and reported separately:
14601 Root tagged types (abstract, non-abstract, private, non-private). Type
14602 extensions are @emph{not} counted
14605 Private types (including private extensions)
14616 This metric is computed for any compilation unit. It is equal to the total
14617 number of the declarations of different types given in the compilation unit.
14618 The private and the corresponding full type declaration are counted as one
14619 type declaration. Incomplete type declarations and generic formal types
14621 No distinction is made among different kinds of types (abstract,
14622 private etc.); the total number of types is computed and reported.
14627 By default, all the syntax metrics are computed and reported. You can use the
14628 following switches to select specific syntax metrics.
14632 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14635 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14638 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14639 Report all the syntax metrics
14641 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14642 Do not report any of syntax metrics
14644 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14645 Report the total number of declarations
14647 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14648 Do not report the total number of declarations
14650 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14651 Report the total number of statements
14653 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14654 Do not report the total number of statements
14656 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14657 Report the number of public subprograms in a compilation unit
14659 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14660 Do not report the number of public subprograms in a compilation unit
14662 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14663 Report the number of all the subprograms in a compilation unit
14665 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14666 Do not report the number of all the subprograms in a compilation unit
14668 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14669 Report the number of public types in a compilation unit
14671 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14672 Do not report the number of public types in a compilation unit
14674 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14675 Report the number of all the types in a compilation unit
14677 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14678 Do not report the number of all the types in a compilation unit
14680 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14681 Report the maximal program unit nesting level
14683 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14684 Do not report the maximal program unit nesting level
14686 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14687 Report the maximal construct nesting level
14689 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14690 Do not report the maximal construct nesting level
14694 @node Complexity Metrics Control
14695 @subsubsection Complexity Metrics Control
14696 @cindex Complexity metrics control in @command{gnatmetric}
14699 For a program unit that is an executable body (a subprogram body (including
14700 generic bodies), task body, entry body or a package body containing
14701 its own statement sequence) @command{gnatmetric} computes the following
14702 complexity metrics:
14706 McCabe cyclomatic complexity;
14709 McCabe essential complexity;
14712 maximal loop nesting level;
14715 extra exit points (for subprograms);
14719 The McCabe cyclomatic complexity metric is defined
14720 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14722 According to McCabe, both control statements and short-circuit control forms
14723 should be taken into account when computing cyclomatic complexity. For each
14724 body, we compute three metric values:
14728 the complexity introduced by control
14729 statements only, without taking into account short-circuit forms,
14732 the complexity introduced by short-circuit control forms only, and
14736 cyclomatic complexity, which is the sum of these two values.
14741 The origin of cyclomatic complexity metric is the need to estimate the number
14742 of independent paths in the control flow graph that in turn gives the number
14743 of tests needed to satisfy paths coverage testing completeness criterion.
14744 Considered from the testing point of view, a static Ada @code{loop} (that is,
14745 the @code{loop} statement having static subtype in loop parameter
14746 specification) does not add to cyclomatic complexity. By providing
14747 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14748 may specify that such loops should not be counted when computing the
14749 cyclomatic complexity metric
14751 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14752 counted for the code that is reduced by excluding all the pure structural Ada
14753 control statements. An compound statement is considered as a non-structural
14754 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14755 or if it contains a @code{goto} statement that transfers the control outside
14756 the operator. A selective accept statement with @code{terminate} alternative
14757 is considered as non-structural statement. When computing this metric,
14758 @code{exit} statements are treated in the same way as @code{goto}
14759 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14761 The Ada essential complexity metric defined here is intended to quantify
14762 the extent to which the software is unstructured. It is adapted from
14763 the McCabe essential complexity metric defined in
14764 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14765 suitable for typical Ada usage. For example, short circuit forms
14766 are not penalized as unstructured in the Ada essential complexity metric.
14768 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14769 the code in the exception handlers and in all the nested program units.
14771 By default, all the complexity metrics are computed and reported.
14772 For more fine-grained control you can use
14773 the following switches:
14776 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14779 @cindex @option{--no-complexity@var{x}}
14782 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14783 Report all the complexity metrics
14785 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14786 Do not report any of complexity metrics
14788 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14789 Report the McCabe Cyclomatic Complexity
14791 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14792 Do not report the McCabe Cyclomatic Complexity
14794 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14795 Report the Essential Complexity
14797 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14798 Do not report the Essential Complexity
14800 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14801 Report maximal loop nesting level
14803 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14804 Do not report maximal loop nesting level
14806 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14807 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14808 task bodies, entry bodies and statement sequences in package bodies.
14809 The metric is computed and reported for whole set of processed Ada sources
14812 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14813 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14814 bodies, task bodies, entry bodies and statement sequences in package bodies
14816 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14817 @item ^-ne^/NO_EXITS_AS_GOTOS^
14818 Do not consider @code{exit} statements as @code{goto}s when
14819 computing Essential Complexity
14821 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14822 @item ^--no-static-loop^/NO_STATIC_LOOP^
14823 Do not consider static loops when computing cyclomatic complexity
14825 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14826 Report the extra exit points for subprogram bodies. As an exit point, this
14827 metric counts @code{return} statements and raise statements in case when the
14828 raised exception is not handled in the same body. In case of a function this
14829 metric subtracts 1 from the number of exit points, because a function body
14830 must contain at least one @code{return} statement.
14832 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14833 Do not report the extra exit points for subprogram bodies
14837 @node Coupling Metrics Control
14838 @subsubsection Coupling Metrics Control
14839 @cindex Coupling metrics control in @command{gnatmetric}
14842 @cindex Coupling metrics (in in @command{gnatmetric})
14843 Coupling metrics measure the dependencies between a given entity and other
14844 entities the program consists of. The goal of these metrics is to estimate the
14845 stability of the whole program considered as the collection of entities
14846 (modules, classes etc.).
14848 Gnatmetric computes the following coupling metrics:
14853 @emph{object-oriented coupling} - for classes in traditional object-oriented
14857 @emph{unit coupling} - for all the program units making up a program;
14860 @emph{control coupling} - this metric counts dependencies between a unit and
14861 only those units that define subprograms;
14865 Two kinds of coupling metrics are computed:
14868 @item fan-out coupling (efferent coupling)
14869 @cindex fan-out coupling
14870 @cindex efferent coupling
14871 the number of entities the given entity depends upon. It
14872 estimates in what extent the given entity depends on the changes in
14875 @item fan-in coupling (afferent coupling)
14876 @cindex fan-in coupling
14877 @cindex afferent coupling
14878 the number of entities that depend on a given entity.
14879 It estimates in what extent the ``external world'' depends on the changes in a
14885 Object-oriented coupling metrics are metrics that measure the dependencies
14886 between a given class (or a group of classes) and the other classes in the
14887 program. In this subsection the term ``class'' is used in its traditional
14888 object-oriented programming sense (an instantiable module that contains data
14889 and/or method members). A @emph{category} (of classes) is a group of closely
14890 related classes that are reused and/or modified together.
14892 A class @code{K}'s fan-out coupling is the number of classes
14893 that @code{K} depends upon.
14894 A category's fan-out coupling is the number of classes outside the
14895 category that the classes inside the category depend upon.
14897 A class @code{K}'s fan-in coupling is the number of classes
14898 that depend upon @code{K}.
14899 A category's fan-in coupling is the number of classes outside the
14900 category that depend on classes belonging to the category.
14902 Ada's implementation of the object-oriented paradigm does not use the
14903 traditional class notion, so the definition of the coupling
14904 metrics for Ada maps the class and class category notions
14905 onto Ada constructs.
14907 For the coupling metrics, several kinds of modules -- a library package,
14908 a library generic package, and a library generic package instantiation --
14909 that define a tagged type or an interface type are
14910 considered to be a class. A category consists of a library package (or
14911 a library generic package) that defines a tagged or an interface type,
14912 together with all its descendant (generic) packages that define tagged
14913 or interface types. That is a
14914 category is an Ada hierarchy of library-level program units. So class coupling
14915 in case of Ada is called as tagged coupling, and category coupling - as
14916 hierarchy coupling.
14918 For any package counted as a class, its body and subunits (if any) are
14919 considered together with its spec when counting the dependencies, and coupling
14920 metrics are reported for spec units only. For dependencies between classes,
14921 the Ada semantic dependencies are considered. For object-oriented coupling
14922 metrics, only dependencies on units that are considered as classes, are
14925 For unit and control coupling also not compilation units but program units are
14926 counted. That is, for a package, its spec, its body and its subunits (if any)
14927 are considered as making up one unit, and the dependencies that are counted
14928 are the dependencies of all these compilation units collected together as
14929 the dependencies as a (whole) unit. And metrics are reported for spec
14930 compilation units only (or for a subprogram body unit in case if there is no
14931 separate spec for the given subprogram).
14933 For unit coupling, dependencies between all kinds of program units are
14934 considered. For control coupling, for each unit the dependencies of this unit
14935 upon units that define subprograms are counted, so control fan-out coupling
14936 is reported for all units, but control fan-in coupling - only for the units
14937 that define subprograms.
14944 When computing coupling metrics, @command{gnatmetric} counts only
14945 dependencies between units that are arguments of the gnatmetric call.
14946 Coupling metrics are program-wide (or project-wide) metrics, so to
14947 get a valid result, you should call @command{gnatmetric} for
14948 the whole set of sources that make up your program. It can be done
14949 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14950 option (see @ref{The GNAT Driver and Project Files} for details).
14952 By default, all the coupling metrics are disabled. You can use the following
14953 switches to specify the coupling metrics to be computed and reported:
14958 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14959 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14960 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14961 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14965 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14968 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14969 Report all the coupling metrics
14971 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14972 Report tagged (class) fan-out coupling
14974 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14975 Report tagged (class) fan-in coupling
14977 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14978 Report hierarchy (category) fan-out coupling
14980 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14981 Report hierarchy (category) fan-in coupling
14983 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14984 Report unit fan-out coupling
14986 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14987 Report unit fan-in coupling
14989 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14990 Report control fan-out coupling
14992 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14993 Report control fan-in coupling
14996 @node Other gnatmetric Switches
14997 @subsection Other @code{gnatmetric} Switches
15000 Additional @command{gnatmetric} switches are as follows:
15003 @item ^-files @var{filename}^/FILES=@var{filename}^
15004 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15005 Take the argument source files from the specified file. This file should be an
15006 ordinary text file containing file names separated by spaces or
15007 line breaks. You can use this switch more than once in the same call to
15008 @command{gnatmetric}. You also can combine this switch with
15009 an explicit list of files.
15011 @item ^-v^/VERBOSE^
15012 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15014 @command{gnatmetric} generates version information and then
15015 a trace of sources being processed.
15018 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15022 @node Generate project-wide metrics
15023 @subsection Generate project-wide metrics
15025 In order to compute metrics on all units of a given project, you can use
15026 the @command{gnat} driver along with the @option{-P} option:
15032 If the project @code{proj} depends upon other projects, you can compute
15033 the metrics on the project closure using the @option{-U} option:
15035 gnat metric -Pproj -U
15039 Finally, if not all the units are relevant to a particular main
15040 program in the project closure, you can generate metrics for the set
15041 of units needed to create a given main program (unit closure) using
15042 the @option{-U} option followed by the name of the main unit:
15044 gnat metric -Pproj -U main
15048 @c ***********************************
15049 @node File Name Krunching Using gnatkr
15050 @chapter File Name Krunching Using @code{gnatkr}
15054 This chapter discusses the method used by the compiler to shorten
15055 the default file names chosen for Ada units so that they do not
15056 exceed the maximum length permitted. It also describes the
15057 @code{gnatkr} utility that can be used to determine the result of
15058 applying this shortening.
15062 * Krunching Method::
15063 * Examples of gnatkr Usage::
15067 @section About @code{gnatkr}
15070 The default file naming rule in GNAT
15071 is that the file name must be derived from
15072 the unit name. The exact default rule is as follows:
15075 Take the unit name and replace all dots by hyphens.
15077 If such a replacement occurs in the
15078 second character position of a name, and the first character is
15079 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15080 then replace the dot by the character
15081 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15082 instead of a minus.
15084 The reason for this exception is to avoid clashes
15085 with the standard names for children of System, Ada, Interfaces,
15086 and GNAT, which use the prefixes
15087 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15090 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15091 switch of the compiler activates a ``krunching''
15092 circuit that limits file names to nn characters (where nn is a decimal
15093 integer). For example, using OpenVMS,
15094 where the maximum file name length is
15095 39, the value of nn is usually set to 39, but if you want to generate
15096 a set of files that would be usable if ported to a system with some
15097 different maximum file length, then a different value can be specified.
15098 The default value of 39 for OpenVMS need not be specified.
15100 The @code{gnatkr} utility can be used to determine the krunched name for
15101 a given file, when krunched to a specified maximum length.
15104 @section Using @code{gnatkr}
15107 The @code{gnatkr} command has the form
15111 @c $ gnatkr @var{name} @ovar{length}
15112 @c Expanding @ovar macro inline (explanation in macro def comments)
15113 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15119 $ gnatkr @var{name} /COUNT=nn
15124 @var{name} is the uncrunched file name, derived from the name of the unit
15125 in the standard manner described in the previous section (i.e., in particular
15126 all dots are replaced by hyphens). The file name may or may not have an
15127 extension (defined as a suffix of the form period followed by arbitrary
15128 characters other than period). If an extension is present then it will
15129 be preserved in the output. For example, when krunching @file{hellofile.ads}
15130 to eight characters, the result will be hellofil.ads.
15132 Note: for compatibility with previous versions of @code{gnatkr} dots may
15133 appear in the name instead of hyphens, but the last dot will always be
15134 taken as the start of an extension. So if @code{gnatkr} is given an argument
15135 such as @file{Hello.World.adb} it will be treated exactly as if the first
15136 period had been a hyphen, and for example krunching to eight characters
15137 gives the result @file{hellworl.adb}.
15139 Note that the result is always all lower case (except on OpenVMS where it is
15140 all upper case). Characters of the other case are folded as required.
15142 @var{length} represents the length of the krunched name. The default
15143 when no argument is given is ^8^39^ characters. A length of zero stands for
15144 unlimited, in other words do not chop except for system files where the
15145 implied crunching length is always eight characters.
15148 The output is the krunched name. The output has an extension only if the
15149 original argument was a file name with an extension.
15151 @node Krunching Method
15152 @section Krunching Method
15155 The initial file name is determined by the name of the unit that the file
15156 contains. The name is formed by taking the full expanded name of the
15157 unit and replacing the separating dots with hyphens and
15158 using ^lowercase^uppercase^
15159 for all letters, except that a hyphen in the second character position is
15160 replaced by a ^tilde^dollar sign^ if the first character is
15161 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15162 The extension is @code{.ads} for a
15163 spec and @code{.adb} for a body.
15164 Krunching does not affect the extension, but the file name is shortened to
15165 the specified length by following these rules:
15169 The name is divided into segments separated by hyphens, tildes or
15170 underscores and all hyphens, tildes, and underscores are
15171 eliminated. If this leaves the name short enough, we are done.
15174 If the name is too long, the longest segment is located (left-most
15175 if there are two of equal length), and shortened by dropping
15176 its last character. This is repeated until the name is short enough.
15178 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15179 to fit the name into 8 characters as required by some operating systems.
15182 our-strings-wide_fixed 22
15183 our strings wide fixed 19
15184 our string wide fixed 18
15185 our strin wide fixed 17
15186 our stri wide fixed 16
15187 our stri wide fixe 15
15188 our str wide fixe 14
15189 our str wid fixe 13
15195 Final file name: oustwifi.adb
15199 The file names for all predefined units are always krunched to eight
15200 characters. The krunching of these predefined units uses the following
15201 special prefix replacements:
15205 replaced by @file{^a^A^-}
15208 replaced by @file{^g^G^-}
15211 replaced by @file{^i^I^-}
15214 replaced by @file{^s^S^-}
15217 These system files have a hyphen in the second character position. That
15218 is why normal user files replace such a character with a
15219 ^tilde^dollar sign^, to
15220 avoid confusion with system file names.
15222 As an example of this special rule, consider
15223 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15226 ada-strings-wide_fixed 22
15227 a- strings wide fixed 18
15228 a- string wide fixed 17
15229 a- strin wide fixed 16
15230 a- stri wide fixed 15
15231 a- stri wide fixe 14
15232 a- str wide fixe 13
15238 Final file name: a-stwifi.adb
15242 Of course no file shortening algorithm can guarantee uniqueness over all
15243 possible unit names, and if file name krunching is used then it is your
15244 responsibility to ensure that no name clashes occur. The utility
15245 program @code{gnatkr} is supplied for conveniently determining the
15246 krunched name of a file.
15248 @node Examples of gnatkr Usage
15249 @section Examples of @code{gnatkr} Usage
15256 $ gnatkr very_long_unit_name.ads --> velounna.ads
15257 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15258 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15259 $ gnatkr grandparent-parent-child --> grparchi
15261 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15262 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15265 @node Preprocessing Using gnatprep
15266 @chapter Preprocessing Using @code{gnatprep}
15270 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15272 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15273 special GNAT features.
15274 For further discussion of conditional compilation in general, see
15275 @ref{Conditional Compilation}.
15278 * Preprocessing Symbols::
15280 * Switches for gnatprep::
15281 * Form of Definitions File::
15282 * Form of Input Text for gnatprep::
15285 @node Preprocessing Symbols
15286 @section Preprocessing Symbols
15289 Preprocessing symbols are defined in definition files and referred to in
15290 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15291 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15292 all characters need to be in the ASCII set (no accented letters).
15294 @node Using gnatprep
15295 @section Using @code{gnatprep}
15298 To call @code{gnatprep} use
15301 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15302 @c Expanding @ovar macro inline (explanation in macro def comments)
15303 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15310 is an optional sequence of switches as described in the next section.
15313 is the full name of the input file, which is an Ada source
15314 file containing preprocessor directives.
15317 is the full name of the output file, which is an Ada source
15318 in standard Ada form. When used with GNAT, this file name will
15319 normally have an ads or adb suffix.
15322 is the full name of a text file containing definitions of
15323 preprocessing symbols to be referenced by the preprocessor. This argument is
15324 optional, and can be replaced by the use of the @option{-D} switch.
15328 @node Switches for gnatprep
15329 @section Switches for @code{gnatprep}
15334 @item ^-b^/BLANK_LINES^
15335 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15336 Causes both preprocessor lines and the lines deleted by
15337 preprocessing to be replaced by blank lines in the output source file,
15338 preserving line numbers in the output file.
15340 @item ^-c^/COMMENTS^
15341 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15342 Causes both preprocessor lines and the lines deleted
15343 by preprocessing to be retained in the output source as comments marked
15344 with the special string @code{"--! "}. This option will result in line numbers
15345 being preserved in the output file.
15347 @item ^-C^/REPLACE_IN_COMMENTS^
15348 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15349 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15350 If this option is specified, then comments are scanned and any $symbol
15351 substitutions performed as in program text. This is particularly useful
15352 when structured comments are used (e.g., when writing programs in the
15353 SPARK dialect of Ada). Note that this switch is not available when
15354 doing integrated preprocessing (it would be useless in this context
15355 since comments are ignored by the compiler in any case).
15357 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15358 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15359 Defines a new preprocessing symbol, associated with value. If no value is given
15360 on the command line, then symbol is considered to be @code{True}. This switch
15361 can be used in place of a definition file.
15365 @cindex @option{/REMOVE} (@command{gnatprep})
15366 This is the default setting which causes lines deleted by preprocessing
15367 to be entirely removed from the output file.
15370 @item ^-r^/REFERENCE^
15371 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15372 Causes a @code{Source_Reference} pragma to be generated that
15373 references the original input file, so that error messages will use
15374 the file name of this original file. The use of this switch implies
15375 that preprocessor lines are not to be removed from the file, so its
15376 use will force @option{^-b^/BLANK_LINES^} mode if
15377 @option{^-c^/COMMENTS^}
15378 has not been specified explicitly.
15380 Note that if the file to be preprocessed contains multiple units, then
15381 it will be necessary to @code{gnatchop} the output file from
15382 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15383 in the preprocessed file, it will be respected by
15384 @code{gnatchop ^-r^/REFERENCE^}
15385 so that the final chopped files will correctly refer to the original
15386 input source file for @code{gnatprep}.
15388 @item ^-s^/SYMBOLS^
15389 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15390 Causes a sorted list of symbol names and values to be
15391 listed on the standard output file.
15393 @item ^-u^/UNDEFINED^
15394 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15395 Causes undefined symbols to be treated as having the value FALSE in the context
15396 of a preprocessor test. In the absence of this option, an undefined symbol in
15397 a @code{#if} or @code{#elsif} test will be treated as an error.
15403 Note: if neither @option{-b} nor @option{-c} is present,
15404 then preprocessor lines and
15405 deleted lines are completely removed from the output, unless -r is
15406 specified, in which case -b is assumed.
15409 @node Form of Definitions File
15410 @section Form of Definitions File
15413 The definitions file contains lines of the form
15420 where symbol is a preprocessing symbol, and value is one of the following:
15424 Empty, corresponding to a null substitution
15426 A string literal using normal Ada syntax
15428 Any sequence of characters from the set
15429 (letters, digits, period, underline).
15433 Comment lines may also appear in the definitions file, starting with
15434 the usual @code{--},
15435 and comments may be added to the definitions lines.
15437 @node Form of Input Text for gnatprep
15438 @section Form of Input Text for @code{gnatprep}
15441 The input text may contain preprocessor conditional inclusion lines,
15442 as well as general symbol substitution sequences.
15444 The preprocessor conditional inclusion commands have the form
15449 #if @i{expression} @r{[}then@r{]}
15451 #elsif @i{expression} @r{[}then@r{]}
15453 #elsif @i{expression} @r{[}then@r{]}
15464 In this example, @i{expression} is defined by the following grammar:
15466 @i{expression} ::= <symbol>
15467 @i{expression} ::= <symbol> = "<value>"
15468 @i{expression} ::= <symbol> = <symbol>
15469 @i{expression} ::= <symbol> 'Defined
15470 @i{expression} ::= not @i{expression}
15471 @i{expression} ::= @i{expression} and @i{expression}
15472 @i{expression} ::= @i{expression} or @i{expression}
15473 @i{expression} ::= @i{expression} and then @i{expression}
15474 @i{expression} ::= @i{expression} or else @i{expression}
15475 @i{expression} ::= ( @i{expression} )
15478 The following restriction exists: it is not allowed to have "and" or "or"
15479 following "not" in the same expression without parentheses. For example, this
15486 This should be one of the following:
15494 For the first test (@i{expression} ::= <symbol>) the symbol must have
15495 either the value true or false, that is to say the right-hand of the
15496 symbol definition must be one of the (case-insensitive) literals
15497 @code{True} or @code{False}. If the value is true, then the
15498 corresponding lines are included, and if the value is false, they are
15501 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15502 the symbol has been defined in the definition file or by a @option{-D}
15503 switch on the command line. Otherwise, the test is false.
15505 The equality tests are case insensitive, as are all the preprocessor lines.
15507 If the symbol referenced is not defined in the symbol definitions file,
15508 then the effect depends on whether or not switch @option{-u}
15509 is specified. If so, then the symbol is treated as if it had the value
15510 false and the test fails. If this switch is not specified, then
15511 it is an error to reference an undefined symbol. It is also an error to
15512 reference a symbol that is defined with a value other than @code{True}
15515 The use of the @code{not} operator inverts the sense of this logical test.
15516 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15517 operators, without parentheses. For example, "if not X or Y then" is not
15518 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15520 The @code{then} keyword is optional as shown
15522 The @code{#} must be the first non-blank character on a line, but
15523 otherwise the format is free form. Spaces or tabs may appear between
15524 the @code{#} and the keyword. The keywords and the symbols are case
15525 insensitive as in normal Ada code. Comments may be used on a
15526 preprocessor line, but other than that, no other tokens may appear on a
15527 preprocessor line. Any number of @code{elsif} clauses can be present,
15528 including none at all. The @code{else} is optional, as in Ada.
15530 The @code{#} marking the start of a preprocessor line must be the first
15531 non-blank character on the line, i.e., it must be preceded only by
15532 spaces or horizontal tabs.
15534 Symbol substitution outside of preprocessor lines is obtained by using
15542 anywhere within a source line, except in a comment or within a
15543 string literal. The identifier
15544 following the @code{$} must match one of the symbols defined in the symbol
15545 definition file, and the result is to substitute the value of the
15546 symbol in place of @code{$symbol} in the output file.
15548 Note that although the substitution of strings within a string literal
15549 is not possible, it is possible to have a symbol whose defined value is
15550 a string literal. So instead of setting XYZ to @code{hello} and writing:
15553 Header : String := "$XYZ";
15557 you should set XYZ to @code{"hello"} and write:
15560 Header : String := $XYZ;
15564 and then the substitution will occur as desired.
15566 @node The GNAT Library Browser gnatls
15567 @chapter The GNAT Library Browser @code{gnatls}
15569 @cindex Library browser
15572 @code{gnatls} is a tool that outputs information about compiled
15573 units. It gives the relationship between objects, unit names and source
15574 files. It can also be used to check the source dependencies of a unit
15575 as well as various characteristics.
15577 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15578 driver (see @ref{The GNAT Driver and Project Files}).
15582 * Switches for gnatls::
15583 * Examples of gnatls Usage::
15586 @node Running gnatls
15587 @section Running @code{gnatls}
15590 The @code{gnatls} command has the form
15593 $ gnatls switches @var{object_or_ali_file}
15597 The main argument is the list of object or @file{ali} files
15598 (@pxref{The Ada Library Information Files})
15599 for which information is requested.
15601 In normal mode, without additional option, @code{gnatls} produces a
15602 four-column listing. Each line represents information for a specific
15603 object. The first column gives the full path of the object, the second
15604 column gives the name of the principal unit in this object, the third
15605 column gives the status of the source and the fourth column gives the
15606 full path of the source representing this unit.
15607 Here is a simple example of use:
15611 ^./^[]^demo1.o demo1 DIF demo1.adb
15612 ^./^[]^demo2.o demo2 OK demo2.adb
15613 ^./^[]^hello.o h1 OK hello.adb
15614 ^./^[]^instr-child.o instr.child MOK instr-child.adb
15615 ^./^[]^instr.o instr OK instr.adb
15616 ^./^[]^tef.o tef DIF tef.adb
15617 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
15618 ^./^[]^tgef.o tgef DIF tgef.adb
15622 The first line can be interpreted as follows: the main unit which is
15624 object file @file{demo1.o} is demo1, whose main source is in
15625 @file{demo1.adb}. Furthermore, the version of the source used for the
15626 compilation of demo1 has been modified (DIF). Each source file has a status
15627 qualifier which can be:
15630 @item OK (unchanged)
15631 The version of the source file used for the compilation of the
15632 specified unit corresponds exactly to the actual source file.
15634 @item MOK (slightly modified)
15635 The version of the source file used for the compilation of the
15636 specified unit differs from the actual source file but not enough to
15637 require recompilation. If you use gnatmake with the qualifier
15638 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15639 MOK will not be recompiled.
15641 @item DIF (modified)
15642 No version of the source found on the path corresponds to the source
15643 used to build this object.
15645 @item ??? (file not found)
15646 No source file was found for this unit.
15648 @item HID (hidden, unchanged version not first on PATH)
15649 The version of the source that corresponds exactly to the source used
15650 for compilation has been found on the path but it is hidden by another
15651 version of the same source that has been modified.
15655 @node Switches for gnatls
15656 @section Switches for @code{gnatls}
15659 @code{gnatls} recognizes the following switches:
15663 @cindex @option{--version} @command{gnatls}
15664 Display Copyright and version, then exit disregarding all other options.
15667 @cindex @option{--help} @command{gnatls}
15668 If @option{--version} was not used, display usage, then exit disregarding
15671 @item ^-a^/ALL_UNITS^
15672 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15673 Consider all units, including those of the predefined Ada library.
15674 Especially useful with @option{^-d^/DEPENDENCIES^}.
15676 @item ^-d^/DEPENDENCIES^
15677 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15678 List sources from which specified units depend on.
15680 @item ^-h^/OUTPUT=OPTIONS^
15681 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15682 Output the list of options.
15684 @item ^-o^/OUTPUT=OBJECTS^
15685 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15686 Only output information about object files.
15688 @item ^-s^/OUTPUT=SOURCES^
15689 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15690 Only output information about source files.
15692 @item ^-u^/OUTPUT=UNITS^
15693 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15694 Only output information about compilation units.
15696 @item ^-files^/FILES^=@var{file}
15697 @cindex @option{^-files^/FILES^} (@code{gnatls})
15698 Take as arguments the files listed in text file @var{file}.
15699 Text file @var{file} may contain empty lines that are ignored.
15700 Each nonempty line should contain the name of an existing file.
15701 Several such switches may be specified simultaneously.
15703 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15704 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15705 @itemx ^-I^/SEARCH=^@var{dir}
15706 @itemx ^-I-^/NOCURRENT_DIRECTORY^
15708 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15709 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15710 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15711 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15712 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15713 flags (@pxref{Switches for gnatmake}).
15715 @item --RTS=@var{rts-path}
15716 @cindex @option{--RTS} (@code{gnatls})
15717 Specifies the default location of the runtime library. Same meaning as the
15718 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15720 @item ^-v^/OUTPUT=VERBOSE^
15721 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15722 Verbose mode. Output the complete source, object and project paths. Do not use
15723 the default column layout but instead use long format giving as much as
15724 information possible on each requested units, including special
15725 characteristics such as:
15728 @item Preelaborable
15729 The unit is preelaborable in the Ada sense.
15732 No elaboration code has been produced by the compiler for this unit.
15735 The unit is pure in the Ada sense.
15737 @item Elaborate_Body
15738 The unit contains a pragma Elaborate_Body.
15741 The unit contains a pragma Remote_Types.
15743 @item Shared_Passive
15744 The unit contains a pragma Shared_Passive.
15747 This unit is part of the predefined environment and cannot be modified
15750 @item Remote_Call_Interface
15751 The unit contains a pragma Remote_Call_Interface.
15757 @node Examples of gnatls Usage
15758 @section Example of @code{gnatls} Usage
15762 Example of using the verbose switch. Note how the source and
15763 object paths are affected by the -I switch.
15766 $ gnatls -v -I.. demo1.o
15768 GNATLS 5.03w (20041123-34)
15769 Copyright 1997-2004 Free Software Foundation, Inc.
15771 Source Search Path:
15772 <Current_Directory>
15774 /home/comar/local/adainclude/
15776 Object Search Path:
15777 <Current_Directory>
15779 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15781 Project Search Path:
15782 <Current_Directory>
15783 /home/comar/local/lib/gnat/
15788 Kind => subprogram body
15789 Flags => No_Elab_Code
15790 Source => demo1.adb modified
15794 The following is an example of use of the dependency list.
15795 Note the use of the -s switch
15796 which gives a straight list of source files. This can be useful for
15797 building specialized scripts.
15800 $ gnatls -d demo2.o
15801 ./demo2.o demo2 OK demo2.adb
15807 $ gnatls -d -s -a demo1.o
15809 /home/comar/local/adainclude/ada.ads
15810 /home/comar/local/adainclude/a-finali.ads
15811 /home/comar/local/adainclude/a-filico.ads
15812 /home/comar/local/adainclude/a-stream.ads
15813 /home/comar/local/adainclude/a-tags.ads
15816 /home/comar/local/adainclude/gnat.ads
15817 /home/comar/local/adainclude/g-io.ads
15819 /home/comar/local/adainclude/system.ads
15820 /home/comar/local/adainclude/s-exctab.ads
15821 /home/comar/local/adainclude/s-finimp.ads
15822 /home/comar/local/adainclude/s-finroo.ads
15823 /home/comar/local/adainclude/s-secsta.ads
15824 /home/comar/local/adainclude/s-stalib.ads
15825 /home/comar/local/adainclude/s-stoele.ads
15826 /home/comar/local/adainclude/s-stratt.ads
15827 /home/comar/local/adainclude/s-tasoli.ads
15828 /home/comar/local/adainclude/s-unstyp.ads
15829 /home/comar/local/adainclude/unchconv.ads
15835 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15840 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15841 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15845 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15848 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15850 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15851 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15852 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15855 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15856 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15857 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15858 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15862 @node Cleaning Up Using gnatclean
15863 @chapter Cleaning Up Using @code{gnatclean}
15865 @cindex Cleaning tool
15868 @code{gnatclean} is a tool that allows the deletion of files produced by the
15869 compiler, binder and linker, including ALI files, object files, tree files,
15870 expanded source files, library files, interface copy source files, binder
15871 generated files and executable files.
15874 * Running gnatclean::
15875 * Switches for gnatclean::
15876 @c * Examples of gnatclean Usage::
15879 @node Running gnatclean
15880 @section Running @code{gnatclean}
15883 The @code{gnatclean} command has the form:
15886 $ gnatclean switches @var{names}
15890 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15891 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15892 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15895 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15896 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15897 the linker. In informative-only mode, specified by switch
15898 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15899 normal mode is listed, but no file is actually deleted.
15901 @node Switches for gnatclean
15902 @section Switches for @code{gnatclean}
15905 @code{gnatclean} recognizes the following switches:
15909 @cindex @option{--version} @command{gnatclean}
15910 Display Copyright and version, then exit disregarding all other options.
15913 @cindex @option{--help} @command{gnatclean}
15914 If @option{--version} was not used, display usage, then exit disregarding
15917 @item ^--subdirs^/SUBDIRS^=subdir
15918 Actual object directory of each project file is the subdirectory subdir of the
15919 object directory specified or defaulted in the project file.
15921 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15922 By default, shared library projects are not allowed to import static library
15923 projects. When this switch is used on the command line, this restriction is
15926 @item ^-c^/COMPILER_FILES_ONLY^
15927 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15928 Only attempt to delete the files produced by the compiler, not those produced
15929 by the binder or the linker. The files that are not to be deleted are library
15930 files, interface copy files, binder generated files and executable files.
15932 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15933 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15934 Indicate that ALI and object files should normally be found in directory
15937 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15938 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15939 When using project files, if some errors or warnings are detected during
15940 parsing and verbose mode is not in effect (no use of switch
15941 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15942 file, rather than its simple file name.
15945 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15946 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15948 @item ^-n^/NODELETE^
15949 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15950 Informative-only mode. Do not delete any files. Output the list of the files
15951 that would have been deleted if this switch was not specified.
15953 @item ^-P^/PROJECT_FILE=^@var{project}
15954 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15955 Use project file @var{project}. Only one such switch can be used.
15956 When cleaning a project file, the files produced by the compilation of the
15957 immediate sources or inherited sources of the project files are to be
15958 deleted. This is not depending on the presence or not of executable names
15959 on the command line.
15962 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15963 Quiet output. If there are no errors, do not output anything, except in
15964 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15965 (switch ^-n^/NODELETE^).
15967 @item ^-r^/RECURSIVE^
15968 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15969 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15970 clean all imported and extended project files, recursively. If this switch
15971 is not specified, only the files related to the main project file are to be
15972 deleted. This switch has no effect if no project file is specified.
15974 @item ^-v^/VERBOSE^
15975 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15978 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15979 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15980 Indicates the verbosity of the parsing of GNAT project files.
15981 @xref{Switches Related to Project Files}.
15983 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15984 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15985 Indicates that external variable @var{name} has the value @var{value}.
15986 The Project Manager will use this value for occurrences of
15987 @code{external(name)} when parsing the project file.
15988 @xref{Switches Related to Project Files}.
15990 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15991 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15992 When searching for ALI and object files, look in directory
15995 @item ^-I^/SEARCH=^@var{dir}
15996 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15997 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15999 @item ^-I-^/NOCURRENT_DIRECTORY^
16000 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16001 @cindex Source files, suppressing search
16002 Do not look for ALI or object files in the directory
16003 where @code{gnatclean} was invoked.
16007 @c @node Examples of gnatclean Usage
16008 @c @section Examples of @code{gnatclean} Usage
16011 @node GNAT and Libraries
16012 @chapter GNAT and Libraries
16013 @cindex Library, building, installing, using
16016 This chapter describes how to build and use libraries with GNAT, and also shows
16017 how to recompile the GNAT run-time library. You should be familiar with the
16018 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16022 * Introduction to Libraries in GNAT::
16023 * General Ada Libraries::
16024 * Stand-alone Ada Libraries::
16025 * Rebuilding the GNAT Run-Time Library::
16028 @node Introduction to Libraries in GNAT
16029 @section Introduction to Libraries in GNAT
16032 A library is, conceptually, a collection of objects which does not have its
16033 own main thread of execution, but rather provides certain services to the
16034 applications that use it. A library can be either statically linked with the
16035 application, in which case its code is directly included in the application,
16036 or, on platforms that support it, be dynamically linked, in which case
16037 its code is shared by all applications making use of this library.
16039 GNAT supports both types of libraries.
16040 In the static case, the compiled code can be provided in different ways. The
16041 simplest approach is to provide directly the set of objects resulting from
16042 compilation of the library source files. Alternatively, you can group the
16043 objects into an archive using whatever commands are provided by the operating
16044 system. For the latter case, the objects are grouped into a shared library.
16046 In the GNAT environment, a library has three types of components:
16052 @xref{The Ada Library Information Files}.
16054 Object files, an archive or a shared library.
16058 A GNAT library may expose all its source files, which is useful for
16059 documentation purposes. Alternatively, it may expose only the units needed by
16060 an external user to make use of the library. That is to say, the specs
16061 reflecting the library services along with all the units needed to compile
16062 those specs, which can include generic bodies or any body implementing an
16063 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16064 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16066 All compilation units comprising an application, including those in a library,
16067 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16068 computes the elaboration order from the @file{ALI} files and this is why they
16069 constitute a mandatory part of GNAT libraries.
16070 @emph{Stand-alone libraries} are the exception to this rule because a specific
16071 library elaboration routine is produced independently of the application(s)
16074 @node General Ada Libraries
16075 @section General Ada Libraries
16078 * Building a library::
16079 * Installing a library::
16080 * Using a library::
16083 @node Building a library
16084 @subsection Building a library
16087 The easiest way to build a library is to use the Project Manager,
16088 which supports a special type of project called a @emph{Library Project}
16089 (@pxref{Library Projects}).
16091 A project is considered a library project, when two project-level attributes
16092 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16093 control different aspects of library configuration, additional optional
16094 project-level attributes can be specified:
16097 This attribute controls whether the library is to be static or dynamic
16099 @item Library_Version
16100 This attribute specifies the library version; this value is used
16101 during dynamic linking of shared libraries to determine if the currently
16102 installed versions of the binaries are compatible.
16104 @item Library_Options
16106 These attributes specify additional low-level options to be used during
16107 library generation, and redefine the actual application used to generate
16112 The GNAT Project Manager takes full care of the library maintenance task,
16113 including recompilation of the source files for which objects do not exist
16114 or are not up to date, assembly of the library archive, and installation of
16115 the library (i.e., copying associated source, object and @file{ALI} files
16116 to the specified location).
16118 Here is a simple library project file:
16119 @smallexample @c ada
16121 for Source_Dirs use ("src1", "src2");
16122 for Object_Dir use "obj";
16123 for Library_Name use "mylib";
16124 for Library_Dir use "lib";
16125 for Library_Kind use "dynamic";
16130 and the compilation command to build and install the library:
16132 @smallexample @c ada
16133 $ gnatmake -Pmy_lib
16137 It is not entirely trivial to perform manually all the steps required to
16138 produce a library. We recommend that you use the GNAT Project Manager
16139 for this task. In special cases where this is not desired, the necessary
16140 steps are discussed below.
16142 There are various possibilities for compiling the units that make up the
16143 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16144 with a conventional script. For simple libraries, it is also possible to create
16145 a dummy main program which depends upon all the packages that comprise the
16146 interface of the library. This dummy main program can then be given to
16147 @command{gnatmake}, which will ensure that all necessary objects are built.
16149 After this task is accomplished, you should follow the standard procedure
16150 of the underlying operating system to produce the static or shared library.
16152 Here is an example of such a dummy program:
16153 @smallexample @c ada
16155 with My_Lib.Service1;
16156 with My_Lib.Service2;
16157 with My_Lib.Service3;
16158 procedure My_Lib_Dummy is
16166 Here are the generic commands that will build an archive or a shared library.
16169 # compiling the library
16170 $ gnatmake -c my_lib_dummy.adb
16172 # we don't need the dummy object itself
16173 $ rm my_lib_dummy.o my_lib_dummy.ali
16175 # create an archive with the remaining objects
16176 $ ar rc libmy_lib.a *.o
16177 # some systems may require "ranlib" to be run as well
16179 # or create a shared library
16180 $ gcc -shared -o libmy_lib.so *.o
16181 # some systems may require the code to have been compiled with -fPIC
16183 # remove the object files that are now in the library
16186 # Make the ALI files read-only so that gnatmake will not try to
16187 # regenerate the objects that are in the library
16192 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16193 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16194 be accessed by the directive @option{-l@var{xxx}} at link time.
16196 @node Installing a library
16197 @subsection Installing a library
16198 @cindex @code{ADA_PROJECT_PATH}
16199 @cindex @code{GPR_PROJECT_PATH}
16202 If you use project files, library installation is part of the library build
16203 process (@pxref{Installing a library with project files}).
16205 When project files are not an option, it is also possible, but not recommended,
16206 to install the library so that the sources needed to use the library are on the
16207 Ada source path and the ALI files & libraries be on the Ada Object path (see
16208 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16209 administrator can place general-purpose libraries in the default compiler
16210 paths, by specifying the libraries' location in the configuration files
16211 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16212 must be located in the GNAT installation tree at the same place as the gcc spec
16213 file. The location of the gcc spec file can be determined as follows:
16219 The configuration files mentioned above have a simple format: each line
16220 must contain one unique directory name.
16221 Those names are added to the corresponding path
16222 in their order of appearance in the file. The names can be either absolute
16223 or relative; in the latter case, they are relative to where theses files
16226 The files @file{ada_source_path} and @file{ada_object_path} might not be
16228 GNAT installation, in which case, GNAT will look for its run-time library in
16229 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16230 objects and @file{ALI} files). When the files exist, the compiler does not
16231 look in @file{adainclude} and @file{adalib}, and thus the
16232 @file{ada_source_path} file
16233 must contain the location for the GNAT run-time sources (which can simply
16234 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16235 contain the location for the GNAT run-time objects (which can simply
16238 You can also specify a new default path to the run-time library at compilation
16239 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16240 the run-time library you want your program to be compiled with. This switch is
16241 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16242 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16244 It is possible to install a library before or after the standard GNAT
16245 library, by reordering the lines in the configuration files. In general, a
16246 library must be installed before the GNAT library if it redefines
16249 @node Using a library
16250 @subsection Using a library
16252 @noindent Once again, the project facility greatly simplifies the use of
16253 libraries. In this context, using a library is just a matter of adding a
16254 @code{with} clause in the user project. For instance, to make use of the
16255 library @code{My_Lib} shown in examples in earlier sections, you can
16258 @smallexample @c projectfile
16265 Even if you have a third-party, non-Ada library, you can still use GNAT's
16266 Project Manager facility to provide a wrapper for it. For example, the
16267 following project, when @code{with}ed by your main project, will link with the
16268 third-party library @file{liba.a}:
16270 @smallexample @c projectfile
16273 for Externally_Built use "true";
16274 for Source_Files use ();
16275 for Library_Dir use "lib";
16276 for Library_Name use "a";
16277 for Library_Kind use "static";
16281 This is an alternative to the use of @code{pragma Linker_Options}. It is
16282 especially interesting in the context of systems with several interdependent
16283 static libraries where finding a proper linker order is not easy and best be
16284 left to the tools having visibility over project dependence information.
16287 In order to use an Ada library manually, you need to make sure that this
16288 library is on both your source and object path
16289 (see @ref{Search Paths and the Run-Time Library (RTL)}
16290 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16291 in an archive or a shared library, you need to specify the desired
16292 library at link time.
16294 For example, you can use the library @file{mylib} installed in
16295 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16298 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16303 This can be expressed more simply:
16308 when the following conditions are met:
16311 @file{/dir/my_lib_src} has been added by the user to the environment
16312 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16313 @file{ada_source_path}
16315 @file{/dir/my_lib_obj} has been added by the user to the environment
16316 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16317 @file{ada_object_path}
16319 a pragma @code{Linker_Options} has been added to one of the sources.
16322 @smallexample @c ada
16323 pragma Linker_Options ("-lmy_lib");
16327 @node Stand-alone Ada Libraries
16328 @section Stand-alone Ada Libraries
16329 @cindex Stand-alone library, building, using
16332 * Introduction to Stand-alone Libraries::
16333 * Building a Stand-alone Library::
16334 * Creating a Stand-alone Library to be used in a non-Ada context::
16335 * Restrictions in Stand-alone Libraries::
16338 @node Introduction to Stand-alone Libraries
16339 @subsection Introduction to Stand-alone Libraries
16342 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16344 elaborate the Ada units that are included in the library. In contrast with
16345 an ordinary library, which consists of all sources, objects and @file{ALI}
16347 library, a SAL may specify a restricted subset of compilation units
16348 to serve as a library interface. In this case, the fully
16349 self-sufficient set of files will normally consist of an objects
16350 archive, the sources of interface units' specs, and the @file{ALI}
16351 files of interface units.
16352 If an interface spec contains a generic unit or an inlined subprogram,
16354 source must also be provided; if the units that must be provided in the source
16355 form depend on other units, the source and @file{ALI} files of those must
16358 The main purpose of a SAL is to minimize the recompilation overhead of client
16359 applications when a new version of the library is installed. Specifically,
16360 if the interface sources have not changed, client applications do not need to
16361 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16362 version, controlled by @code{Library_Version} attribute, is not changed,
16363 then the clients do not need to be relinked.
16365 SALs also allow the library providers to minimize the amount of library source
16366 text exposed to the clients. Such ``information hiding'' might be useful or
16367 necessary for various reasons.
16369 Stand-alone libraries are also well suited to be used in an executable whose
16370 main routine is not written in Ada.
16372 @node Building a Stand-alone Library
16373 @subsection Building a Stand-alone Library
16376 GNAT's Project facility provides a simple way of building and installing
16377 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16378 To be a Stand-alone Library Project, in addition to the two attributes
16379 that make a project a Library Project (@code{Library_Name} and
16380 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16381 @code{Library_Interface} must be defined. For example:
16383 @smallexample @c projectfile
16385 for Library_Dir use "lib_dir";
16386 for Library_Name use "dummy";
16387 for Library_Interface use ("int1", "int1.child");
16392 Attribute @code{Library_Interface} has a non-empty string list value,
16393 each string in the list designating a unit contained in an immediate source
16394 of the project file.
16396 When a Stand-alone Library is built, first the binder is invoked to build
16397 a package whose name depends on the library name
16398 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16399 This binder-generated package includes initialization and
16400 finalization procedures whose
16401 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16403 above). The object corresponding to this package is included in the library.
16405 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16406 calling of these procedures if a static SAL is built, or if a shared SAL
16408 with the project-level attribute @code{Library_Auto_Init} set to
16411 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16412 (those that are listed in attribute @code{Library_Interface}) are copied to
16413 the Library Directory. As a consequence, only the Interface Units may be
16414 imported from Ada units outside of the library. If other units are imported,
16415 the binding phase will fail.
16418 It is also possible to build an encapsulated library where not only
16419 the code to elaborate and finalize the library is embedded but also
16420 ensuring that the library is linked only against static
16421 libraries. So an encapsulated library only depends on system
16422 libraries, all other code, including the GNAT runtime, is embedded. To
16423 build an encapsulated library the attribute
16424 @code{Library_Standalone} must be set to @code{encapsulated}:
16426 @smallexample @c projectfile
16428 for Library_Dir use "lib_dir";
16429 for Library_Name use "dummy";
16430 for Library_Interface use ("int1", "int1.child");
16431 for Library_Standalone use "encapsulated";
16436 The default value for this attribute is @code{standard} in which case
16437 a stand-alone library is built.
16439 The attribute @code{Library_Src_Dir} may be specified for a
16440 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16441 single string value. Its value must be the path (absolute or relative to the
16442 project directory) of an existing directory. This directory cannot be the
16443 object directory or one of the source directories, but it can be the same as
16444 the library directory. The sources of the Interface
16445 Units of the library that are needed by an Ada client of the library will be
16446 copied to the designated directory, called the Interface Copy directory.
16447 These sources include the specs of the Interface Units, but they may also
16448 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16449 are used, or when there is a generic unit in the spec. Before the sources
16450 are copied to the Interface Copy directory, an attempt is made to delete all
16451 files in the Interface Copy directory.
16453 Building stand-alone libraries by hand is somewhat tedious, but for those
16454 occasions when it is necessary here are the steps that you need to perform:
16457 Compile all library sources.
16460 Invoke the binder with the switch @option{-n} (No Ada main program),
16461 with all the @file{ALI} files of the interfaces, and
16462 with the switch @option{-L} to give specific names to the @code{init}
16463 and @code{final} procedures. For example:
16465 gnatbind -n int1.ali int2.ali -Lsal1
16469 Compile the binder generated file:
16475 Link the dynamic library with all the necessary object files,
16476 indicating to the linker the names of the @code{init} (and possibly
16477 @code{final}) procedures for automatic initialization (and finalization).
16478 The built library should be placed in a directory different from
16479 the object directory.
16482 Copy the @code{ALI} files of the interface to the library directory,
16483 add in this copy an indication that it is an interface to a SAL
16484 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16485 with letter ``P'') and make the modified copy of the @file{ALI} file
16490 Using SALs is not different from using other libraries
16491 (see @ref{Using a library}).
16493 @node Creating a Stand-alone Library to be used in a non-Ada context
16494 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16497 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16500 The only extra step required is to ensure that library interface subprograms
16501 are compatible with the main program, by means of @code{pragma Export}
16502 or @code{pragma Convention}.
16504 Here is an example of simple library interface for use with C main program:
16506 @smallexample @c ada
16507 package My_Package is
16509 procedure Do_Something;
16510 pragma Export (C, Do_Something, "do_something");
16512 procedure Do_Something_Else;
16513 pragma Export (C, Do_Something_Else, "do_something_else");
16519 On the foreign language side, you must provide a ``foreign'' view of the
16520 library interface; remember that it should contain elaboration routines in
16521 addition to interface subprograms.
16523 The example below shows the content of @code{mylib_interface.h} (note
16524 that there is no rule for the naming of this file, any name can be used)
16526 /* the library elaboration procedure */
16527 extern void mylibinit (void);
16529 /* the library finalization procedure */
16530 extern void mylibfinal (void);
16532 /* the interface exported by the library */
16533 extern void do_something (void);
16534 extern void do_something_else (void);
16538 Libraries built as explained above can be used from any program, provided
16539 that the elaboration procedures (named @code{mylibinit} in the previous
16540 example) are called before the library services are used. Any number of
16541 libraries can be used simultaneously, as long as the elaboration
16542 procedure of each library is called.
16544 Below is an example of a C program that uses the @code{mylib} library.
16547 #include "mylib_interface.h"
16552 /* First, elaborate the library before using it */
16555 /* Main program, using the library exported entities */
16557 do_something_else ();
16559 /* Library finalization at the end of the program */
16566 Note that invoking any library finalization procedure generated by
16567 @code{gnatbind} shuts down the Ada run-time environment.
16569 finalization of all Ada libraries must be performed at the end of the program.
16570 No call to these libraries or to the Ada run-time library should be made
16571 after the finalization phase.
16573 @node Restrictions in Stand-alone Libraries
16574 @subsection Restrictions in Stand-alone Libraries
16577 The pragmas listed below should be used with caution inside libraries,
16578 as they can create incompatibilities with other Ada libraries:
16580 @item pragma @code{Locking_Policy}
16581 @item pragma @code{Queuing_Policy}
16582 @item pragma @code{Task_Dispatching_Policy}
16583 @item pragma @code{Unreserve_All_Interrupts}
16587 When using a library that contains such pragmas, the user must make sure
16588 that all libraries use the same pragmas with the same values. Otherwise,
16589 @code{Program_Error} will
16590 be raised during the elaboration of the conflicting
16591 libraries. The usage of these pragmas and its consequences for the user
16592 should therefore be well documented.
16594 Similarly, the traceback in the exception occurrence mechanism should be
16595 enabled or disabled in a consistent manner across all libraries.
16596 Otherwise, Program_Error will be raised during the elaboration of the
16597 conflicting libraries.
16599 If the @code{Version} or @code{Body_Version}
16600 attributes are used inside a library, then you need to
16601 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16602 libraries, so that version identifiers can be properly computed.
16603 In practice these attributes are rarely used, so this is unlikely
16604 to be a consideration.
16606 @node Rebuilding the GNAT Run-Time Library
16607 @section Rebuilding the GNAT Run-Time Library
16608 @cindex GNAT Run-Time Library, rebuilding
16609 @cindex Building the GNAT Run-Time Library
16610 @cindex Rebuilding the GNAT Run-Time Library
16611 @cindex Run-Time Library, rebuilding
16614 It may be useful to recompile the GNAT library in various contexts, the
16615 most important one being the use of partition-wide configuration pragmas
16616 such as @code{Normalize_Scalars}. A special Makefile called
16617 @code{Makefile.adalib} is provided to that effect and can be found in
16618 the directory containing the GNAT library. The location of this
16619 directory depends on the way the GNAT environment has been installed and can
16620 be determined by means of the command:
16627 The last entry in the object search path usually contains the
16628 gnat library. This Makefile contains its own documentation and in
16629 particular the set of instructions needed to rebuild a new library and
16632 @node Using the GNU make Utility
16633 @chapter Using the GNU @code{make} Utility
16637 This chapter offers some examples of makefiles that solve specific
16638 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16639 make, make, GNU @code{make}}), nor does it try to replace the
16640 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16642 All the examples in this section are specific to the GNU version of
16643 make. Although @command{make} is a standard utility, and the basic language
16644 is the same, these examples use some advanced features found only in
16648 * Using gnatmake in a Makefile::
16649 * Automatically Creating a List of Directories::
16650 * Generating the Command Line Switches::
16651 * Overcoming Command Line Length Limits::
16654 @node Using gnatmake in a Makefile
16655 @section Using gnatmake in a Makefile
16660 Complex project organizations can be handled in a very powerful way by
16661 using GNU make combined with gnatmake. For instance, here is a Makefile
16662 which allows you to build each subsystem of a big project into a separate
16663 shared library. Such a makefile allows you to significantly reduce the link
16664 time of very big applications while maintaining full coherence at
16665 each step of the build process.
16667 The list of dependencies are handled automatically by
16668 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16669 the appropriate directories.
16671 Note that you should also read the example on how to automatically
16672 create the list of directories
16673 (@pxref{Automatically Creating a List of Directories})
16674 which might help you in case your project has a lot of subdirectories.
16679 @font@heightrm=cmr8
16682 ## This Makefile is intended to be used with the following directory
16684 ## - The sources are split into a series of csc (computer software components)
16685 ## Each of these csc is put in its own directory.
16686 ## Their name are referenced by the directory names.
16687 ## They will be compiled into shared library (although this would also work
16688 ## with static libraries
16689 ## - The main program (and possibly other packages that do not belong to any
16690 ## csc is put in the top level directory (where the Makefile is).
16691 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16692 ## \_ second_csc (sources) __ lib (will contain the library)
16694 ## Although this Makefile is build for shared library, it is easy to modify
16695 ## to build partial link objects instead (modify the lines with -shared and
16698 ## With this makefile, you can change any file in the system or add any new
16699 ## file, and everything will be recompiled correctly (only the relevant shared
16700 ## objects will be recompiled, and the main program will be re-linked).
16702 # The list of computer software component for your project. This might be
16703 # generated automatically.
16706 # Name of the main program (no extension)
16709 # If we need to build objects with -fPIC, uncomment the following line
16712 # The following variable should give the directory containing libgnat.so
16713 # You can get this directory through 'gnatls -v'. This is usually the last
16714 # directory in the Object_Path.
16717 # The directories for the libraries
16718 # (This macro expands the list of CSC to the list of shared libraries, you
16719 # could simply use the expanded form:
16720 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16721 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16723 $@{MAIN@}: objects $@{LIB_DIR@}
16724 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16725 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16728 # recompile the sources
16729 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16731 # Note: In a future version of GNAT, the following commands will be simplified
16732 # by a new tool, gnatmlib
16734 mkdir -p $@{dir $@@ @}
16735 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16736 cd $@{dir $@@ @} && cp -f ../*.ali .
16738 # The dependencies for the modules
16739 # Note that we have to force the expansion of *.o, since in some cases
16740 # make won't be able to do it itself.
16741 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16742 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16743 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16745 # Make sure all of the shared libraries are in the path before starting the
16748 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16751 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16752 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16753 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16754 $@{RM@} *.o *.ali $@{MAIN@}
16757 @node Automatically Creating a List of Directories
16758 @section Automatically Creating a List of Directories
16761 In most makefiles, you will have to specify a list of directories, and
16762 store it in a variable. For small projects, it is often easier to
16763 specify each of them by hand, since you then have full control over what
16764 is the proper order for these directories, which ones should be
16767 However, in larger projects, which might involve hundreds of
16768 subdirectories, it might be more convenient to generate this list
16771 The example below presents two methods. The first one, although less
16772 general, gives you more control over the list. It involves wildcard
16773 characters, that are automatically expanded by @command{make}. Its
16774 shortcoming is that you need to explicitly specify some of the
16775 organization of your project, such as for instance the directory tree
16776 depth, whether some directories are found in a separate tree, @enddots{}
16778 The second method is the most general one. It requires an external
16779 program, called @command{find}, which is standard on all Unix systems. All
16780 the directories found under a given root directory will be added to the
16786 @font@heightrm=cmr8
16789 # The examples below are based on the following directory hierarchy:
16790 # All the directories can contain any number of files
16791 # ROOT_DIRECTORY -> a -> aa -> aaa
16794 # -> b -> ba -> baa
16797 # This Makefile creates a variable called DIRS, that can be reused any time
16798 # you need this list (see the other examples in this section)
16800 # The root of your project's directory hierarchy
16804 # First method: specify explicitly the list of directories
16805 # This allows you to specify any subset of all the directories you need.
16808 DIRS := a/aa/ a/ab/ b/ba/
16811 # Second method: use wildcards
16812 # Note that the argument(s) to wildcard below should end with a '/'.
16813 # Since wildcards also return file names, we have to filter them out
16814 # to avoid duplicate directory names.
16815 # We thus use make's @code{dir} and @code{sort} functions.
16816 # It sets DIRs to the following value (note that the directories aaa and baa
16817 # are not given, unless you change the arguments to wildcard).
16818 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16821 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16822 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16825 # Third method: use an external program
16826 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16827 # This is the most complete command: it sets DIRs to the following value:
16828 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16831 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16835 @node Generating the Command Line Switches
16836 @section Generating the Command Line Switches
16839 Once you have created the list of directories as explained in the
16840 previous section (@pxref{Automatically Creating a List of Directories}),
16841 you can easily generate the command line arguments to pass to gnatmake.
16843 For the sake of completeness, this example assumes that the source path
16844 is not the same as the object path, and that you have two separate lists
16848 # see "Automatically creating a list of directories" to create
16853 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16854 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16857 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16860 @node Overcoming Command Line Length Limits
16861 @section Overcoming Command Line Length Limits
16864 One problem that might be encountered on big projects is that many
16865 operating systems limit the length of the command line. It is thus hard to give
16866 gnatmake the list of source and object directories.
16868 This example shows how you can set up environment variables, which will
16869 make @command{gnatmake} behave exactly as if the directories had been
16870 specified on the command line, but have a much higher length limit (or
16871 even none on most systems).
16873 It assumes that you have created a list of directories in your Makefile,
16874 using one of the methods presented in
16875 @ref{Automatically Creating a List of Directories}.
16876 For the sake of completeness, we assume that the object
16877 path (where the ALI files are found) is different from the sources patch.
16879 Note a small trick in the Makefile below: for efficiency reasons, we
16880 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16881 expanded immediately by @code{make}. This way we overcome the standard
16882 make behavior which is to expand the variables only when they are
16885 On Windows, if you are using the standard Windows command shell, you must
16886 replace colons with semicolons in the assignments to these variables.
16891 @font@heightrm=cmr8
16894 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16895 # This is the same thing as putting the -I arguments on the command line.
16896 # (the equivalent of using -aI on the command line would be to define
16897 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16898 # You can of course have different values for these variables.
16900 # Note also that we need to keep the previous values of these variables, since
16901 # they might have been set before running 'make' to specify where the GNAT
16902 # library is installed.
16904 # see "Automatically creating a list of directories" to create these
16910 space:=$@{empty@} $@{empty@}
16911 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16912 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16913 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16914 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16915 export ADA_INCLUDE_PATH
16916 export ADA_OBJECTS_PATH
16923 @node Memory Management Issues
16924 @chapter Memory Management Issues
16927 This chapter describes some useful memory pools provided in the GNAT library
16928 and in particular the GNAT Debug Pool facility, which can be used to detect
16929 incorrect uses of access values (including ``dangling references'').
16931 It also describes the @command{gnatmem} tool, which can be used to track down
16936 * Some Useful Memory Pools::
16937 * The GNAT Debug Pool Facility::
16939 * The gnatmem Tool::
16943 @node Some Useful Memory Pools
16944 @section Some Useful Memory Pools
16945 @findex Memory Pool
16946 @cindex storage, pool
16949 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16950 storage pool. Allocations use the standard system call @code{malloc} while
16951 deallocations use the standard system call @code{free}. No reclamation is
16952 performed when the pool goes out of scope. For performance reasons, the
16953 standard default Ada allocators/deallocators do not use any explicit storage
16954 pools but if they did, they could use this storage pool without any change in
16955 behavior. That is why this storage pool is used when the user
16956 manages to make the default implicit allocator explicit as in this example:
16957 @smallexample @c ada
16958 type T1 is access Something;
16959 -- no Storage pool is defined for T2
16960 type T2 is access Something_Else;
16961 for T2'Storage_Pool use T1'Storage_Pool;
16962 -- the above is equivalent to
16963 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16967 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16968 pool. The allocation strategy is similar to @code{Pool_Local}'s
16969 except that the all
16970 storage allocated with this pool is reclaimed when the pool object goes out of
16971 scope. This pool provides a explicit mechanism similar to the implicit one
16972 provided by several Ada 83 compilers for allocations performed through a local
16973 access type and whose purpose was to reclaim memory when exiting the
16974 scope of a given local access. As an example, the following program does not
16975 leak memory even though it does not perform explicit deallocation:
16977 @smallexample @c ada
16978 with System.Pool_Local;
16979 procedure Pooloc1 is
16980 procedure Internal is
16981 type A is access Integer;
16982 X : System.Pool_Local.Unbounded_Reclaim_Pool;
16983 for A'Storage_Pool use X;
16986 for I in 1 .. 50 loop
16991 for I in 1 .. 100 loop
16998 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16999 @code{Storage_Size} is specified for an access type.
17000 The whole storage for the pool is
17001 allocated at once, usually on the stack at the point where the access type is
17002 elaborated. It is automatically reclaimed when exiting the scope where the
17003 access type is defined. This package is not intended to be used directly by the
17004 user and it is implicitly used for each such declaration:
17006 @smallexample @c ada
17007 type T1 is access Something;
17008 for T1'Storage_Size use 10_000;
17011 @node The GNAT Debug Pool Facility
17012 @section The GNAT Debug Pool Facility
17014 @cindex storage, pool, memory corruption
17017 The use of unchecked deallocation and unchecked conversion can easily
17018 lead to incorrect memory references. The problems generated by such
17019 references are usually difficult to tackle because the symptoms can be
17020 very remote from the origin of the problem. In such cases, it is
17021 very helpful to detect the problem as early as possible. This is the
17022 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17024 In order to use the GNAT specific debugging pool, the user must
17025 associate a debug pool object with each of the access types that may be
17026 related to suspected memory problems. See Ada Reference Manual 13.11.
17027 @smallexample @c ada
17028 type Ptr is access Some_Type;
17029 Pool : GNAT.Debug_Pools.Debug_Pool;
17030 for Ptr'Storage_Pool use Pool;
17034 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17035 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17036 allow the user to redefine allocation and deallocation strategies. They
17037 also provide a checkpoint for each dereference, through the use of
17038 the primitive operation @code{Dereference} which is implicitly called at
17039 each dereference of an access value.
17041 Once an access type has been associated with a debug pool, operations on
17042 values of the type may raise four distinct exceptions,
17043 which correspond to four potential kinds of memory corruption:
17046 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17048 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17050 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17052 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17056 For types associated with a Debug_Pool, dynamic allocation is performed using
17057 the standard GNAT allocation routine. References to all allocated chunks of
17058 memory are kept in an internal dictionary. Several deallocation strategies are
17059 provided, whereupon the user can choose to release the memory to the system,
17060 keep it allocated for further invalid access checks, or fill it with an easily
17061 recognizable pattern for debug sessions. The memory pattern is the old IBM
17062 hexadecimal convention: @code{16#DEADBEEF#}.
17064 See the documentation in the file g-debpoo.ads for more information on the
17065 various strategies.
17067 Upon each dereference, a check is made that the access value denotes a
17068 properly allocated memory location. Here is a complete example of use of
17069 @code{Debug_Pools}, that includes typical instances of memory corruption:
17070 @smallexample @c ada
17074 with Gnat.Io; use Gnat.Io;
17075 with Unchecked_Deallocation;
17076 with Unchecked_Conversion;
17077 with GNAT.Debug_Pools;
17078 with System.Storage_Elements;
17079 with Ada.Exceptions; use Ada.Exceptions;
17080 procedure Debug_Pool_Test is
17082 type T is access Integer;
17083 type U is access all T;
17085 P : GNAT.Debug_Pools.Debug_Pool;
17086 for T'Storage_Pool use P;
17088 procedure Free is new Unchecked_Deallocation (Integer, T);
17089 function UC is new Unchecked_Conversion (U, T);
17092 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17102 Put_Line (Integer'Image(B.all));
17104 when E : others => Put_Line ("raised: " & Exception_Name (E));
17109 when E : others => Put_Line ("raised: " & Exception_Name (E));
17113 Put_Line (Integer'Image(B.all));
17115 when E : others => Put_Line ("raised: " & Exception_Name (E));
17120 when E : others => Put_Line ("raised: " & Exception_Name (E));
17123 end Debug_Pool_Test;
17127 The debug pool mechanism provides the following precise diagnostics on the
17128 execution of this erroneous program:
17131 Total allocated bytes : 0
17132 Total deallocated bytes : 0
17133 Current Water Mark: 0
17137 Total allocated bytes : 8
17138 Total deallocated bytes : 0
17139 Current Water Mark: 8
17142 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17143 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17144 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17145 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17147 Total allocated bytes : 8
17148 Total deallocated bytes : 4
17149 Current Water Mark: 4
17154 @node The gnatmem Tool
17155 @section The @command{gnatmem} Tool
17159 The @code{gnatmem} utility monitors dynamic allocation and
17160 deallocation activity in a program, and displays information about
17161 incorrect deallocations and possible sources of memory leaks.
17162 It is designed to work in association with a static runtime library
17163 only and in this context provides three types of information:
17166 General information concerning memory management, such as the total
17167 number of allocations and deallocations, the amount of allocated
17168 memory and the high water mark, i.e.@: the largest amount of allocated
17169 memory in the course of program execution.
17172 Backtraces for all incorrect deallocations, that is to say deallocations
17173 which do not correspond to a valid allocation.
17176 Information on each allocation that is potentially the origin of a memory
17181 * Running gnatmem::
17182 * Switches for gnatmem::
17183 * Example of gnatmem Usage::
17186 @node Running gnatmem
17187 @subsection Running @code{gnatmem}
17190 @code{gnatmem} makes use of the output created by the special version of
17191 allocation and deallocation routines that record call information. This
17192 allows to obtain accurate dynamic memory usage history at a minimal cost to
17193 the execution speed. Note however, that @code{gnatmem} is not supported on
17194 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17195 Solaris and Windows NT/2000/XP (x86).
17198 The @code{gnatmem} command has the form
17201 @c $ gnatmem @ovar{switches} user_program
17202 @c Expanding @ovar macro inline (explanation in macro def comments)
17203 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17207 The program must have been linked with the instrumented version of the
17208 allocation and deallocation routines. This is done by linking with the
17209 @file{libgmem.a} library. For correct symbolic backtrace information,
17210 the user program should be compiled with debugging options
17211 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17214 $ gnatmake -g my_program -largs -lgmem
17218 As library @file{libgmem.a} contains an alternate body for package
17219 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17220 when an executable is linked with library @file{libgmem.a}. It is then not
17221 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17224 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17225 This file contains information about all allocations and deallocations
17226 performed by the program. It is produced by the instrumented allocations and
17227 deallocations routines and will be used by @code{gnatmem}.
17229 In order to produce symbolic backtrace information for allocations and
17230 deallocations performed by the GNAT run-time library, you need to use a
17231 version of that library that has been compiled with the @option{-g} switch
17232 (see @ref{Rebuilding the GNAT Run-Time Library}).
17234 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17235 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17236 @option{-i} switch, gnatmem will assume that this file can be found in the
17237 current directory. For example, after you have executed @file{my_program},
17238 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17241 $ gnatmem my_program
17245 This will produce the output with the following format:
17247 *************** debut cc
17249 $ gnatmem my_program
17253 Total number of allocations : 45
17254 Total number of deallocations : 6
17255 Final Water Mark (non freed mem) : 11.29 Kilobytes
17256 High Water Mark : 11.40 Kilobytes
17261 Allocation Root # 2
17262 -------------------
17263 Number of non freed allocations : 11
17264 Final Water Mark (non freed mem) : 1.16 Kilobytes
17265 High Water Mark : 1.27 Kilobytes
17267 my_program.adb:23 my_program.alloc
17273 The first block of output gives general information. In this case, the
17274 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17275 Unchecked_Deallocation routine occurred.
17278 Subsequent paragraphs display information on all allocation roots.
17279 An allocation root is a specific point in the execution of the program
17280 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17281 construct. This root is represented by an execution backtrace (or subprogram
17282 call stack). By default the backtrace depth for allocations roots is 1, so
17283 that a root corresponds exactly to a source location. The backtrace can
17284 be made deeper, to make the root more specific.
17286 @node Switches for gnatmem
17287 @subsection Switches for @code{gnatmem}
17290 @code{gnatmem} recognizes the following switches:
17295 @cindex @option{-q} (@code{gnatmem})
17296 Quiet. Gives the minimum output needed to identify the origin of the
17297 memory leaks. Omits statistical information.
17300 @cindex @var{N} (@code{gnatmem})
17301 N is an integer literal (usually between 1 and 10) which controls the
17302 depth of the backtraces defining allocation root. The default value for
17303 N is 1. The deeper the backtrace, the more precise the localization of
17304 the root. Note that the total number of roots can depend on this
17305 parameter. This parameter must be specified @emph{before} the name of the
17306 executable to be analyzed, to avoid ambiguity.
17309 @cindex @option{-b} (@code{gnatmem})
17310 This switch has the same effect as just depth parameter.
17312 @item -i @var{file}
17313 @cindex @option{-i} (@code{gnatmem})
17314 Do the @code{gnatmem} processing starting from @file{file}, rather than
17315 @file{gmem.out} in the current directory.
17318 @cindex @option{-m} (@code{gnatmem})
17319 This switch causes @code{gnatmem} to mask the allocation roots that have less
17320 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17321 examine even the roots that didn't result in leaks.
17324 @cindex @option{-s} (@code{gnatmem})
17325 This switch causes @code{gnatmem} to sort the allocation roots according to the
17326 specified order of sort criteria, each identified by a single letter. The
17327 currently supported criteria are @code{n, h, w} standing respectively for
17328 number of unfreed allocations, high watermark, and final watermark
17329 corresponding to a specific root. The default order is @code{nwh}.
17333 @node Example of gnatmem Usage
17334 @subsection Example of @code{gnatmem} Usage
17337 The following example shows the use of @code{gnatmem}
17338 on a simple memory-leaking program.
17339 Suppose that we have the following Ada program:
17341 @smallexample @c ada
17344 with Unchecked_Deallocation;
17345 procedure Test_Gm is
17347 type T is array (1..1000) of Integer;
17348 type Ptr is access T;
17349 procedure Free is new Unchecked_Deallocation (T, Ptr);
17352 procedure My_Alloc is
17357 procedure My_DeAlloc is
17365 for I in 1 .. 5 loop
17366 for J in I .. 5 loop
17377 The program needs to be compiled with debugging option and linked with
17378 @code{gmem} library:
17381 $ gnatmake -g test_gm -largs -lgmem
17385 Then we execute the program as usual:
17392 Then @code{gnatmem} is invoked simply with
17398 which produces the following output (result may vary on different platforms):
17403 Total number of allocations : 18
17404 Total number of deallocations : 5
17405 Final Water Mark (non freed mem) : 53.00 Kilobytes
17406 High Water Mark : 56.90 Kilobytes
17408 Allocation Root # 1
17409 -------------------
17410 Number of non freed allocations : 11
17411 Final Water Mark (non freed mem) : 42.97 Kilobytes
17412 High Water Mark : 46.88 Kilobytes
17414 test_gm.adb:11 test_gm.my_alloc
17416 Allocation Root # 2
17417 -------------------
17418 Number of non freed allocations : 1
17419 Final Water Mark (non freed mem) : 10.02 Kilobytes
17420 High Water Mark : 10.02 Kilobytes
17422 s-secsta.adb:81 system.secondary_stack.ss_init
17424 Allocation Root # 3
17425 -------------------
17426 Number of non freed allocations : 1
17427 Final Water Mark (non freed mem) : 12 Bytes
17428 High Water Mark : 12 Bytes
17430 s-secsta.adb:181 system.secondary_stack.ss_init
17434 Note that the GNAT run time contains itself a certain number of
17435 allocations that have no corresponding deallocation,
17436 as shown here for root #2 and root
17437 #3. This is a normal behavior when the number of non-freed allocations
17438 is one, it allocates dynamic data structures that the run time needs for
17439 the complete lifetime of the program. Note also that there is only one
17440 allocation root in the user program with a single line back trace:
17441 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17442 program shows that 'My_Alloc' is called at 2 different points in the
17443 source (line 21 and line 24). If those two allocation roots need to be
17444 distinguished, the backtrace depth parameter can be used:
17447 $ gnatmem 3 test_gm
17451 which will give the following output:
17456 Total number of allocations : 18
17457 Total number of deallocations : 5
17458 Final Water Mark (non freed mem) : 53.00 Kilobytes
17459 High Water Mark : 56.90 Kilobytes
17461 Allocation Root # 1
17462 -------------------
17463 Number of non freed allocations : 10
17464 Final Water Mark (non freed mem) : 39.06 Kilobytes
17465 High Water Mark : 42.97 Kilobytes
17467 test_gm.adb:11 test_gm.my_alloc
17468 test_gm.adb:24 test_gm
17469 b_test_gm.c:52 main
17471 Allocation Root # 2
17472 -------------------
17473 Number of non freed allocations : 1
17474 Final Water Mark (non freed mem) : 10.02 Kilobytes
17475 High Water Mark : 10.02 Kilobytes
17477 s-secsta.adb:81 system.secondary_stack.ss_init
17478 s-secsta.adb:283 <system__secondary_stack___elabb>
17479 b_test_gm.c:33 adainit
17481 Allocation Root # 3
17482 -------------------
17483 Number of non freed allocations : 1
17484 Final Water Mark (non freed mem) : 3.91 Kilobytes
17485 High Water Mark : 3.91 Kilobytes
17487 test_gm.adb:11 test_gm.my_alloc
17488 test_gm.adb:21 test_gm
17489 b_test_gm.c:52 main
17491 Allocation Root # 4
17492 -------------------
17493 Number of non freed allocations : 1
17494 Final Water Mark (non freed mem) : 12 Bytes
17495 High Water Mark : 12 Bytes
17497 s-secsta.adb:181 system.secondary_stack.ss_init
17498 s-secsta.adb:283 <system__secondary_stack___elabb>
17499 b_test_gm.c:33 adainit
17503 The allocation root #1 of the first example has been split in 2 roots #1
17504 and #3 thanks to the more precise associated backtrace.
17508 @node Stack Related Facilities
17509 @chapter Stack Related Facilities
17512 This chapter describes some useful tools associated with stack
17513 checking and analysis. In
17514 particular, it deals with dynamic and static stack usage measurements.
17517 * Stack Overflow Checking::
17518 * Static Stack Usage Analysis::
17519 * Dynamic Stack Usage Analysis::
17522 @node Stack Overflow Checking
17523 @section Stack Overflow Checking
17524 @cindex Stack Overflow Checking
17525 @cindex -fstack-check
17528 For most operating systems, @command{gcc} does not perform stack overflow
17529 checking by default. This means that if the main environment task or
17530 some other task exceeds the available stack space, then unpredictable
17531 behavior will occur. Most native systems offer some level of protection by
17532 adding a guard page at the end of each task stack. This mechanism is usually
17533 not enough for dealing properly with stack overflow situations because
17534 a large local variable could ``jump'' above the guard page.
17535 Furthermore, when the
17536 guard page is hit, there may not be any space left on the stack for executing
17537 the exception propagation code. Enabling stack checking avoids
17540 To activate stack checking, compile all units with the gcc option
17541 @option{-fstack-check}. For example:
17544 gcc -c -fstack-check package1.adb
17548 Units compiled with this option will generate extra instructions to check
17549 that any use of the stack (for procedure calls or for declaring local
17550 variables in declare blocks) does not exceed the available stack space.
17551 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17553 For declared tasks, the stack size is controlled by the size
17554 given in an applicable @code{Storage_Size} pragma or by the value specified
17555 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17556 the default size as defined in the GNAT runtime otherwise.
17558 For the environment task, the stack size depends on
17559 system defaults and is unknown to the compiler. Stack checking
17560 may still work correctly if a fixed
17561 size stack is allocated, but this cannot be guaranteed.
17563 To ensure that a clean exception is signalled for stack
17564 overflow, set the environment variable
17565 @env{GNAT_STACK_LIMIT} to indicate the maximum
17566 stack area that can be used, as in:
17567 @cindex GNAT_STACK_LIMIT
17570 SET GNAT_STACK_LIMIT 1600
17574 The limit is given in kilobytes, so the above declaration would
17575 set the stack limit of the environment task to 1.6 megabytes.
17576 Note that the only purpose of this usage is to limit the amount
17577 of stack used by the environment task. If it is necessary to
17578 increase the amount of stack for the environment task, then this
17579 is an operating systems issue, and must be addressed with the
17580 appropriate operating systems commands.
17583 To have a fixed size stack in the environment task, the stack must be put
17584 in the P0 address space and its size specified. Use these switches to
17588 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17592 The quotes are required to keep case. The number after @samp{STACK=} is the
17593 size of the environmental task stack in pagelets (512 bytes). In this example
17594 the stack size is about 2 megabytes.
17597 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17598 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
17599 more details about the @option{/p0image} qualifier and the @option{stack}
17603 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17604 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17605 stack in kilobytes. For example:
17608 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17612 @node Static Stack Usage Analysis
17613 @section Static Stack Usage Analysis
17614 @cindex Static Stack Usage Analysis
17615 @cindex -fstack-usage
17618 A unit compiled with @option{-fstack-usage} will generate an extra file
17620 the maximum amount of stack used, on a per-function basis.
17621 The file has the same
17622 basename as the target object file with a @file{.su} extension.
17623 Each line of this file is made up of three fields:
17627 The name of the function.
17631 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17634 The second field corresponds to the size of the known part of the function
17637 The qualifier @code{static} means that the function frame size
17639 It usually means that all local variables have a static size.
17640 In this case, the second field is a reliable measure of the function stack
17643 The qualifier @code{dynamic} means that the function frame size is not static.
17644 It happens mainly when some local variables have a dynamic size. When this
17645 qualifier appears alone, the second field is not a reliable measure
17646 of the function stack analysis. When it is qualified with @code{bounded}, it
17647 means that the second field is a reliable maximum of the function stack
17650 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17651 subprogram whose stack usage might be larger than the specified amount of
17652 bytes. The wording is in keeping with the qualifier documented above.
17654 @node Dynamic Stack Usage Analysis
17655 @section Dynamic Stack Usage Analysis
17658 It is possible to measure the maximum amount of stack used by a task, by
17659 adding a switch to @command{gnatbind}, as:
17662 $ gnatbind -u0 file
17666 With this option, at each task termination, its stack usage is output on
17668 It is not always convenient to output the stack usage when the program
17669 is still running. Hence, it is possible to delay this output until program
17670 termination. for a given number of tasks specified as the argument of the
17671 @option{-u} option. For instance:
17674 $ gnatbind -u100 file
17678 will buffer the stack usage information of the first 100 tasks to terminate and
17679 output this info at program termination. Results are displayed in four
17683 Index | Task Name | Stack Size | Stack Usage
17690 is a number associated with each task.
17693 is the name of the task analyzed.
17696 is the maximum size for the stack.
17699 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17700 is not entirely analyzed, and it's not possible to know exactly how
17701 much has actually been used.
17706 The environment task stack, e.g., the stack that contains the main unit, is
17707 only processed when the environment variable GNAT_STACK_LIMIT is set.
17710 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17711 stack usage reports at run-time. See its body for the details.
17713 @c *********************************
17715 @c *********************************
17716 @node Verifying Properties Using gnatcheck
17717 @chapter Verifying Properties Using @command{gnatcheck}
17719 @cindex @command{gnatcheck}
17722 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17723 of Ada source files according to a given set of semantic rules.
17726 In order to check compliance with a given rule, @command{gnatcheck} has to
17727 semantically analyze the Ada sources.
17728 Therefore, checks can only be performed on
17729 legal Ada units. Moreover, when a unit depends semantically upon units located
17730 outside the current directory, the source search path has to be provided when
17731 calling @command{gnatcheck}, either through a specified project file or
17732 through @command{gnatcheck} switches.
17734 For full details, refer to @cite{GNATcheck Reference Manual} document.
17737 @c *********************************
17738 @node Creating Sample Bodies Using gnatstub
17739 @chapter Creating Sample Bodies Using @command{gnatstub}
17743 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17744 for library unit declarations.
17746 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17747 driver (see @ref{The GNAT Driver and Project Files}).
17749 To create a body stub, @command{gnatstub} has to compile the library
17750 unit declaration. Therefore, bodies can be created only for legal
17751 library units. Moreover, if a library unit depends semantically upon
17752 units located outside the current directory, you have to provide
17753 the source search path when calling @command{gnatstub}, see the description
17754 of @command{gnatstub} switches below.
17756 By default, all the program unit body stubs generated by @code{gnatstub}
17757 raise the predefined @code{Program_Error} exception, which will catch
17758 accidental calls of generated stubs. This behavior can be changed with
17759 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17762 * Running gnatstub::
17763 * Switches for gnatstub::
17766 @node Running gnatstub
17767 @section Running @command{gnatstub}
17770 @command{gnatstub} has a command-line interface of the form:
17773 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17774 @c Expanding @ovar macro inline (explanation in macro def comments)
17775 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17782 is the name of the source file that contains a library unit declaration
17783 for which a body must be created. The file name may contain the path
17785 The file name does not have to follow the GNAT file name conventions. If the
17787 does not follow GNAT file naming conventions, the name of the body file must
17789 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17790 If the file name follows the GNAT file naming
17791 conventions and the name of the body file is not provided,
17794 of the body file from the argument file name by replacing the @file{.ads}
17796 with the @file{.adb} suffix.
17799 indicates the directory in which the body stub is to be placed (the default
17803 @item @samp{@var{gcc_switches}} is a list of switches for
17804 @command{gcc}. They will be passed on to all compiler invocations made by
17805 @command{gnatstub} to generate the ASIS trees. Here you can provide
17806 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17807 use the @option{-gnatec} switch to set the configuration file,
17808 use the @option{-gnat05} switch if sources should be compiled in
17812 is an optional sequence of switches as described in the next section
17815 @node Switches for gnatstub
17816 @section Switches for @command{gnatstub}
17822 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17823 If the destination directory already contains a file with the name of the
17825 for the argument spec file, replace it with the generated body stub.
17827 @item ^-hs^/HEADER=SPEC^
17828 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17829 Put the comment header (i.e., all the comments preceding the
17830 compilation unit) from the source of the library unit declaration
17831 into the body stub.
17833 @item ^-hg^/HEADER=GENERAL^
17834 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17835 Put a sample comment header into the body stub.
17837 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17838 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17839 Use the content of the file as the comment header for a generated body stub.
17843 @cindex @option{-IDIR} (@command{gnatstub})
17845 @cindex @option{-I-} (@command{gnatstub})
17848 @item /NOCURRENT_DIRECTORY
17849 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17851 ^These switches have ^This switch has^ the same meaning as in calls to
17853 ^They define ^It defines ^ the source search path in the call to
17854 @command{gcc} issued
17855 by @command{gnatstub} to compile an argument source file.
17857 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17858 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17859 This switch has the same meaning as in calls to @command{gcc}.
17860 It defines the additional configuration file to be passed to the call to
17861 @command{gcc} issued
17862 by @command{gnatstub} to compile an argument source file.
17864 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17865 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17866 (@var{n} is a non-negative integer). Set the maximum line length in the
17867 body stub to @var{n}; the default is 79. The maximum value that can be
17868 specified is 32767. Note that in the special case of configuration
17869 pragma files, the maximum is always 32767 regardless of whether or
17870 not this switch appears.
17872 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17873 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17874 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17875 the generated body sample to @var{n}.
17876 The default indentation is 3.
17878 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17879 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17880 Order local bodies alphabetically. (By default local bodies are ordered
17881 in the same way as the corresponding local specs in the argument spec file.)
17883 @item ^-i^/INDENTATION=^@var{n}
17884 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17885 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17887 @item ^-k^/TREE_FILE=SAVE^
17888 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17889 Do not remove the tree file (i.e., the snapshot of the compiler internal
17890 structures used by @command{gnatstub}) after creating the body stub.
17892 @item ^-l^/LINE_LENGTH=^@var{n}
17893 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17894 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17896 @item ^--no-exception^/NO_EXCEPTION^
17897 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17898 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17899 This is not always possible for function stubs.
17901 @item ^--no-local-header^/NO_LOCAL_HEADER^
17902 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17903 Do not place local comment header with unit name before body stub for a
17906 @item ^-o ^/BODY=^@var{body-name}
17907 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17908 Body file name. This should be set if the argument file name does not
17910 the GNAT file naming
17911 conventions. If this switch is omitted the default name for the body will be
17913 from the argument file name according to the GNAT file naming conventions.
17916 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17917 Quiet mode: do not generate a confirmation when a body is
17918 successfully created, and do not generate a message when a body is not
17922 @item ^-r^/TREE_FILE=REUSE^
17923 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17924 Reuse the tree file (if it exists) instead of creating it. Instead of
17925 creating the tree file for the library unit declaration, @command{gnatstub}
17926 tries to find it in the current directory and use it for creating
17927 a body. If the tree file is not found, no body is created. This option
17928 also implies @option{^-k^/SAVE^}, whether or not
17929 the latter is set explicitly.
17931 @item ^-t^/TREE_FILE=OVERWRITE^
17932 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17933 Overwrite the existing tree file. If the current directory already
17934 contains the file which, according to the GNAT file naming rules should
17935 be considered as a tree file for the argument source file,
17937 will refuse to create the tree file needed to create a sample body
17938 unless this option is set.
17940 @item ^-v^/VERBOSE^
17941 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17942 Verbose mode: generate version information.
17946 @c *********************************
17947 @node Creating Unit Tests Using gnattest
17948 @chapter Creating Unit Tests Using @command{gnattest}
17952 @command{gnattest} is an ASIS-based utility that creates unit-test stubs
17953 as well as a test driver infrastructure (harness). @command{gnattest} creates
17954 a stub for each visible subprogram in the packages under consideration when
17955 they do not exist already.
17957 In order to process source files from a project, @command{gnattest} has to
17958 semantically analyze the sources. Therefore, test stubs can only be
17959 generated for legal Ada units. If a unit is dependent on other units,
17960 those units should be among the source files of the project or of other projects
17961 imported by this one.
17963 Generated stubs and harnesses are based on the AUnit testing framework. AUnit is
17964 an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit for Java
17965 or CppUnit for C++. While it is advised that gnattest users read the AUnit
17966 manual, deep knowledge of AUnit is not necessary for using gnattest. For correct
17967 operation of @command{gnattest}, AUnit should be installed and aunit.gpr must be
17968 on the project path. This happens automatically when Aunit is installed at its
17971 * Running gnattest::
17972 * Switches for gnattest::
17973 * Project Attributes for gnattest::
17975 * Setting Up and Tearing Down the Testing Environment::
17976 * Regenerating Tests::
17977 * Default Test Behavior::
17978 * Testing Primitive Operations of Tagged Types::
17979 * Testing Inheritance::
17980 * Tagged Types Substitutability Testing::
17981 * Testing with Contracts::
17982 * Additional Tests::
17983 * Current Limitations::
17986 @node Running gnattest
17987 @section Running @command{gnattest}
17990 @command{gnattest} has a command-line interface of the form
17993 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
17994 @c Expanding @ovar macro inline (explanation in macro def comments)
17995 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18003 specifies the project defining the location of source files. When no
18004 file names are provided on the command line, all sources in the project
18005 are used as input. This switch is required.
18007 @item --harness-dir=dirname
18008 specifies the directory that will hold the harness packages and project file
18009 for the test driver. The harness directory should be specified either by that
18010 switch or by the corresponding attribute in the project file.
18013 is the name of the source file containing the library unit package declaration
18014 for which a test package will be created. The file name may be given with a
18017 @item @samp{@var{gcc_switches}}
18018 is a list of switches for
18019 @command{gcc}. These switches will be passed on to all compiler invocations
18020 made by @command{gnatstub} to generate a set of ASIS trees. Here you can provide
18021 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18022 use the @option{-gnatec} switch to set the configuration file,
18023 use the @option{-gnat05} switch if sources should be compiled in
18024 Ada 2005 mode, etc.
18027 is an optional sequence of switches as described in the next section.
18031 @command{gnattest} results can be found in two different places.
18034 @item automatic harness:
18035 the harness code, which is located either in the harness-dir as specified on
18036 the command line or in the project file. All of this code is generated
18037 completely automatically and can be destroyed and regenerated at will. It is not
18038 recommended to modify this code manually, since it could easily be overridden
18039 by mistake. The entry point in the harness code is the project file named
18040 @command{test_driver.gpr}. Tests can be compiled and run using a command
18044 gnatmake -P<harness-dir>/test_driver
18048 Note that you might need to specify the necessary values of scenario variables
18049 when you are not using the AUnit defaults.
18051 @item actual unit test stubs:
18052 a test stub for each visible subprogram is created in a separate file, if it
18053 doesn't exist already. By default, those separate test files are located in a
18054 "tests" directory that is created in the directory containing the source file
18055 itself. If it is not appropriate to create the tests in subdirectories of the
18056 source, option @option{--separate-root} can be used. For example, if a source
18057 file my_unit.ads in directory src contains a visible subprogram Proc, then
18058 the corresponding unit test will be found in file
18059 src/tests/my_unit-tests-proc_<code>.adb. <code> is a signature encoding used to
18060 differentiate test names in case of overloading.
18062 Note that if the project already has both my_unit.ads and my_unit-tests.ads,
18063 this will cause a name conflict with the generated test package.
18066 @node Switches for gnattest
18067 @section Switches for @command{gnattest}
18072 @item --harness-only
18073 @cindex @option{--harness-only} (@command{gnattest})
18074 When this option is given, @command{gnattest} creates a harness for all
18075 sources, treating them as test packages.
18077 @item --additional-tests=@var{projname}
18078 @cindex @option{--additional-tests} (@command{gnattest})
18079 Sources described in @var{projname} are considered potential additional
18080 manual tests to be added to the test suite.
18083 @cindex @option{-r} (@command{gnattest})
18084 Recursively consider all sources from all projects.
18086 @item -X@var{name=value}
18087 @cindex @option{-X} (@command{gnattest})
18088 Indicate that external variable @var{name} has the value @var{value}.
18091 @cindex @option{-q} (@command{gnattest})
18092 Suppresses noncritical output messages.
18095 @cindex @option{-v} (@command{gnattest})
18096 Verbose mode: generates version information.
18099 @cindex @option{--liskov} (@command{gnattest})
18100 Enables Liskov verification: run all tests from all parents in order
18101 to check substitutability.
18103 @item --stub-default=@var{val}
18104 @cindex @option{--stub-default} (@command{gnattest})
18105 Specifies the default behavior of generated stubs. @var{val} can be either
18106 "fail" or "pass", "fail" being the default.
18108 @item --separate-root=@var{dirname}
18109 @cindex @option{--separate-root} (@command{gnattest})
18110 The directory hierarchy of tested sources is recreated in the @var{dirname}
18111 directory, and test packages are placed in corresponding directories.
18113 @item --subdir=@var{dirname}
18114 @cindex @option{--subdir} (@command{gnattest})
18115 Test packages are placed in subdirectories. This is the default output mode
18116 since it does not require any additional input from the user. Subdirectories
18117 named "tests" will be created by default.
18121 @option{--separate_root} and @option{--subdir} switches are mutually exclusive.
18123 @node Project Attributes for gnattest
18124 @section Project Attributes for @command{gnattest}
18128 Most of the command-line options can also be passed to the tool by adding
18129 special attributes to the project file. Those attributes should be put in
18130 package gnattest. Here is the list of attributes:
18134 @item Separate_Stub_Root
18135 is used to select the same output mode as with the --separate-root option.
18136 This attribute cannot be used together with Stub_Subdir.
18139 is used to select the same output mode as with the --subdir option.
18140 This attribute cannot be used together with Separate_Stub_Root.
18143 is used to specify the directory in which to place harness packages and project
18144 file for the test driver, otherwise specified by --harness-dir.
18146 @item Additional_Tests
18147 is used to specify the project file, otherwise given by
18148 --additional-tests switch.
18150 @item Stubs_Default
18151 is used to specify the default behaviour of test stubs, otherwise
18152 specified by --stub-default option. The value of this attribute
18153 should be either "pass" or "fail".
18157 Each of those attributes can be overridden from the command line if needed.
18158 Other @command{gnattest} switches can also be passed via the project
18159 file as an attribute list called GNATtest_Switches.
18161 @node Simple Example
18162 @section Simple Example
18166 Let's take a very simple example using the first @command{gnattest} example
18170 <install_prefix>/share/examples/gnattest/simple
18173 This project contains a simple package containing one subprogram. By running gnattest:
18176 $ gnattest --harness-dir=driver -Psimple.gpr
18179 a test driver is created in directory "driver". It can be compiled and run:
18183 $ gprbuild -Ptest_driver
18187 One failed test with diagnosis "test not implemented" is reported.
18188 Since no special output option was specified, the test package Simple.Tests
18192 <install_prefix>/share/examples/gnattest/simple/src/tests
18195 For each package containing visible subprograms, a child test package is
18196 generated. It contains one test routine per tested subprogram. Each
18197 declaration of a test subprogram has a comment specifying which tested
18198 subprogram it corresponds to. All of the test routines have separate bodies.
18199 The test routine located at simple-tests-test_inc_5eaee3.adb contains a single
18200 statement: a call to procedure Assert. It has two arguments: the Boolean
18201 expression we want to check and the diagnosis message to display if
18202 the condition is false.
18204 That is where actual testing code should be written after a proper setup.
18205 An actual check can be performed by replacing the Assert call with:
18207 @smallexample @c ada
18208 Assert (Inc (1) = 2, "wrong incrementation");
18211 After recompiling and running the test driver, one successfully passed test
18214 @node Setting Up and Tearing Down the Testing Environment
18215 @section Setting Up and Tearing Down the Testing Environment
18219 Besides test routines themselves, each test package has an inner package
18220 Env_Mgmt that has two procedures: User_Set_Up and User_Tear_Down.
18221 User_Set_Up is called before each test routine of the package and
18222 User_Tear_Down is called after each test routine. Those two procedures can
18223 be used to perform necessary initialization and finalization,
18224 memory allocation, etc.
18226 @node Regenerating Tests
18227 @section Regenerating Tests
18231 Bodies of test routines and env_mgmt packages are never overridden after they
18232 have been created once. As long as the name of the subprogram, full expanded Ada
18233 names, and the order of its parameters is the same, the old test routine will
18234 fit in its place and no test stub will be generated for the subprogram.
18236 This can be demonstrated with the previous example. By uncommenting declaration
18237 and body of function Dec in simple.ads and simple.adb, running
18238 @command{gnattest} on the project, and then running the test driver:
18241 gnattest --harness-dir=driver -Psimple.gpr
18243 gprbuild -Ptest_driver
18247 the old test is not replaced with a stub, nor is it lost, but a new test stub is
18248 created for function Dec.
18250 The only way of regenerating tests stubs is to remove the previously created
18253 @node Default Test Behavior
18254 @section Default Test Behavior
18258 The generated test driver can treat unimplemented tests in two ways:
18259 either count them all as failed (this is useful to see which tests are still
18260 left to implement) or as passed (to sort out unimplemented ones from those
18263 The test driver accepts a switch to specify this behavior: --stub-default=val,
18264 where val is either "pass" or "fail" (exactly as for @command{gnattest}).
18266 The default behavior of the test driver is set with the same switch
18267 as passed to gnattest when generating the test driver.
18269 Passing it to the driver generated on the first example:
18272 test_runner --stub-default=pass
18275 makes both tests pass, even the unimplemented one.
18277 @node Testing Primitive Operations of Tagged Types
18278 @section Testing Primitive Operations of Tagged Types
18282 Creation of test stubs for primitive operations of tagged types entails a number
18283 of features. Test routines for all primitives of a given tagged type are
18284 placed in a separate child package named according to the tagged type. For
18285 example, if you have tagged type T in package P, all tests for primitives
18286 of T will be in P.T_Tests.
18288 Consider running gnattest on the second example (note: actual tests for this
18289 example already exist, so there's no need to worry if the tool reports that
18290 no new stubs were generated):
18293 cd <install_prefix>/share/examples/gnattest/tagged_rec
18294 gnattest --harness-dir=driver -Ptagged_rec.gpr
18297 Taking a closer look at the test type declared in the test package
18298 Speed1.Controller_Tests is necessary. It is declared in:
18301 <install_prefix>/share/examples/gnattest/tagged_rec/src/tests
18304 Test types are direct or indirect descendants of
18305 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18306 subprograms, the user doesn't need to be concerned with them. However,
18307 when generating test packages for primitive operations, there are some things
18308 the user needs to know.
18310 Type Test_Controller has components that allow assignment of various
18311 derivations of type Controller. And if you look at the specification of
18312 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18313 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18314 Thus, test types mirror the hierarchy of tested types.
18316 The User_Set_Up procedure of Env_Mgmt package corresponding to a test package
18317 of primitive operations of type T assigns to Fixture a reference to an
18318 object of that exact type T. Notice, however, that if the tagged type has
18319 discriminants, the User_Set_Up only has a commented template for setting
18320 up the fixture, since filling the discriminant with actual value is up
18323 The knowledge of the structure of test types allows additional testing
18324 without additional effort. Those possibilities are described below.
18326 @node Testing Inheritance
18327 @section Testing Inheritance
18331 Since the test type hierarchy mimics the hierarchy of tested types, the
18332 inheritance of tests takes place. An example of such inheritance can be
18333 seen by running the test driver generated for the second example. As previously
18334 mentioned, actual tests are already written for this example.
18338 gprbuild -Ptest_driver
18342 There are 6 passed tests while there are only 5 testable subprograms. The test
18343 routine for function Speed has been inherited and run against objects of the
18346 @node Tagged Types Substitutability Testing
18347 @section Tagged Types Substitutability Testing
18351 Tagged Types Substitutability Testing is a way of verifying the Liskov
18352 substitution principle (LSP) by testing. LSP is a principle stating that if
18353 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18354 then objects of type T may be replaced with objects of type S (that is,
18355 objects of type S may be substituted for objects of type T), without
18356 altering any of the desirable properties of the program. When the properties
18357 of the program are expressed in the form of subprogram preconditions and
18358 postconditions (let's call them pre and post), LSP is formulated as relations
18359 between the pre and post of primitive operations and the pre and post of their
18360 derived operations. The pre of a derived operation should not be stronger than
18361 the original pre, and the post of the derived operation should not be weaker
18362 than the original post. Those relations ensure that verifying if a dispatching
18363 call is safe can be done just by using the pre and post of the root operation.
18365 Verifying LSP by testing consists of running all the unit tests associated with
18366 the primitives of a given tagged type with objects of its derived types.
18368 In the example used in the previous section, there was clearly a violation of
18369 LSP. The overriding primitive Adjust_Speed in package Speed2 removes the
18370 functionality of the overridden primitive and thus doesn't respect LSP.
18371 Gnattest has a special option to run overridden parent tests against objects
18372 of the type which have overriding primitives:
18375 gnattest --harness-dir=driver --liskov -Ptagged_rec.gpr
18377 gprbuild -Ptest_driver
18381 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18382 against objects of the derived type.
18384 @node Testing with Contracts
18385 @section Testing with Contracts
18389 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case.
18390 Test routines are generated, one per each Test_Case associated with a tested
18391 subprogram. Those test routines have special wrappers for tested functions
18392 that have composition of pre- and postcondition of the subprogram with
18393 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18394 either count for Nominal mode or do not count for Robustness mode).
18396 The third example demonstrates how this works:
18399 cd <install_prefix>/share/examples/gnattest/contracts
18400 gnattest --harness-dir=driver -Pcontracts.gpr
18403 Putting actual checks within the range of the contract does not cause any
18404 error reports. For example, for the test routine which corresponds to
18407 @smallexample @c ada
18408 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18411 and for the test routine corresponding to test case 2:
18413 @smallexample @c ada
18414 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18421 gprbuild -Ptest_driver
18425 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18426 a precondition violation for test case one. Also, by using any otherwise
18427 correct but positive pair of numbers in the second test routine, you can also
18428 get a precondition violation. Postconditions are checked and reported
18431 @node Additional Tests
18432 @section Additional Tests
18435 @command{gnattest} can add user-written tests to the main suite of the test
18436 driver. @command{gnattest} traverses the given packages and searches for test
18437 routines. All procedures with a single in out parameter of a type which is
18438 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18439 specifications are added to the suites and are then executed by the test driver.
18440 (Set_Up and Tear_Down are filtered out.)
18442 An example illustrates two ways of creating test harnesses for user-written
18443 tests. Directory additional_tests contains an AUnit-based test driver written
18447 <install_prefix>/share/examples/gnattest/additional_tests/
18450 To create a test driver for already-written tests, use the --harness-only
18454 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18456 gnatmake -Pharness_only/test_driver.gpr
18457 harness_only/test_runner
18460 Additional tests can also be executed together with generated tests:
18463 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18464 --harness-dir=mixing
18465 gnatmake -Pmixing/test_driver.gpr
18469 @node Current Limitations
18470 @section Current Limitations
18474 The tool currently does not support following features:
18477 @item generic tests for generic packages and package instantiations
18478 @item tests for protected subprograms and entries
18479 @item aspects Precondition, Postcondition, and Test_Case
18480 @item generating test packages for code that is not conformant with ada 2005
18484 @c *********************************
18485 @node Generating Ada Bindings for C and C++ headers
18486 @chapter Generating Ada Bindings for C and C++ headers
18490 GNAT now comes with a binding generator for C and C++ headers which is
18491 intended to do 95% of the tedious work of generating Ada specs from C
18492 or C++ header files.
18494 Note that this capability is not intended to generate 100% correct Ada specs,
18495 and will is some cases require manual adjustments, although it can often
18496 be used out of the box in practice.
18498 Some of the known limitations include:
18501 @item only very simple character constant macros are translated into Ada
18502 constants. Function macros (macros with arguments) are partially translated
18503 as comments, to be completed manually if needed.
18504 @item some extensions (e.g. vector types) are not supported
18505 @item pointers to pointers or complex structures are mapped to System.Address
18506 @item identifiers with identical name (except casing) will generate compilation
18507 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
18510 The code generated is using the Ada 2005 syntax, which makes it
18511 easier to interface with other languages than previous versions of Ada.
18514 * Running the binding generator::
18515 * Generating bindings for C++ headers::
18519 @node Running the binding generator
18520 @section Running the binding generator
18523 The binding generator is part of the @command{gcc} compiler and can be
18524 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18525 spec files for the header files specified on the command line, and all
18526 header files needed by these files transitively. For example:
18529 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18530 $ gcc -c -gnat05 *.ads
18533 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18534 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18535 correspond to the files @file{/usr/include/time.h},
18536 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18537 mode these Ada specs.
18539 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18540 and will attempt to generate corresponding Ada comments.
18542 If you want to generate a single Ada file and not the transitive closure, you
18543 can use instead the @option{-fdump-ada-spec-slim} switch.
18545 Note that we recommend when possible to use the @command{g++} driver to
18546 generate bindings, even for most C headers, since this will in general
18547 generate better Ada specs. For generating bindings for C++ headers, it is
18548 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18549 is equivalent in this case. If @command{g++} cannot work on your C headers
18550 because of incompatibilities between C and C++, then you can fallback to
18551 @command{gcc} instead.
18553 For an example of better bindings generated from the C++ front-end,
18554 the name of the parameters (when available) are actually ignored by the C
18555 front-end. Consider the following C header:
18558 extern void foo (int variable);
18561 with the C front-end, @code{variable} is ignored, and the above is handled as:
18564 extern void foo (int);
18567 generating a generic:
18570 procedure foo (param1 : int);
18573 with the C++ front-end, the name is available, and we generate:
18576 procedure foo (variable : int);
18579 In some cases, the generated bindings will be more complete or more meaningful
18580 when defining some macros, which you can do via the @option{-D} switch. This
18581 is for example the case with @file{Xlib.h} under GNU/Linux:
18584 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18587 The above will generate more complete bindings than a straight call without
18588 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18590 In other cases, it is not possible to parse a header file in a stand-alone
18591 manner, because other include files need to be included first. In this
18592 case, the solution is to create a small header file including the needed
18593 @code{#include} and possible @code{#define} directives. For example, to
18594 generate Ada bindings for @file{readline/readline.h}, you need to first
18595 include @file{stdio.h}, so you can create a file with the following two
18596 lines in e.g. @file{readline1.h}:
18600 #include <readline/readline.h>
18603 and then generate Ada bindings from this file:
18606 $ g++ -c -fdump-ada-spec readline1.h
18609 @node Generating bindings for C++ headers
18610 @section Generating bindings for C++ headers
18613 Generating bindings for C++ headers is done using the same options, always
18614 with the @command{g++} compiler.
18616 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18617 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18618 multiple inheritance of abstract classes will be mapped to Ada interfaces
18619 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18620 information on interfacing to C++).
18622 For example, given the following C++ header file:
18629 virtual int Number_Of_Teeth () = 0;
18634 virtual void Set_Owner (char* Name) = 0;
18640 virtual void Set_Age (int New_Age);
18643 class Dog : Animal, Carnivore, Domestic @{
18648 virtual int Number_Of_Teeth ();
18649 virtual void Set_Owner (char* Name);
18657 The corresponding Ada code is generated:
18659 @smallexample @c ada
18662 package Class_Carnivore is
18663 type Carnivore is limited interface;
18664 pragma Import (CPP, Carnivore);
18666 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18668 use Class_Carnivore;
18670 package Class_Domestic is
18671 type Domestic is limited interface;
18672 pragma Import (CPP, Domestic);
18674 procedure Set_Owner
18675 (this : access Domestic;
18676 Name : Interfaces.C.Strings.chars_ptr) is abstract;
18678 use Class_Domestic;
18680 package Class_Animal is
18681 type Animal is tagged limited record
18682 Age_Count : aliased int;
18684 pragma Import (CPP, Animal);
18686 procedure Set_Age (this : access Animal; New_Age : int);
18687 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18691 package Class_Dog is
18692 type Dog is new Animal and Carnivore and Domestic with record
18693 Tooth_Count : aliased int;
18694 Owner : Interfaces.C.Strings.chars_ptr;
18696 pragma Import (CPP, Dog);
18698 function Number_Of_Teeth (this : access Dog) return int;
18699 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18701 procedure Set_Owner
18702 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18703 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18705 function New_Dog return Dog;
18706 pragma CPP_Constructor (New_Dog);
18707 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18718 @item -fdump-ada-spec
18719 @cindex @option{-fdump-ada-spec} (@command{gcc})
18720 Generate Ada spec files for the given header files transitively (including
18721 all header files that these headers depend upon).
18723 @item -fdump-ada-spec-slim
18724 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18725 Generate Ada spec files for the header files specified on the command line
18729 @cindex @option{-C} (@command{gcc})
18730 Extract comments from headers and generate Ada comments in the Ada spec files.
18733 @node Other Utility Programs
18734 @chapter Other Utility Programs
18737 This chapter discusses some other utility programs available in the Ada
18741 * Using Other Utility Programs with GNAT::
18742 * The External Symbol Naming Scheme of GNAT::
18743 * Converting Ada Files to html with gnathtml::
18744 * Installing gnathtml::
18751 @node Using Other Utility Programs with GNAT
18752 @section Using Other Utility Programs with GNAT
18755 The object files generated by GNAT are in standard system format and in
18756 particular the debugging information uses this format. This means
18757 programs generated by GNAT can be used with existing utilities that
18758 depend on these formats.
18761 In general, any utility program that works with C will also often work with
18762 Ada programs generated by GNAT. This includes software utilities such as
18763 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18767 @node The External Symbol Naming Scheme of GNAT
18768 @section The External Symbol Naming Scheme of GNAT
18771 In order to interpret the output from GNAT, when using tools that are
18772 originally intended for use with other languages, it is useful to
18773 understand the conventions used to generate link names from the Ada
18776 All link names are in all lowercase letters. With the exception of library
18777 procedure names, the mechanism used is simply to use the full expanded
18778 Ada name with dots replaced by double underscores. For example, suppose
18779 we have the following package spec:
18781 @smallexample @c ada
18792 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18793 the corresponding link name is @code{qrs__mn}.
18795 Of course if a @code{pragma Export} is used this may be overridden:
18797 @smallexample @c ada
18802 pragma Export (Var1, C, External_Name => "var1_name");
18804 pragma Export (Var2, C, Link_Name => "var2_link_name");
18811 In this case, the link name for @var{Var1} is whatever link name the
18812 C compiler would assign for the C function @var{var1_name}. This typically
18813 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18814 system conventions, but other possibilities exist. The link name for
18815 @var{Var2} is @var{var2_link_name}, and this is not operating system
18819 One exception occurs for library level procedures. A potential ambiguity
18820 arises between the required name @code{_main} for the C main program,
18821 and the name we would otherwise assign to an Ada library level procedure
18822 called @code{Main} (which might well not be the main program).
18824 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18825 names. So if we have a library level procedure such as
18827 @smallexample @c ada
18830 procedure Hello (S : String);
18836 the external name of this procedure will be @var{_ada_hello}.
18839 @node Converting Ada Files to html with gnathtml
18840 @section Converting Ada Files to HTML with @code{gnathtml}
18843 This @code{Perl} script allows Ada source files to be browsed using
18844 standard Web browsers. For installation procedure, see the section
18845 @xref{Installing gnathtml}.
18847 Ada reserved keywords are highlighted in a bold font and Ada comments in
18848 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18849 switch to suppress the generation of cross-referencing information, user
18850 defined variables and types will appear in a different color; you will
18851 be able to click on any identifier and go to its declaration.
18853 The command line is as follow:
18855 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18856 @c Expanding @ovar macro inline (explanation in macro def comments)
18857 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18861 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18862 an html file for every ada file, and a global file called @file{index.htm}.
18863 This file is an index of every identifier defined in the files.
18865 The available ^switches^options^ are the following ones:
18869 @cindex @option{-83} (@code{gnathtml})
18870 Only the Ada 83 subset of keywords will be highlighted.
18872 @item -cc @var{color}
18873 @cindex @option{-cc} (@code{gnathtml})
18874 This option allows you to change the color used for comments. The default
18875 value is green. The color argument can be any name accepted by html.
18878 @cindex @option{-d} (@code{gnathtml})
18879 If the Ada files depend on some other files (for instance through
18880 @code{with} clauses, the latter files will also be converted to html.
18881 Only the files in the user project will be converted to html, not the files
18882 in the run-time library itself.
18885 @cindex @option{-D} (@code{gnathtml})
18886 This command is the same as @option{-d} above, but @command{gnathtml} will
18887 also look for files in the run-time library, and generate html files for them.
18889 @item -ext @var{extension}
18890 @cindex @option{-ext} (@code{gnathtml})
18891 This option allows you to change the extension of the generated HTML files.
18892 If you do not specify an extension, it will default to @file{htm}.
18895 @cindex @option{-f} (@code{gnathtml})
18896 By default, gnathtml will generate html links only for global entities
18897 ('with'ed units, global variables and types,@dots{}). If you specify
18898 @option{-f} on the command line, then links will be generated for local
18901 @item -l @var{number}
18902 @cindex @option{-l} (@code{gnathtml})
18903 If this ^switch^option^ is provided and @var{number} is not 0, then
18904 @code{gnathtml} will number the html files every @var{number} line.
18907 @cindex @option{-I} (@code{gnathtml})
18908 Specify a directory to search for library files (@file{.ALI} files) and
18909 source files. You can provide several -I switches on the command line,
18910 and the directories will be parsed in the order of the command line.
18913 @cindex @option{-o} (@code{gnathtml})
18914 Specify the output directory for html files. By default, gnathtml will
18915 saved the generated html files in a subdirectory named @file{html/}.
18917 @item -p @var{file}
18918 @cindex @option{-p} (@code{gnathtml})
18919 If you are using Emacs and the most recent Emacs Ada mode, which provides
18920 a full Integrated Development Environment for compiling, checking,
18921 running and debugging applications, you may use @file{.gpr} files
18922 to give the directories where Emacs can find sources and object files.
18924 Using this ^switch^option^, you can tell gnathtml to use these files.
18925 This allows you to get an html version of your application, even if it
18926 is spread over multiple directories.
18928 @item -sc @var{color}
18929 @cindex @option{-sc} (@code{gnathtml})
18930 This ^switch^option^ allows you to change the color used for symbol
18932 The default value is red. The color argument can be any name accepted by html.
18934 @item -t @var{file}
18935 @cindex @option{-t} (@code{gnathtml})
18936 This ^switch^option^ provides the name of a file. This file contains a list of
18937 file names to be converted, and the effect is exactly as though they had
18938 appeared explicitly on the command line. This
18939 is the recommended way to work around the command line length limit on some
18944 @node Installing gnathtml
18945 @section Installing @code{gnathtml}
18948 @code{Perl} needs to be installed on your machine to run this script.
18949 @code{Perl} is freely available for almost every architecture and
18950 Operating System via the Internet.
18952 On Unix systems, you may want to modify the first line of the script
18953 @code{gnathtml}, to explicitly tell the Operating system where Perl
18954 is. The syntax of this line is:
18956 #!full_path_name_to_perl
18960 Alternatively, you may run the script using the following command line:
18963 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18964 @c Expanding @ovar macro inline (explanation in macro def comments)
18965 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18974 The GNAT distribution provides an Ada 95 template for the HP Language
18975 Sensitive Editor (LSE), a component of DECset. In order to
18976 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18983 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18984 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18985 the collection phase with the /DEBUG qualifier.
18988 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18989 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18990 $ RUN/DEBUG <PROGRAM_NAME>
18996 @c ******************************
18997 @node Code Coverage and Profiling
18998 @chapter Code Coverage and Profiling
18999 @cindex Code Coverage
19003 This chapter describes how to use @code{gcov} - coverage testing tool - and
19004 @code{gprof} - profiler tool - on your Ada programs.
19007 * Code Coverage of Ada Programs using gcov::
19008 * Profiling an Ada Program using gprof::
19011 @node Code Coverage of Ada Programs using gcov
19012 @section Code Coverage of Ada Programs using gcov
19014 @cindex -fprofile-arcs
19015 @cindex -ftest-coverage
19017 @cindex Code Coverage
19020 @code{gcov} is a test coverage program: it analyzes the execution of a given
19021 program on selected tests, to help you determine the portions of the program
19022 that are still untested.
19024 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
19025 User's Guide. You can refer to this documentation for a more complete
19028 This chapter provides a quick startup guide, and
19029 details some Gnat-specific features.
19032 * Quick startup guide::
19036 @node Quick startup guide
19037 @subsection Quick startup guide
19039 In order to perform coverage analysis of a program using @code{gcov}, 3
19044 Code instrumentation during the compilation process
19046 Execution of the instrumented program
19048 Execution of the @code{gcov} tool to generate the result.
19051 The code instrumentation needed by gcov is created at the object level:
19052 The source code is not modified in any way, because the instrumentation code is
19053 inserted by gcc during the compilation process. To compile your code with code
19054 coverage activated, you need to recompile your whole project using the
19056 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19057 @code{-fprofile-arcs}.
19060 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19061 -largs -fprofile-arcs
19064 This compilation process will create @file{.gcno} files together with
19065 the usual object files.
19067 Once the program is compiled with coverage instrumentation, you can
19068 run it as many times as needed - on portions of a test suite for
19069 example. The first execution will produce @file{.gcda} files at the
19070 same location as the @file{.gcno} files. The following executions
19071 will update those files, so that a cumulative result of the covered
19072 portions of the program is generated.
19074 Finally, you need to call the @code{gcov} tool. The different options of
19075 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
19077 This will create annotated source files with a @file{.gcov} extension:
19078 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
19080 @node Gnat specifics
19081 @subsection Gnat specifics
19083 Because Ada semantics, portions of the source code may be shared among
19084 several object files. This is the case for example when generics are
19085 involved, when inlining is active or when declarations generate initialisation
19086 calls. In order to take
19087 into account this shared code, you need to call @code{gcov} on all
19088 source files of the tested program at once.
19090 The list of source files might exceed the system's maximum command line
19091 length. In order to bypass this limitation, a new mechanism has been
19092 implemented in @code{gcov}: you can now list all your project's files into a
19093 text file, and provide this file to gcov as a parameter, preceded by a @@
19094 (e.g. @samp{gcov @@mysrclist.txt}).
19096 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
19097 not supported as there can be unresolved symbols during the final link.
19099 @node Profiling an Ada Program using gprof
19100 @section Profiling an Ada Program using gprof
19106 This section is not meant to be an exhaustive documentation of @code{gprof}.
19107 Full documentation for it can be found in the GNU Profiler User's Guide
19108 documentation that is part of this GNAT distribution.
19110 Profiling a program helps determine the parts of a program that are executed
19111 most often, and are therefore the most time-consuming.
19113 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19114 better handle Ada programs and multitasking.
19115 It is currently supported on the following platforms
19120 solaris sparc/sparc64/x86
19126 In order to profile a program using @code{gprof}, 3 steps are needed:
19130 Code instrumentation, requiring a full recompilation of the project with the
19133 Execution of the program under the analysis conditions, i.e. with the desired
19136 Analysis of the results using the @code{gprof} tool.
19140 The following sections detail the different steps, and indicate how
19141 to interpret the results:
19143 * Compilation for profiling::
19144 * Program execution::
19146 * Interpretation of profiling results::
19149 @node Compilation for profiling
19150 @subsection Compilation for profiling
19154 In order to profile a program the first step is to tell the compiler
19155 to generate the necessary profiling information. The compiler switch to be used
19156 is @code{-pg}, which must be added to other compilation switches. This
19157 switch needs to be specified both during compilation and link stages, and can
19158 be specified once when using gnatmake:
19161 gnatmake -f -pg -P my_project
19165 Note that only the objects that were compiled with the @samp{-pg} switch will
19166 be profiled; if you need to profile your whole project, use the @samp{-f}
19167 gnatmake switch to force full recompilation.
19169 @node Program execution
19170 @subsection Program execution
19173 Once the program has been compiled for profiling, you can run it as usual.
19175 The only constraint imposed by profiling is that the program must terminate
19176 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19179 Once the program completes execution, a data file called @file{gmon.out} is
19180 generated in the directory where the program was launched from. If this file
19181 already exists, it will be overwritten.
19183 @node Running gprof
19184 @subsection Running gprof
19187 The @code{gprof} tool is called as follow:
19190 gprof my_prog gmon.out
19201 The complete form of the gprof command line is the following:
19204 gprof [^switches^options^] [executable [data-file]]
19208 @code{gprof} supports numerous ^switch^options^. The order of these
19209 ^switch^options^ does not matter. The full list of options can be found in
19210 the GNU Profiler User's Guide documentation that comes with this documentation.
19212 The following is the subset of those switches that is most relevant:
19216 @item --demangle[=@var{style}]
19217 @itemx --no-demangle
19218 @cindex @option{--demangle} (@code{gprof})
19219 These options control whether symbol names should be demangled when
19220 printing output. The default is to demangle C++ symbols. The
19221 @code{--no-demangle} option may be used to turn off demangling. Different
19222 compilers have different mangling styles. The optional demangling style
19223 argument can be used to choose an appropriate demangling style for your
19224 compiler, in particular Ada symbols generated by GNAT can be demangled using
19225 @code{--demangle=gnat}.
19227 @item -e @var{function_name}
19228 @cindex @option{-e} (@code{gprof})
19229 The @samp{-e @var{function}} option tells @code{gprof} not to print
19230 information about the function @var{function_name} (and its
19231 children@dots{}) in the call graph. The function will still be listed
19232 as a child of any functions that call it, but its index number will be
19233 shown as @samp{[not printed]}. More than one @samp{-e} option may be
19234 given; only one @var{function_name} may be indicated with each @samp{-e}
19237 @item -E @var{function_name}
19238 @cindex @option{-E} (@code{gprof})
19239 The @code{-E @var{function}} option works like the @code{-e} option, but
19240 execution time spent in the function (and children who were not called from
19241 anywhere else), will not be used to compute the percentages-of-time for
19242 the call graph. More than one @samp{-E} option may be given; only one
19243 @var{function_name} may be indicated with each @samp{-E} option.
19245 @item -f @var{function_name}
19246 @cindex @option{-f} (@code{gprof})
19247 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19248 call graph to the function @var{function_name} and its children (and
19249 their children@dots{}). More than one @samp{-f} option may be given;
19250 only one @var{function_name} may be indicated with each @samp{-f}
19253 @item -F @var{function_name}
19254 @cindex @option{-F} (@code{gprof})
19255 The @samp{-F @var{function}} option works like the @code{-f} option, but
19256 only time spent in the function and its children (and their
19257 children@dots{}) will be used to determine total-time and
19258 percentages-of-time for the call graph. More than one @samp{-F} option
19259 may be given; only one @var{function_name} may be indicated with each
19260 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
19264 @node Interpretation of profiling results
19265 @subsection Interpretation of profiling results
19269 The results of the profiling analysis are represented by two arrays: the
19270 'flat profile' and the 'call graph'. Full documentation of those outputs
19271 can be found in the GNU Profiler User's Guide.
19273 The flat profile shows the time spent in each function of the program, and how
19274 many time it has been called. This allows you to locate easily the most
19275 time-consuming functions.
19277 The call graph shows, for each subprogram, the subprograms that call it,
19278 and the subprograms that it calls. It also provides an estimate of the time
19279 spent in each of those callers/called subprograms.
19282 @c ******************************
19283 @node Running and Debugging Ada Programs
19284 @chapter Running and Debugging Ada Programs
19288 This chapter discusses how to debug Ada programs.
19290 It applies to GNAT on the Alpha OpenVMS platform;
19291 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19292 since HP has implemented Ada support in the OpenVMS debugger on I64.
19295 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19299 The illegality may be a violation of the static semantics of Ada. In
19300 that case GNAT diagnoses the constructs in the program that are illegal.
19301 It is then a straightforward matter for the user to modify those parts of
19305 The illegality may be a violation of the dynamic semantics of Ada. In
19306 that case the program compiles and executes, but may generate incorrect
19307 results, or may terminate abnormally with some exception.
19310 When presented with a program that contains convoluted errors, GNAT
19311 itself may terminate abnormally without providing full diagnostics on
19312 the incorrect user program.
19316 * The GNAT Debugger GDB::
19318 * Introduction to GDB Commands::
19319 * Using Ada Expressions::
19320 * Calling User-Defined Subprograms::
19321 * Using the Next Command in a Function::
19324 * Debugging Generic Units::
19325 * Remote Debugging using gdbserver::
19326 * GNAT Abnormal Termination or Failure to Terminate::
19327 * Naming Conventions for GNAT Source Files::
19328 * Getting Internal Debugging Information::
19329 * Stack Traceback::
19335 @node The GNAT Debugger GDB
19336 @section The GNAT Debugger GDB
19339 @code{GDB} is a general purpose, platform-independent debugger that
19340 can be used to debug mixed-language programs compiled with @command{gcc},
19341 and in particular is capable of debugging Ada programs compiled with
19342 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19343 complex Ada data structures.
19345 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19347 located in the GNU:[DOCS] directory,
19349 for full details on the usage of @code{GDB}, including a section on
19350 its usage on programs. This manual should be consulted for full
19351 details. The section that follows is a brief introduction to the
19352 philosophy and use of @code{GDB}.
19354 When GNAT programs are compiled, the compiler optionally writes debugging
19355 information into the generated object file, including information on
19356 line numbers, and on declared types and variables. This information is
19357 separate from the generated code. It makes the object files considerably
19358 larger, but it does not add to the size of the actual executable that
19359 will be loaded into memory, and has no impact on run-time performance. The
19360 generation of debug information is triggered by the use of the
19361 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19362 used to carry out the compilations. It is important to emphasize that
19363 the use of these options does not change the generated code.
19365 The debugging information is written in standard system formats that
19366 are used by many tools, including debuggers and profilers. The format
19367 of the information is typically designed to describe C types and
19368 semantics, but GNAT implements a translation scheme which allows full
19369 details about Ada types and variables to be encoded into these
19370 standard C formats. Details of this encoding scheme may be found in
19371 the file exp_dbug.ads in the GNAT source distribution. However, the
19372 details of this encoding are, in general, of no interest to a user,
19373 since @code{GDB} automatically performs the necessary decoding.
19375 When a program is bound and linked, the debugging information is
19376 collected from the object files, and stored in the executable image of
19377 the program. Again, this process significantly increases the size of
19378 the generated executable file, but it does not increase the size of
19379 the executable program itself. Furthermore, if this program is run in
19380 the normal manner, it runs exactly as if the debug information were
19381 not present, and takes no more actual memory.
19383 However, if the program is run under control of @code{GDB}, the
19384 debugger is activated. The image of the program is loaded, at which
19385 point it is ready to run. If a run command is given, then the program
19386 will run exactly as it would have if @code{GDB} were not present. This
19387 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
19388 entirely non-intrusive until a breakpoint is encountered. If no
19389 breakpoint is ever hit, the program will run exactly as it would if no
19390 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19391 the debugging information and can respond to user commands to inspect
19392 variables, and more generally to report on the state of execution.
19396 @section Running GDB
19399 This section describes how to initiate the debugger.
19400 @c The above sentence is really just filler, but it was otherwise
19401 @c clumsy to get the first paragraph nonindented given the conditional
19402 @c nature of the description
19405 The debugger can be launched from a @code{GPS} menu or
19406 directly from the command line. The description below covers the latter use.
19407 All the commands shown can be used in the @code{GPS} debug console window,
19408 but there are usually more GUI-based ways to achieve the same effect.
19411 The command to run @code{GDB} is
19414 $ ^gdb program^GDB PROGRAM^
19418 where @code{^program^PROGRAM^} is the name of the executable file. This
19419 activates the debugger and results in a prompt for debugger commands.
19420 The simplest command is simply @code{run}, which causes the program to run
19421 exactly as if the debugger were not present. The following section
19422 describes some of the additional commands that can be given to @code{GDB}.
19424 @c *******************************
19425 @node Introduction to GDB Commands
19426 @section Introduction to GDB Commands
19429 @code{GDB} contains a large repertoire of commands. @xref{Top,,
19430 Debugging with GDB, gdb, Debugging with GDB},
19432 located in the GNU:[DOCS] directory,
19434 for extensive documentation on the use
19435 of these commands, together with examples of their use. Furthermore,
19436 the command @command{help} invoked from within GDB activates a simple help
19437 facility which summarizes the available commands and their options.
19438 In this section we summarize a few of the most commonly
19439 used commands to give an idea of what @code{GDB} is about. You should create
19440 a simple program with debugging information and experiment with the use of
19441 these @code{GDB} commands on the program as you read through the
19445 @item set args @var{arguments}
19446 The @var{arguments} list above is a list of arguments to be passed to
19447 the program on a subsequent run command, just as though the arguments
19448 had been entered on a normal invocation of the program. The @code{set args}
19449 command is not needed if the program does not require arguments.
19452 The @code{run} command causes execution of the program to start from
19453 the beginning. If the program is already running, that is to say if
19454 you are currently positioned at a breakpoint, then a prompt will ask
19455 for confirmation that you want to abandon the current execution and
19458 @item breakpoint @var{location}
19459 The breakpoint command sets a breakpoint, that is to say a point at which
19460 execution will halt and @code{GDB} will await further
19461 commands. @var{location} is
19462 either a line number within a file, given in the format @code{file:linenumber},
19463 or it is the name of a subprogram. If you request that a breakpoint be set on
19464 a subprogram that is overloaded, a prompt will ask you to specify on which of
19465 those subprograms you want to breakpoint. You can also
19466 specify that all of them should be breakpointed. If the program is run
19467 and execution encounters the breakpoint, then the program
19468 stops and @code{GDB} signals that the breakpoint was encountered by
19469 printing the line of code before which the program is halted.
19471 @item catch exception @var{name}
19472 This command causes the program execution to stop whenever exception
19473 @var{name} is raised. If @var{name} is omitted, then the execution is
19474 suspended when any exception is raised.
19476 @item print @var{expression}
19477 This will print the value of the given expression. Most simple
19478 Ada expression formats are properly handled by @code{GDB}, so the expression
19479 can contain function calls, variables, operators, and attribute references.
19482 Continues execution following a breakpoint, until the next breakpoint or the
19483 termination of the program.
19486 Executes a single line after a breakpoint. If the next statement
19487 is a subprogram call, execution continues into (the first statement of)
19488 the called subprogram.
19491 Executes a single line. If this line is a subprogram call, executes and
19492 returns from the call.
19495 Lists a few lines around the current source location. In practice, it
19496 is usually more convenient to have a separate edit window open with the
19497 relevant source file displayed. Successive applications of this command
19498 print subsequent lines. The command can be given an argument which is a
19499 line number, in which case it displays a few lines around the specified one.
19502 Displays a backtrace of the call chain. This command is typically
19503 used after a breakpoint has occurred, to examine the sequence of calls that
19504 leads to the current breakpoint. The display includes one line for each
19505 activation record (frame) corresponding to an active subprogram.
19508 At a breakpoint, @code{GDB} can display the values of variables local
19509 to the current frame. The command @code{up} can be used to
19510 examine the contents of other active frames, by moving the focus up
19511 the stack, that is to say from callee to caller, one frame at a time.
19514 Moves the focus of @code{GDB} down from the frame currently being
19515 examined to the frame of its callee (the reverse of the previous command),
19517 @item frame @var{n}
19518 Inspect the frame with the given number. The value 0 denotes the frame
19519 of the current breakpoint, that is to say the top of the call stack.
19524 The above list is a very short introduction to the commands that
19525 @code{GDB} provides. Important additional capabilities, including conditional
19526 breakpoints, the ability to execute command sequences on a breakpoint,
19527 the ability to debug at the machine instruction level and many other
19528 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19529 Debugging with GDB}. Note that most commands can be abbreviated
19530 (for example, c for continue, bt for backtrace).
19532 @node Using Ada Expressions
19533 @section Using Ada Expressions
19534 @cindex Ada expressions
19537 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19538 extensions. The philosophy behind the design of this subset is
19542 That @code{GDB} should provide basic literals and access to operations for
19543 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19544 leaving more sophisticated computations to subprograms written into the
19545 program (which therefore may be called from @code{GDB}).
19548 That type safety and strict adherence to Ada language restrictions
19549 are not particularly important to the @code{GDB} user.
19552 That brevity is important to the @code{GDB} user.
19556 Thus, for brevity, the debugger acts as if there were
19557 implicit @code{with} and @code{use} clauses in effect for all user-written
19558 packages, thus making it unnecessary to fully qualify most names with
19559 their packages, regardless of context. Where this causes ambiguity,
19560 @code{GDB} asks the user's intent.
19562 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19563 GDB, gdb, Debugging with GDB}.
19565 @node Calling User-Defined Subprograms
19566 @section Calling User-Defined Subprograms
19569 An important capability of @code{GDB} is the ability to call user-defined
19570 subprograms while debugging. This is achieved simply by entering
19571 a subprogram call statement in the form:
19574 call subprogram-name (parameters)
19578 The keyword @code{call} can be omitted in the normal case where the
19579 @code{subprogram-name} does not coincide with any of the predefined
19580 @code{GDB} commands.
19582 The effect is to invoke the given subprogram, passing it the
19583 list of parameters that is supplied. The parameters can be expressions and
19584 can include variables from the program being debugged. The
19585 subprogram must be defined
19586 at the library level within your program, and @code{GDB} will call the
19587 subprogram within the environment of your program execution (which
19588 means that the subprogram is free to access or even modify variables
19589 within your program).
19591 The most important use of this facility is in allowing the inclusion of
19592 debugging routines that are tailored to particular data structures
19593 in your program. Such debugging routines can be written to provide a suitably
19594 high-level description of an abstract type, rather than a low-level dump
19595 of its physical layout. After all, the standard
19596 @code{GDB print} command only knows the physical layout of your
19597 types, not their abstract meaning. Debugging routines can provide information
19598 at the desired semantic level and are thus enormously useful.
19600 For example, when debugging GNAT itself, it is crucial to have access to
19601 the contents of the tree nodes used to represent the program internally.
19602 But tree nodes are represented simply by an integer value (which in turn
19603 is an index into a table of nodes).
19604 Using the @code{print} command on a tree node would simply print this integer
19605 value, which is not very useful. But the PN routine (defined in file
19606 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19607 a useful high level representation of the tree node, which includes the
19608 syntactic category of the node, its position in the source, the integers
19609 that denote descendant nodes and parent node, as well as varied
19610 semantic information. To study this example in more detail, you might want to
19611 look at the body of the PN procedure in the stated file.
19613 @node Using the Next Command in a Function
19614 @section Using the Next Command in a Function
19617 When you use the @code{next} command in a function, the current source
19618 location will advance to the next statement as usual. A special case
19619 arises in the case of a @code{return} statement.
19621 Part of the code for a return statement is the ``epilog'' of the function.
19622 This is the code that returns to the caller. There is only one copy of
19623 this epilog code, and it is typically associated with the last return
19624 statement in the function if there is more than one return. In some
19625 implementations, this epilog is associated with the first statement
19628 The result is that if you use the @code{next} command from a return
19629 statement that is not the last return statement of the function you
19630 may see a strange apparent jump to the last return statement or to
19631 the start of the function. You should simply ignore this odd jump.
19632 The value returned is always that from the first return statement
19633 that was stepped through.
19635 @node Ada Exceptions
19636 @section Stopping when Ada Exceptions are Raised
19640 You can set catchpoints that stop the program execution when your program
19641 raises selected exceptions.
19644 @item catch exception
19645 Set a catchpoint that stops execution whenever (any task in the) program
19646 raises any exception.
19648 @item catch exception @var{name}
19649 Set a catchpoint that stops execution whenever (any task in the) program
19650 raises the exception @var{name}.
19652 @item catch exception unhandled
19653 Set a catchpoint that stops executing whenever (any task in the) program
19654 raises an exception for which there is no handler.
19656 @item info exceptions
19657 @itemx info exceptions @var{regexp}
19658 The @code{info exceptions} command permits the user to examine all defined
19659 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19660 argument, prints out only those exceptions whose name matches @var{regexp}.
19668 @code{GDB} allows the following task-related commands:
19672 This command shows a list of current Ada tasks, as in the following example:
19679 ID TID P-ID Thread Pri State Name
19680 1 8088000 0 807e000 15 Child Activation Wait main_task
19681 2 80a4000 1 80ae000 15 Accept/Select Wait b
19682 3 809a800 1 80a4800 15 Child Activation Wait a
19683 * 4 80ae800 3 80b8000 15 Running c
19687 In this listing, the asterisk before the first task indicates it to be the
19688 currently running task. The first column lists the task ID that is used
19689 to refer to tasks in the following commands.
19691 @item break @var{linespec} task @var{taskid}
19692 @itemx break @var{linespec} task @var{taskid} if @dots{}
19693 @cindex Breakpoints and tasks
19694 These commands are like the @code{break @dots{} thread @dots{}}.
19695 @var{linespec} specifies source lines.
19697 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19698 to specify that you only want @code{GDB} to stop the program when a
19699 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19700 numeric task identifiers assigned by @code{GDB}, shown in the first
19701 column of the @samp{info tasks} display.
19703 If you do not specify @samp{task @var{taskid}} when you set a
19704 breakpoint, the breakpoint applies to @emph{all} tasks of your
19707 You can use the @code{task} qualifier on conditional breakpoints as
19708 well; in this case, place @samp{task @var{taskid}} before the
19709 breakpoint condition (before the @code{if}).
19711 @item task @var{taskno}
19712 @cindex Task switching
19714 This command allows to switch to the task referred by @var{taskno}. In
19715 particular, This allows to browse the backtrace of the specified
19716 task. It is advised to switch back to the original task before
19717 continuing execution otherwise the scheduling of the program may be
19722 For more detailed information on the tasking support,
19723 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19725 @node Debugging Generic Units
19726 @section Debugging Generic Units
19727 @cindex Debugging Generic Units
19731 GNAT always uses code expansion for generic instantiation. This means that
19732 each time an instantiation occurs, a complete copy of the original code is
19733 made, with appropriate substitutions of formals by actuals.
19735 It is not possible to refer to the original generic entities in
19736 @code{GDB}, but it is always possible to debug a particular instance of
19737 a generic, by using the appropriate expanded names. For example, if we have
19739 @smallexample @c ada
19744 generic package k is
19745 procedure kp (v1 : in out integer);
19749 procedure kp (v1 : in out integer) is
19755 package k1 is new k;
19756 package k2 is new k;
19758 var : integer := 1;
19771 Then to break on a call to procedure kp in the k2 instance, simply
19775 (gdb) break g.k2.kp
19779 When the breakpoint occurs, you can step through the code of the
19780 instance in the normal manner and examine the values of local variables, as for
19783 @node Remote Debugging using gdbserver
19784 @section Remote Debugging using gdbserver
19785 @cindex Remote Debugging using gdbserver
19788 On platforms where gdbserver is supported, it is possible to use this tool
19789 to debug your application remotely. This can be useful in situations
19790 where the program needs to be run on a target host that is different
19791 from the host used for development, particularly when the target has
19792 a limited amount of resources (either CPU and/or memory).
19794 To do so, start your program using gdbserver on the target machine.
19795 gdbserver then automatically suspends the execution of your program
19796 at its entry point, waiting for a debugger to connect to it. The
19797 following commands starts an application and tells gdbserver to
19798 wait for a connection with the debugger on localhost port 4444.
19801 $ gdbserver localhost:4444 program
19802 Process program created; pid = 5685
19803 Listening on port 4444
19806 Once gdbserver has started listening, we can tell the debugger to establish
19807 a connection with this gdbserver, and then start the same debugging session
19808 as if the program was being debugged on the same host, directly under
19809 the control of GDB.
19813 (gdb) target remote targethost:4444
19814 Remote debugging using targethost:4444
19815 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19817 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19821 Breakpoint 1, foo () at foo.adb:4
19825 It is also possible to use gdbserver to attach to an already running
19826 program, in which case the execution of that program is simply suspended
19827 until the connection between the debugger and gdbserver is established.
19829 For more information on how to use gdbserver, @ref{Top, Server, Using
19830 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
19831 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19833 @node GNAT Abnormal Termination or Failure to Terminate
19834 @section GNAT Abnormal Termination or Failure to Terminate
19835 @cindex GNAT Abnormal Termination or Failure to Terminate
19838 When presented with programs that contain serious errors in syntax
19840 GNAT may on rare occasions experience problems in operation, such
19842 segmentation fault or illegal memory access, raising an internal
19843 exception, terminating abnormally, or failing to terminate at all.
19844 In such cases, you can activate
19845 various features of GNAT that can help you pinpoint the construct in your
19846 program that is the likely source of the problem.
19848 The following strategies are presented in increasing order of
19849 difficulty, corresponding to your experience in using GNAT and your
19850 familiarity with compiler internals.
19854 Run @command{gcc} with the @option{-gnatf}. This first
19855 switch causes all errors on a given line to be reported. In its absence,
19856 only the first error on a line is displayed.
19858 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19859 are encountered, rather than after compilation is terminated. If GNAT
19860 terminates prematurely or goes into an infinite loop, the last error
19861 message displayed may help to pinpoint the culprit.
19864 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19865 mode, @command{gcc} produces ongoing information about the progress of the
19866 compilation and provides the name of each procedure as code is
19867 generated. This switch allows you to find which Ada procedure was being
19868 compiled when it encountered a code generation problem.
19871 @cindex @option{-gnatdc} switch
19872 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19873 switch that does for the front-end what @option{^-v^VERBOSE^} does
19874 for the back end. The system prints the name of each unit,
19875 either a compilation unit or nested unit, as it is being analyzed.
19877 Finally, you can start
19878 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19879 front-end of GNAT, and can be run independently (normally it is just
19880 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19881 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19882 @code{where} command is the first line of attack; the variable
19883 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19884 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19885 which the execution stopped, and @code{input_file name} indicates the name of
19889 @node Naming Conventions for GNAT Source Files
19890 @section Naming Conventions for GNAT Source Files
19893 In order to examine the workings of the GNAT system, the following
19894 brief description of its organization may be helpful:
19898 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19901 All files prefixed with @file{^par^PAR^} are components of the parser. The
19902 numbers correspond to chapters of the Ada Reference Manual. For example,
19903 parsing of select statements can be found in @file{par-ch9.adb}.
19906 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19907 numbers correspond to chapters of the Ada standard. For example, all
19908 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19909 addition, some features of the language require sufficient special processing
19910 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19911 dynamic dispatching, etc.
19914 All files prefixed with @file{^exp^EXP^} perform normalization and
19915 expansion of the intermediate representation (abstract syntax tree, or AST).
19916 these files use the same numbering scheme as the parser and semantics files.
19917 For example, the construction of record initialization procedures is done in
19918 @file{exp_ch3.adb}.
19921 The files prefixed with @file{^bind^BIND^} implement the binder, which
19922 verifies the consistency of the compilation, determines an order of
19923 elaboration, and generates the bind file.
19926 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19927 data structures used by the front-end.
19930 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19931 the abstract syntax tree as produced by the parser.
19934 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19935 all entities, computed during semantic analysis.
19938 Library management issues are dealt with in files with prefix
19944 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19945 defined in Annex A.
19950 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19951 defined in Annex B.
19955 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19956 both language-defined children and GNAT run-time routines.
19960 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19961 general-purpose packages, fully documented in their specs. All
19962 the other @file{.c} files are modifications of common @command{gcc} files.
19965 @node Getting Internal Debugging Information
19966 @section Getting Internal Debugging Information
19969 Most compilers have internal debugging switches and modes. GNAT
19970 does also, except GNAT internal debugging switches and modes are not
19971 secret. A summary and full description of all the compiler and binder
19972 debug flags are in the file @file{debug.adb}. You must obtain the
19973 sources of the compiler to see the full detailed effects of these flags.
19975 The switches that print the source of the program (reconstructed from
19976 the internal tree) are of general interest for user programs, as are the
19978 the full internal tree, and the entity table (the symbol table
19979 information). The reconstructed source provides a readable version of the
19980 program after the front-end has completed analysis and expansion,
19981 and is useful when studying the performance of specific constructs.
19982 For example, constraint checks are indicated, complex aggregates
19983 are replaced with loops and assignments, and tasking primitives
19984 are replaced with run-time calls.
19986 @node Stack Traceback
19987 @section Stack Traceback
19989 @cindex stack traceback
19990 @cindex stack unwinding
19993 Traceback is a mechanism to display the sequence of subprogram calls that
19994 leads to a specified execution point in a program. Often (but not always)
19995 the execution point is an instruction at which an exception has been raised.
19996 This mechanism is also known as @i{stack unwinding} because it obtains
19997 its information by scanning the run-time stack and recovering the activation
19998 records of all active subprograms. Stack unwinding is one of the most
19999 important tools for program debugging.
20001 The first entry stored in traceback corresponds to the deepest calling level,
20002 that is to say the subprogram currently executing the instruction
20003 from which we want to obtain the traceback.
20005 Note that there is no runtime performance penalty when stack traceback
20006 is enabled, and no exception is raised during program execution.
20009 * Non-Symbolic Traceback::
20010 * Symbolic Traceback::
20013 @node Non-Symbolic Traceback
20014 @subsection Non-Symbolic Traceback
20015 @cindex traceback, non-symbolic
20018 Note: this feature is not supported on all platforms. See
20019 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20023 * Tracebacks From an Unhandled Exception::
20024 * Tracebacks From Exception Occurrences (non-symbolic)::
20025 * Tracebacks From Anywhere in a Program (non-symbolic)::
20028 @node Tracebacks From an Unhandled Exception
20029 @subsubsection Tracebacks From an Unhandled Exception
20032 A runtime non-symbolic traceback is a list of addresses of call instructions.
20033 To enable this feature you must use the @option{-E}
20034 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20035 of exception information. You can retrieve this information using the
20036 @code{addr2line} tool.
20038 Here is a simple example:
20040 @smallexample @c ada
20046 raise Constraint_Error;
20061 $ gnatmake stb -bargs -E
20064 Execution terminated by unhandled exception
20065 Exception name: CONSTRAINT_ERROR
20067 Call stack traceback locations:
20068 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20072 As we see the traceback lists a sequence of addresses for the unhandled
20073 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20074 guess that this exception come from procedure P1. To translate these
20075 addresses into the source lines where the calls appear, the
20076 @code{addr2line} tool, described below, is invaluable. The use of this tool
20077 requires the program to be compiled with debug information.
20080 $ gnatmake -g stb -bargs -E
20083 Execution terminated by unhandled exception
20084 Exception name: CONSTRAINT_ERROR
20086 Call stack traceback locations:
20087 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20089 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20090 0x4011f1 0x77e892a4
20092 00401373 at d:/stb/stb.adb:5
20093 0040138B at d:/stb/stb.adb:10
20094 0040139C at d:/stb/stb.adb:14
20095 00401335 at d:/stb/b~stb.adb:104
20096 004011C4 at /build/@dots{}/crt1.c:200
20097 004011F1 at /build/@dots{}/crt1.c:222
20098 77E892A4 in ?? at ??:0
20102 The @code{addr2line} tool has several other useful options:
20106 to get the function name corresponding to any location
20108 @item --demangle=gnat
20109 to use the gnat decoding mode for the function names. Note that
20110 for binutils version 2.9.x the option is simply @option{--demangle}.
20114 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20115 0x40139c 0x401335 0x4011c4 0x4011f1
20117 00401373 in stb.p1 at d:/stb/stb.adb:5
20118 0040138B in stb.p2 at d:/stb/stb.adb:10
20119 0040139C in stb at d:/stb/stb.adb:14
20120 00401335 in main at d:/stb/b~stb.adb:104
20121 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
20122 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
20126 From this traceback we can see that the exception was raised in
20127 @file{stb.adb} at line 5, which was reached from a procedure call in
20128 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20129 which contains the call to the main program.
20130 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20131 and the output will vary from platform to platform.
20133 It is also possible to use @code{GDB} with these traceback addresses to debug
20134 the program. For example, we can break at a given code location, as reported
20135 in the stack traceback:
20141 Furthermore, this feature is not implemented inside Windows DLL. Only
20142 the non-symbolic traceback is reported in this case.
20145 (gdb) break *0x401373
20146 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20150 It is important to note that the stack traceback addresses
20151 do not change when debug information is included. This is particularly useful
20152 because it makes it possible to release software without debug information (to
20153 minimize object size), get a field report that includes a stack traceback
20154 whenever an internal bug occurs, and then be able to retrieve the sequence
20155 of calls with the same program compiled with debug information.
20157 @node Tracebacks From Exception Occurrences (non-symbolic)
20158 @subsubsection Tracebacks From Exception Occurrences
20161 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20162 The stack traceback is attached to the exception information string, and can
20163 be retrieved in an exception handler within the Ada program, by means of the
20164 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20166 @smallexample @c ada
20168 with Ada.Exceptions;
20173 use Ada.Exceptions;
20181 Text_IO.Put_Line (Exception_Information (E));
20195 This program will output:
20200 Exception name: CONSTRAINT_ERROR
20201 Message: stb.adb:12
20202 Call stack traceback locations:
20203 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20206 @node Tracebacks From Anywhere in a Program (non-symbolic)
20207 @subsubsection Tracebacks From Anywhere in a Program
20210 It is also possible to retrieve a stack traceback from anywhere in a
20211 program. For this you need to
20212 use the @code{GNAT.Traceback} API. This package includes a procedure called
20213 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20214 display procedures described below. It is not necessary to use the
20215 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20216 is invoked explicitly.
20219 In the following example we compute a traceback at a specific location in
20220 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20221 convert addresses to strings:
20223 @smallexample @c ada
20225 with GNAT.Traceback;
20226 with GNAT.Debug_Utilities;
20232 use GNAT.Traceback;
20235 TB : Tracebacks_Array (1 .. 10);
20236 -- We are asking for a maximum of 10 stack frames.
20238 -- Len will receive the actual number of stack frames returned.
20240 Call_Chain (TB, Len);
20242 Text_IO.Put ("In STB.P1 : ");
20244 for K in 1 .. Len loop
20245 Text_IO.Put (Debug_Utilities.Image (TB (K)));
20266 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20267 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20271 You can then get further information by invoking the @code{addr2line}
20272 tool as described earlier (note that the hexadecimal addresses
20273 need to be specified in C format, with a leading ``0x'').
20275 @node Symbolic Traceback
20276 @subsection Symbolic Traceback
20277 @cindex traceback, symbolic
20280 A symbolic traceback is a stack traceback in which procedure names are
20281 associated with each code location.
20284 Note that this feature is not supported on all platforms. See
20285 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20286 list of currently supported platforms.
20289 Note that the symbolic traceback requires that the program be compiled
20290 with debug information. If it is not compiled with debug information
20291 only the non-symbolic information will be valid.
20294 * Tracebacks From Exception Occurrences (symbolic)::
20295 * Tracebacks From Anywhere in a Program (symbolic)::
20298 @node Tracebacks From Exception Occurrences (symbolic)
20299 @subsubsection Tracebacks From Exception Occurrences
20301 @smallexample @c ada
20303 with GNAT.Traceback.Symbolic;
20309 raise Constraint_Error;
20326 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20331 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20334 0040149F in stb.p1 at stb.adb:8
20335 004014B7 in stb.p2 at stb.adb:13
20336 004014CF in stb.p3 at stb.adb:18
20337 004015DD in ada.stb at stb.adb:22
20338 00401461 in main at b~stb.adb:168
20339 004011C4 in __mingw_CRTStartup at crt1.c:200
20340 004011F1 in mainCRTStartup at crt1.c:222
20341 77E892A4 in ?? at ??:0
20345 In the above example the ``.\'' syntax in the @command{gnatmake} command
20346 is currently required by @command{addr2line} for files that are in
20347 the current working directory.
20348 Moreover, the exact sequence of linker options may vary from platform
20350 The above @option{-largs} section is for Windows platforms. By contrast,
20351 under Unix there is no need for the @option{-largs} section.
20352 Differences across platforms are due to details of linker implementation.
20354 @node Tracebacks From Anywhere in a Program (symbolic)
20355 @subsubsection Tracebacks From Anywhere in a Program
20358 It is possible to get a symbolic stack traceback
20359 from anywhere in a program, just as for non-symbolic tracebacks.
20360 The first step is to obtain a non-symbolic
20361 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20362 information. Here is an example:
20364 @smallexample @c ada
20366 with GNAT.Traceback;
20367 with GNAT.Traceback.Symbolic;
20372 use GNAT.Traceback;
20373 use GNAT.Traceback.Symbolic;
20376 TB : Tracebacks_Array (1 .. 10);
20377 -- We are asking for a maximum of 10 stack frames.
20379 -- Len will receive the actual number of stack frames returned.
20381 Call_Chain (TB, Len);
20382 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20395 @c ******************************
20397 @node Compatibility with HP Ada
20398 @chapter Compatibility with HP Ada
20399 @cindex Compatibility
20404 @cindex Compatibility between GNAT and HP Ada
20405 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20406 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20407 GNAT is highly compatible
20408 with HP Ada, and it should generally be straightforward to port code
20409 from the HP Ada environment to GNAT. However, there are a few language
20410 and implementation differences of which the user must be aware. These
20411 differences are discussed in this chapter. In
20412 addition, the operating environment and command structure for the
20413 compiler are different, and these differences are also discussed.
20415 For further details on these and other compatibility issues,
20416 see Appendix E of the HP publication
20417 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20419 Except where otherwise indicated, the description of GNAT for OpenVMS
20420 applies to both the Alpha and I64 platforms.
20422 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20423 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20425 The discussion in this chapter addresses specifically the implementation
20426 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20427 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20428 GNAT always follows the Alpha implementation.
20430 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20431 attributes are recognized, although only a subset of them can sensibly
20432 be implemented. The description of pragmas in
20433 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20434 indicates whether or not they are applicable to non-VMS systems.
20437 * Ada Language Compatibility::
20438 * Differences in the Definition of Package System::
20439 * Language-Related Features::
20440 * The Package STANDARD::
20441 * The Package SYSTEM::
20442 * Tasking and Task-Related Features::
20443 * Pragmas and Pragma-Related Features::
20444 * Library of Predefined Units::
20446 * Main Program Definition::
20447 * Implementation-Defined Attributes::
20448 * Compiler and Run-Time Interfacing::
20449 * Program Compilation and Library Management::
20451 * Implementation Limits::
20452 * Tools and Utilities::
20455 @node Ada Language Compatibility
20456 @section Ada Language Compatibility
20459 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20460 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20461 with Ada 83, and therefore Ada 83 programs will compile
20462 and run under GNAT with
20463 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20464 provides details on specific incompatibilities.
20466 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20467 as well as the pragma @code{ADA_83}, to force the compiler to
20468 operate in Ada 83 mode. This mode does not guarantee complete
20469 conformance to Ada 83, but in practice is sufficient to
20470 eliminate most sources of incompatibilities.
20471 In particular, it eliminates the recognition of the
20472 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20473 in Ada 83 programs is legal, and handles the cases of packages
20474 with optional bodies, and generics that instantiate unconstrained
20475 types without the use of @code{(<>)}.
20477 @node Differences in the Definition of Package System
20478 @section Differences in the Definition of Package @code{System}
20481 An Ada compiler is allowed to add
20482 implementation-dependent declarations to package @code{System}.
20484 GNAT does not take advantage of this permission, and the version of
20485 @code{System} provided by GNAT exactly matches that defined in the Ada
20488 However, HP Ada adds an extensive set of declarations to package
20490 as fully documented in the HP Ada manuals. To minimize changes required
20491 for programs that make use of these extensions, GNAT provides the pragma
20492 @code{Extend_System} for extending the definition of package System. By using:
20493 @cindex pragma @code{Extend_System}
20494 @cindex @code{Extend_System} pragma
20496 @smallexample @c ada
20499 pragma Extend_System (Aux_DEC);
20505 the set of definitions in @code{System} is extended to include those in
20506 package @code{System.Aux_DEC}.
20507 @cindex @code{System.Aux_DEC} package
20508 @cindex @code{Aux_DEC} package (child of @code{System})
20509 These definitions are incorporated directly into package @code{System},
20510 as though they had been declared there. For a
20511 list of the declarations added, see the spec of this package,
20512 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20513 @cindex @file{s-auxdec.ads} file
20514 The pragma @code{Extend_System} is a configuration pragma, which means that
20515 it can be placed in the file @file{gnat.adc}, so that it will automatically
20516 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20517 for further details.
20519 An alternative approach that avoids the use of the non-standard
20520 @code{Extend_System} pragma is to add a context clause to the unit that
20521 references these facilities:
20523 @smallexample @c ada
20525 with System.Aux_DEC;
20526 use System.Aux_DEC;
20531 The effect is not quite semantically identical to incorporating
20532 the declarations directly into package @code{System},
20533 but most programs will not notice a difference
20534 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20535 to reference the entities directly in package @code{System}.
20536 For units containing such references,
20537 the prefixes must either be removed, or the pragma @code{Extend_System}
20540 @node Language-Related Features
20541 @section Language-Related Features
20544 The following sections highlight differences in types,
20545 representations of types, operations, alignment, and
20549 * Integer Types and Representations::
20550 * Floating-Point Types and Representations::
20551 * Pragmas Float_Representation and Long_Float::
20552 * Fixed-Point Types and Representations::
20553 * Record and Array Component Alignment::
20554 * Address Clauses::
20555 * Other Representation Clauses::
20558 @node Integer Types and Representations
20559 @subsection Integer Types and Representations
20562 The set of predefined integer types is identical in HP Ada and GNAT.
20563 Furthermore the representation of these integer types is also identical,
20564 including the capability of size clauses forcing biased representation.
20567 HP Ada for OpenVMS Alpha systems has defined the
20568 following additional integer types in package @code{System}:
20585 @code{LARGEST_INTEGER}
20589 In GNAT, the first four of these types may be obtained from the
20590 standard Ada package @code{Interfaces}.
20591 Alternatively, by use of the pragma @code{Extend_System}, identical
20592 declarations can be referenced directly in package @code{System}.
20593 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20595 @node Floating-Point Types and Representations
20596 @subsection Floating-Point Types and Representations
20597 @cindex Floating-Point types
20600 The set of predefined floating-point types is identical in HP Ada and GNAT.
20601 Furthermore the representation of these floating-point
20602 types is also identical. One important difference is that the default
20603 representation for HP Ada is @code{VAX_Float}, but the default representation
20606 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20607 pragma @code{Float_Representation} as described in the HP Ada
20609 For example, the declarations:
20611 @smallexample @c ada
20613 type F_Float is digits 6;
20614 pragma Float_Representation (VAX_Float, F_Float);
20619 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20621 This set of declarations actually appears in @code{System.Aux_DEC},
20623 the full set of additional floating-point declarations provided in
20624 the HP Ada version of package @code{System}.
20625 This and similar declarations may be accessed in a user program
20626 by using pragma @code{Extend_System}. The use of this
20627 pragma, and the related pragma @code{Long_Float} is described in further
20628 detail in the following section.
20630 @node Pragmas Float_Representation and Long_Float
20631 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20634 HP Ada provides the pragma @code{Float_Representation}, which
20635 acts as a program library switch to allow control over
20636 the internal representation chosen for the predefined
20637 floating-point types declared in the package @code{Standard}.
20638 The format of this pragma is as follows:
20640 @smallexample @c ada
20642 pragma Float_Representation(VAX_Float | IEEE_Float);
20647 This pragma controls the representation of floating-point
20652 @code{VAX_Float} specifies that floating-point
20653 types are represented by default with the VAX system hardware types
20654 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20655 Note that the @code{H-floating}
20656 type was available only on VAX systems, and is not available
20657 in either HP Ada or GNAT.
20660 @code{IEEE_Float} specifies that floating-point
20661 types are represented by default with the IEEE single and
20662 double floating-point types.
20666 GNAT provides an identical implementation of the pragma
20667 @code{Float_Representation}, except that it functions as a
20668 configuration pragma. Note that the
20669 notion of configuration pragma corresponds closely to the
20670 HP Ada notion of a program library switch.
20672 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20674 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20675 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20676 advisable to change the format of numbers passed to standard library
20677 routines, and if necessary explicit type conversions may be needed.
20679 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20680 efficient, and (given that it conforms to an international standard)
20681 potentially more portable.
20682 The situation in which @code{VAX_Float} may be useful is in interfacing
20683 to existing code and data that expect the use of @code{VAX_Float}.
20684 In such a situation use the predefined @code{VAX_Float}
20685 types in package @code{System}, as extended by
20686 @code{Extend_System}. For example, use @code{System.F_Float}
20687 to specify the 32-bit @code{F-Float} format.
20690 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20691 to allow control over the internal representation chosen
20692 for the predefined type @code{Long_Float} and for floating-point
20693 type declarations with digits specified in the range 7 .. 15.
20694 The format of this pragma is as follows:
20696 @smallexample @c ada
20698 pragma Long_Float (D_FLOAT | G_FLOAT);
20702 @node Fixed-Point Types and Representations
20703 @subsection Fixed-Point Types and Representations
20706 On HP Ada for OpenVMS Alpha systems, rounding is
20707 away from zero for both positive and negative numbers.
20708 Therefore, @code{+0.5} rounds to @code{1},
20709 and @code{-0.5} rounds to @code{-1}.
20711 On GNAT the results of operations
20712 on fixed-point types are in accordance with the Ada
20713 rules. In particular, results of operations on decimal
20714 fixed-point types are truncated.
20716 @node Record and Array Component Alignment
20717 @subsection Record and Array Component Alignment
20720 On HP Ada for OpenVMS Alpha, all non-composite components
20721 are aligned on natural boundaries. For example, 1-byte
20722 components are aligned on byte boundaries, 2-byte
20723 components on 2-byte boundaries, 4-byte components on 4-byte
20724 byte boundaries, and so on. The OpenVMS Alpha hardware
20725 runs more efficiently with naturally aligned data.
20727 On GNAT, alignment rules are compatible
20728 with HP Ada for OpenVMS Alpha.
20730 @node Address Clauses
20731 @subsection Address Clauses
20734 In HP Ada and GNAT, address clauses are supported for
20735 objects and imported subprograms.
20736 The predefined type @code{System.Address} is a private type
20737 in both compilers on Alpha OpenVMS, with the same representation
20738 (it is simply a machine pointer). Addition, subtraction, and comparison
20739 operations are available in the standard Ada package
20740 @code{System.Storage_Elements}, or in package @code{System}
20741 if it is extended to include @code{System.Aux_DEC} using a
20742 pragma @code{Extend_System} as previously described.
20744 Note that code that @code{with}'s both this extended package @code{System}
20745 and the package @code{System.Storage_Elements} should not @code{use}
20746 both packages, or ambiguities will result. In general it is better
20747 not to mix these two sets of facilities. The Ada package was
20748 designed specifically to provide the kind of features that HP Ada
20749 adds directly to package @code{System}.
20751 The type @code{System.Address} is a 64-bit integer type in GNAT for
20752 I64 OpenVMS. For more information,
20753 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20755 GNAT is compatible with HP Ada in its handling of address
20756 clauses, except for some limitations in
20757 the form of address clauses for composite objects with
20758 initialization. Such address clauses are easily replaced
20759 by the use of an explicitly-defined constant as described
20760 in the Ada Reference Manual (13.1(22)). For example, the sequence
20763 @smallexample @c ada
20765 X, Y : Integer := Init_Func;
20766 Q : String (X .. Y) := "abc";
20768 for Q'Address use Compute_Address;
20773 will be rejected by GNAT, since the address cannot be computed at the time
20774 that @code{Q} is declared. To achieve the intended effect, write instead:
20776 @smallexample @c ada
20779 X, Y : Integer := Init_Func;
20780 Q_Address : constant Address := Compute_Address;
20781 Q : String (X .. Y) := "abc";
20783 for Q'Address use Q_Address;
20789 which will be accepted by GNAT (and other Ada compilers), and is also
20790 compatible with Ada 83. A fuller description of the restrictions
20791 on address specifications is found in @ref{Top, GNAT Reference Manual,
20792 About This Guide, gnat_rm, GNAT Reference Manual}.
20794 @node Other Representation Clauses
20795 @subsection Other Representation Clauses
20798 GNAT implements in a compatible manner all the representation
20799 clauses supported by HP Ada. In addition, GNAT
20800 implements the representation clause forms that were introduced in Ada 95,
20801 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20803 @node The Package STANDARD
20804 @section The Package @code{STANDARD}
20807 The package @code{STANDARD}, as implemented by HP Ada, is fully
20808 described in the @cite{Ada Reference Manual} and in the
20809 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20810 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20812 In addition, HP Ada supports the Latin-1 character set in
20813 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20814 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20815 the type @code{WIDE_CHARACTER}.
20817 The floating-point types supported by GNAT are those
20818 supported by HP Ada, but the defaults are different, and are controlled by
20819 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20821 @node The Package SYSTEM
20822 @section The Package @code{SYSTEM}
20825 HP Ada provides a specific version of the package
20826 @code{SYSTEM} for each platform on which the language is implemented.
20827 For the complete spec of the package @code{SYSTEM}, see
20828 Appendix F of the @cite{HP Ada Language Reference Manual}.
20830 On HP Ada, the package @code{SYSTEM} includes the following conversion
20833 @item @code{TO_ADDRESS(INTEGER)}
20835 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20837 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20839 @item @code{TO_INTEGER(ADDRESS)}
20841 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20843 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20844 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20848 By default, GNAT supplies a version of @code{SYSTEM} that matches
20849 the definition given in the @cite{Ada Reference Manual}.
20851 is a subset of the HP system definitions, which is as
20852 close as possible to the original definitions. The only difference
20853 is that the definition of @code{SYSTEM_NAME} is different:
20855 @smallexample @c ada
20857 type Name is (SYSTEM_NAME_GNAT);
20858 System_Name : constant Name := SYSTEM_NAME_GNAT;
20863 Also, GNAT adds the Ada declarations for
20864 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20866 However, the use of the following pragma causes GNAT
20867 to extend the definition of package @code{SYSTEM} so that it
20868 encompasses the full set of HP-specific extensions,
20869 including the functions listed above:
20871 @smallexample @c ada
20873 pragma Extend_System (Aux_DEC);
20878 The pragma @code{Extend_System} is a configuration pragma that
20879 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20880 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20882 HP Ada does not allow the recompilation of the package
20883 @code{SYSTEM}. Instead HP Ada provides several pragmas
20884 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20885 to modify values in the package @code{SYSTEM}.
20886 On OpenVMS Alpha systems, the pragma
20887 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20888 its single argument.
20890 GNAT does permit the recompilation of package @code{SYSTEM} using
20891 the special switch @option{-gnatg}, and this switch can be used if
20892 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20893 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20894 or @code{MEMORY_SIZE} by any other means.
20896 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20897 enumeration literal @code{SYSTEM_NAME_GNAT}.
20899 The definitions provided by the use of
20901 @smallexample @c ada
20902 pragma Extend_System (AUX_Dec);
20906 are virtually identical to those provided by the HP Ada 83 package
20907 @code{SYSTEM}. One important difference is that the name of the
20909 function for type @code{UNSIGNED_LONGWORD} is changed to
20910 @code{TO_ADDRESS_LONG}.
20911 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20912 discussion of why this change was necessary.
20915 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20917 an extension to Ada 83 not strictly compatible with the reference manual.
20918 GNAT, in order to be exactly compatible with the standard,
20919 does not provide this capability. In HP Ada 83, the
20920 point of this definition is to deal with a call like:
20922 @smallexample @c ada
20923 TO_ADDRESS (16#12777#);
20927 Normally, according to Ada 83 semantics, one would expect this to be
20928 ambiguous, since it matches both the @code{INTEGER} and
20929 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20930 However, in HP Ada 83, there is no ambiguity, since the
20931 definition using @i{universal_integer} takes precedence.
20933 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20935 not possible to be 100% compatible. Since there are many programs using
20936 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20938 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20939 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20941 @smallexample @c ada
20942 function To_Address (X : Integer) return Address;
20943 pragma Pure_Function (To_Address);
20945 function To_Address_Long (X : Unsigned_Longword) return Address;
20946 pragma Pure_Function (To_Address_Long);
20950 This means that programs using @code{TO_ADDRESS} for
20951 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20953 @node Tasking and Task-Related Features
20954 @section Tasking and Task-Related Features
20957 This section compares the treatment of tasking in GNAT
20958 and in HP Ada for OpenVMS Alpha.
20959 The GNAT description applies to both Alpha and I64 OpenVMS.
20960 For detailed information on tasking in
20961 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20962 relevant run-time reference manual.
20965 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20966 * Assigning Task IDs::
20967 * Task IDs and Delays::
20968 * Task-Related Pragmas::
20969 * Scheduling and Task Priority::
20971 * External Interrupts::
20974 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20975 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20978 On OpenVMS Alpha systems, each Ada task (except a passive
20979 task) is implemented as a single stream of execution
20980 that is created and managed by the kernel. On these
20981 systems, HP Ada tasking support is based on DECthreads,
20982 an implementation of the POSIX standard for threads.
20984 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20985 code that calls DECthreads routines can be used together.
20986 The interaction between Ada tasks and DECthreads routines
20987 can have some benefits. For example when on OpenVMS Alpha,
20988 HP Ada can call C code that is already threaded.
20990 GNAT uses the facilities of DECthreads,
20991 and Ada tasks are mapped to threads.
20993 @node Assigning Task IDs
20994 @subsection Assigning Task IDs
20997 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20998 the environment task that executes the main program. On
20999 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21000 that have been created but are not yet activated.
21002 On OpenVMS Alpha systems, task IDs are assigned at
21003 activation. On GNAT systems, task IDs are also assigned at
21004 task creation but do not have the same form or values as
21005 task ID values in HP Ada. There is no null task, and the
21006 environment task does not have a specific task ID value.
21008 @node Task IDs and Delays
21009 @subsection Task IDs and Delays
21012 On OpenVMS Alpha systems, tasking delays are implemented
21013 using Timer System Services. The Task ID is used for the
21014 identification of the timer request (the @code{REQIDT} parameter).
21015 If Timers are used in the application take care not to use
21016 @code{0} for the identification, because cancelling such a timer
21017 will cancel all timers and may lead to unpredictable results.
21019 @node Task-Related Pragmas
21020 @subsection Task-Related Pragmas
21023 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21024 specification of the size of the guard area for a task
21025 stack. (The guard area forms an area of memory that has no
21026 read or write access and thus helps in the detection of
21027 stack overflow.) On OpenVMS Alpha systems, if the pragma
21028 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21029 area is created. In the absence of a pragma @code{TASK_STORAGE},
21030 a default guard area is created.
21032 GNAT supplies the following task-related pragmas:
21035 @item @code{TASK_INFO}
21037 This pragma appears within a task definition and
21038 applies to the task in which it appears. The argument
21039 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21041 @item @code{TASK_STORAGE}
21043 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
21044 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21045 @code{SUPPRESS}, and @code{VOLATILE}.
21047 @node Scheduling and Task Priority
21048 @subsection Scheduling and Task Priority
21051 HP Ada implements the Ada language requirement that
21052 when two tasks are eligible for execution and they have
21053 different priorities, the lower priority task does not
21054 execute while the higher priority task is waiting. The HP
21055 Ada Run-Time Library keeps a task running until either the
21056 task is suspended or a higher priority task becomes ready.
21058 On OpenVMS Alpha systems, the default strategy is round-
21059 robin with preemption. Tasks of equal priority take turns
21060 at the processor. A task is run for a certain period of
21061 time and then placed at the tail of the ready queue for
21062 its priority level.
21064 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21065 which can be used to enable or disable round-robin
21066 scheduling of tasks with the same priority.
21067 See the relevant HP Ada run-time reference manual for
21068 information on using the pragmas to control HP Ada task
21071 GNAT follows the scheduling rules of Annex D (Real-Time
21072 Annex) of the @cite{Ada Reference Manual}. In general, this
21073 scheduling strategy is fully compatible with HP Ada
21074 although it provides some additional constraints (as
21075 fully documented in Annex D).
21076 GNAT implements time slicing control in a manner compatible with
21077 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21078 are identical to the HP Ada 83 pragma of the same name.
21079 Note that it is not possible to mix GNAT tasking and
21080 HP Ada 83 tasking in the same program, since the two run-time
21081 libraries are not compatible.
21083 @node The Task Stack
21084 @subsection The Task Stack
21087 In HP Ada, a task stack is allocated each time a
21088 non-passive task is activated. As soon as the task is
21089 terminated, the storage for the task stack is deallocated.
21090 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21091 a default stack size is used. Also, regardless of the size
21092 specified, some additional space is allocated for task
21093 management purposes. On OpenVMS Alpha systems, at least
21094 one page is allocated.
21096 GNAT handles task stacks in a similar manner. In accordance with
21097 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
21098 an alternative method for controlling the task stack size.
21099 The specification of the attribute @code{T'STORAGE_SIZE} is also
21100 supported in a manner compatible with HP Ada.
21102 @node External Interrupts
21103 @subsection External Interrupts
21106 On HP Ada, external interrupts can be associated with task entries.
21107 GNAT is compatible with HP Ada in its handling of external interrupts.
21109 @node Pragmas and Pragma-Related Features
21110 @section Pragmas and Pragma-Related Features
21113 Both HP Ada and GNAT supply all language-defined pragmas
21114 as specified by the Ada 83 standard. GNAT also supplies all
21115 language-defined pragmas introduced by Ada 95 and Ada 2005.
21116 In addition, GNAT implements the implementation-defined pragmas
21120 @item @code{AST_ENTRY}
21122 @item @code{COMMON_OBJECT}
21124 @item @code{COMPONENT_ALIGNMENT}
21126 @item @code{EXPORT_EXCEPTION}
21128 @item @code{EXPORT_FUNCTION}
21130 @item @code{EXPORT_OBJECT}
21132 @item @code{EXPORT_PROCEDURE}
21134 @item @code{EXPORT_VALUED_PROCEDURE}
21136 @item @code{FLOAT_REPRESENTATION}
21140 @item @code{IMPORT_EXCEPTION}
21142 @item @code{IMPORT_FUNCTION}
21144 @item @code{IMPORT_OBJECT}
21146 @item @code{IMPORT_PROCEDURE}
21148 @item @code{IMPORT_VALUED_PROCEDURE}
21150 @item @code{INLINE_GENERIC}
21152 @item @code{INTERFACE_NAME}
21154 @item @code{LONG_FLOAT}
21156 @item @code{MAIN_STORAGE}
21158 @item @code{PASSIVE}
21160 @item @code{PSECT_OBJECT}
21162 @item @code{SHARE_GENERIC}
21164 @item @code{SUPPRESS_ALL}
21166 @item @code{TASK_STORAGE}
21168 @item @code{TIME_SLICE}
21174 These pragmas are all fully implemented, with the exception of @code{TITLE},
21175 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21176 recognized, but which have no
21177 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21178 use of Ada protected objects. In GNAT, all generics are inlined.
21180 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21181 a separate subprogram specification which must appear before the
21184 GNAT also supplies a number of implementation-defined pragmas including the
21188 @item @code{ABORT_DEFER}
21190 @item @code{ADA_83}
21192 @item @code{ADA_95}
21194 @item @code{ADA_05}
21196 @item @code{Ada_2005}
21198 @item @code{Ada_12}
21200 @item @code{Ada_2012}
21202 @item @code{ANNOTATE}
21204 @item @code{ASSERT}
21206 @item @code{C_PASS_BY_COPY}
21208 @item @code{CPP_CLASS}
21210 @item @code{CPP_CONSTRUCTOR}
21212 @item @code{CPP_DESTRUCTOR}
21216 @item @code{EXTEND_SYSTEM}
21218 @item @code{LINKER_ALIAS}
21220 @item @code{LINKER_SECTION}
21222 @item @code{MACHINE_ATTRIBUTE}
21224 @item @code{NO_RETURN}
21226 @item @code{PURE_FUNCTION}
21228 @item @code{SOURCE_FILE_NAME}
21230 @item @code{SOURCE_REFERENCE}
21232 @item @code{TASK_INFO}
21234 @item @code{UNCHECKED_UNION}
21236 @item @code{UNIMPLEMENTED_UNIT}
21238 @item @code{UNIVERSAL_DATA}
21240 @item @code{UNSUPPRESS}
21242 @item @code{WARNINGS}
21244 @item @code{WEAK_EXTERNAL}
21248 For full details on these and other GNAT implementation-defined pragmas,
21249 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21253 * Restrictions on the Pragma INLINE::
21254 * Restrictions on the Pragma INTERFACE::
21255 * Restrictions on the Pragma SYSTEM_NAME::
21258 @node Restrictions on the Pragma INLINE
21259 @subsection Restrictions on Pragma @code{INLINE}
21262 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21264 @item Parameters cannot have a task type.
21266 @item Function results cannot be task types, unconstrained
21267 array types, or unconstrained types with discriminants.
21269 @item Bodies cannot declare the following:
21271 @item Subprogram body or stub (imported subprogram is allowed)
21275 @item Generic declarations
21277 @item Instantiations
21281 @item Access types (types derived from access types allowed)
21283 @item Array or record types
21285 @item Dependent tasks
21287 @item Direct recursive calls of subprogram or containing
21288 subprogram, directly or via a renaming
21294 In GNAT, the only restriction on pragma @code{INLINE} is that the
21295 body must occur before the call if both are in the same
21296 unit, and the size must be appropriately small. There are
21297 no other specific restrictions which cause subprograms to
21298 be incapable of being inlined.
21300 @node Restrictions on the Pragma INTERFACE
21301 @subsection Restrictions on Pragma @code{INTERFACE}
21304 The following restrictions on pragma @code{INTERFACE}
21305 are enforced by both HP Ada and GNAT:
21307 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
21308 Default is the default on OpenVMS Alpha systems.
21310 @item Parameter passing: Language specifies default
21311 mechanisms but can be overridden with an @code{EXPORT} pragma.
21314 @item Ada: Use internal Ada rules.
21316 @item Bliss, C: Parameters must be mode @code{in}; cannot be
21317 record or task type. Result cannot be a string, an
21318 array, or a record.
21320 @item Fortran: Parameters cannot have a task type. Result cannot
21321 be a string, an array, or a record.
21326 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21327 record parameters for all languages.
21329 @node Restrictions on the Pragma SYSTEM_NAME
21330 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
21333 For HP Ada for OpenVMS Alpha, the enumeration literal
21334 for the type @code{NAME} is @code{OPENVMS_AXP}.
21335 In GNAT, the enumeration
21336 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21338 @node Library of Predefined Units
21339 @section Library of Predefined Units
21342 A library of predefined units is provided as part of the
21343 HP Ada and GNAT implementations. HP Ada does not provide
21344 the package @code{MACHINE_CODE} but instead recommends importing
21347 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21348 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21350 The HP Ada Predefined Library units are modified to remove post-Ada 83
21351 incompatibilities and to make them interoperable with GNAT
21352 (@pxref{Changes to DECLIB}, for details).
21353 The units are located in the @file{DECLIB} directory.
21355 The GNAT RTL is contained in
21356 the @file{ADALIB} directory, and
21357 the default search path is set up to find @code{DECLIB} units in preference
21358 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21359 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21362 * Changes to DECLIB::
21365 @node Changes to DECLIB
21366 @subsection Changes to @code{DECLIB}
21369 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21370 compatibility are minor and include the following:
21373 @item Adjusting the location of pragmas and record representation
21374 clauses to obey Ada 95 (and thus Ada 2005) rules
21376 @item Adding the proper notation to generic formal parameters
21377 that take unconstrained types in instantiation
21379 @item Adding pragma @code{ELABORATE_BODY} to package specs
21380 that have package bodies not otherwise allowed
21382 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21383 ``@code{PROTECTD}''.
21384 Currently these are found only in the @code{STARLET} package spec.
21386 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21387 where the address size is constrained to 32 bits.
21391 None of the above changes is visible to users.
21397 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21400 @item Command Language Interpreter (CLI interface)
21402 @item DECtalk Run-Time Library (DTK interface)
21404 @item Librarian utility routines (LBR interface)
21406 @item General Purpose Run-Time Library (LIB interface)
21408 @item Math Run-Time Library (MTH interface)
21410 @item National Character Set Run-Time Library (NCS interface)
21412 @item Compiled Code Support Run-Time Library (OTS interface)
21414 @item Parallel Processing Run-Time Library (PPL interface)
21416 @item Screen Management Run-Time Library (SMG interface)
21418 @item Sort Run-Time Library (SOR interface)
21420 @item String Run-Time Library (STR interface)
21422 @item STARLET System Library
21425 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
21427 @item X Windows Toolkit (XT interface)
21429 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
21433 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21434 directory, on both the Alpha and I64 OpenVMS platforms.
21436 The X components of DECLIB compatibility package are located in a separate
21437 library, called XDECGNAT, which is not linked with by default; this library
21438 must be explicitly linked with any application that makes use of any X facilities,
21439 with a command similar to
21441 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21443 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21445 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21446 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21447 @code{Xt}, and @code{X_Lib}
21448 causing the default X/Motif sharable image libraries to be linked in. This
21449 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21450 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21452 It may be necessary to edit these options files to update or correct the
21453 library names if, for example, the newer X/Motif bindings from
21454 @file{ADA$EXAMPLES}
21455 had been (previous to installing GNAT) copied and renamed to supersede the
21456 default @file{ADA$PREDEFINED} versions.
21459 * Shared Libraries and Options Files::
21460 * Interfaces to C::
21463 @node Shared Libraries and Options Files
21464 @subsection Shared Libraries and Options Files
21467 When using the HP Ada
21468 predefined X and Motif bindings, the linking with their sharable images is
21469 done automatically by @command{GNAT LINK}.
21470 When using other X and Motif bindings, you need
21471 to add the corresponding sharable images to the command line for
21472 @code{GNAT LINK}. When linking with shared libraries, or with
21473 @file{.OPT} files, you must
21474 also add them to the command line for @command{GNAT LINK}.
21476 A shared library to be used with GNAT is built in the same way as other
21477 libraries under VMS. The VMS Link command can be used in standard fashion.
21479 @node Interfaces to C
21480 @subsection Interfaces to C
21484 provides the following Ada types and operations:
21487 @item C types package (@code{C_TYPES})
21489 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21491 @item Other_types (@code{SHORT_INT})
21495 Interfacing to C with GNAT, you can use the above approach
21496 described for HP Ada or the facilities of Annex B of
21497 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21498 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21499 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21501 The @option{-gnatF} qualifier forces default and explicit
21502 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21503 to be uppercased for compatibility with the default behavior
21504 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21506 @node Main Program Definition
21507 @section Main Program Definition
21510 The following section discusses differences in the
21511 definition of main programs on HP Ada and GNAT.
21512 On HP Ada, main programs are defined to meet the
21513 following conditions:
21515 @item Procedure with no formal parameters (returns @code{0} upon
21518 @item Procedure with no formal parameters (returns @code{42} when
21519 an unhandled exception is raised)
21521 @item Function with no formal parameters whose returned value
21522 is of a discrete type
21524 @item Procedure with one @code{out} formal of a discrete type for
21525 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21530 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21531 a main function or main procedure returns a discrete
21532 value whose size is less than 64 bits (32 on VAX systems),
21533 the value is zero- or sign-extended as appropriate.
21534 On GNAT, main programs are defined as follows:
21536 @item Must be a non-generic, parameterless subprogram that
21537 is either a procedure or function returning an Ada
21538 @code{STANDARD.INTEGER} (the predefined type)
21540 @item Cannot be a generic subprogram or an instantiation of a
21544 @node Implementation-Defined Attributes
21545 @section Implementation-Defined Attributes
21548 GNAT provides all HP Ada implementation-defined
21551 @node Compiler and Run-Time Interfacing
21552 @section Compiler and Run-Time Interfacing
21555 HP Ada provides the following qualifiers to pass options to the linker
21558 @item @option{/WAIT} and @option{/SUBMIT}
21560 @item @option{/COMMAND}
21562 @item @option{/@r{[}NO@r{]}MAP}
21564 @item @option{/OUTPUT=@var{file-spec}}
21566 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21570 To pass options to the linker, GNAT provides the following
21574 @item @option{/EXECUTABLE=@var{exec-name}}
21576 @item @option{/VERBOSE}
21578 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21582 For more information on these switches, see
21583 @ref{Switches for gnatlink}.
21584 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21585 to control optimization. HP Ada also supplies the
21588 @item @code{OPTIMIZE}
21590 @item @code{INLINE}
21592 @item @code{INLINE_GENERIC}
21594 @item @code{SUPPRESS_ALL}
21596 @item @code{PASSIVE}
21600 In GNAT, optimization is controlled strictly by command
21601 line parameters, as described in the corresponding section of this guide.
21602 The HP pragmas for control of optimization are
21603 recognized but ignored.
21605 Note that in GNAT, the default is optimization off, whereas in HP Ada
21606 the default is that optimization is turned on.
21608 @node Program Compilation and Library Management
21609 @section Program Compilation and Library Management
21612 HP Ada and GNAT provide a comparable set of commands to
21613 build programs. HP Ada also provides a program library,
21614 which is a concept that does not exist on GNAT. Instead,
21615 GNAT provides directories of sources that are compiled as
21618 The following table summarizes
21619 the HP Ada commands and provides
21620 equivalent GNAT commands. In this table, some GNAT
21621 equivalents reflect the fact that GNAT does not use the
21622 concept of a program library. Instead, it uses a model
21623 in which collections of source and object files are used
21624 in a manner consistent with other languages like C and
21625 Fortran. Therefore, standard system file commands are used
21626 to manipulate these elements. Those GNAT commands are marked with
21628 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21631 @multitable @columnfractions .35 .65
21633 @item @emph{HP Ada Command}
21634 @tab @emph{GNAT Equivalent / Description}
21636 @item @command{ADA}
21637 @tab @command{GNAT COMPILE}@*
21638 Invokes the compiler to compile one or more Ada source files.
21640 @item @command{ACS ATTACH}@*
21641 @tab [No equivalent]@*
21642 Switches control of terminal from current process running the program
21645 @item @command{ACS CHECK}
21646 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21647 Forms the execution closure of one
21648 or more compiled units and checks completeness and currency.
21650 @item @command{ACS COMPILE}
21651 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21652 Forms the execution closure of one or
21653 more specified units, checks completeness and currency,
21654 identifies units that have revised source files, compiles same,
21655 and recompiles units that are or will become obsolete.
21656 Also completes incomplete generic instantiations.
21658 @item @command{ACS COPY FOREIGN}
21660 Copies a foreign object file into the program library as a
21663 @item @command{ACS COPY UNIT}
21665 Copies a compiled unit from one program library to another.
21667 @item @command{ACS CREATE LIBRARY}
21668 @tab Create /directory (*)@*
21669 Creates a program library.
21671 @item @command{ACS CREATE SUBLIBRARY}
21672 @tab Create /directory (*)@*
21673 Creates a program sublibrary.
21675 @item @command{ACS DELETE LIBRARY}
21677 Deletes a program library and its contents.
21679 @item @command{ACS DELETE SUBLIBRARY}
21681 Deletes a program sublibrary and its contents.
21683 @item @command{ACS DELETE UNIT}
21684 @tab Delete file (*)@*
21685 On OpenVMS systems, deletes one or more compiled units from
21686 the current program library.
21688 @item @command{ACS DIRECTORY}
21689 @tab Directory (*)@*
21690 On OpenVMS systems, lists units contained in the current
21693 @item @command{ACS ENTER FOREIGN}
21695 Allows the import of a foreign body as an Ada library
21696 spec and enters a reference to a pointer.
21698 @item @command{ACS ENTER UNIT}
21700 Enters a reference (pointer) from the current program library to
21701 a unit compiled into another program library.
21703 @item @command{ACS EXIT}
21704 @tab [No equivalent]@*
21705 Exits from the program library manager.
21707 @item @command{ACS EXPORT}
21709 Creates an object file that contains system-specific object code
21710 for one or more units. With GNAT, object files can simply be copied
21711 into the desired directory.
21713 @item @command{ACS EXTRACT SOURCE}
21715 Allows access to the copied source file for each Ada compilation unit
21717 @item @command{ACS HELP}
21718 @tab @command{HELP GNAT}@*
21719 Provides online help.
21721 @item @command{ACS LINK}
21722 @tab @command{GNAT LINK}@*
21723 Links an object file containing Ada units into an executable file.
21725 @item @command{ACS LOAD}
21727 Loads (partially compiles) Ada units into the program library.
21728 Allows loading a program from a collection of files into a library
21729 without knowing the relationship among units.
21731 @item @command{ACS MERGE}
21733 Merges into the current program library, one or more units from
21734 another library where they were modified.
21736 @item @command{ACS RECOMPILE}
21737 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21738 Recompiles from external or copied source files any obsolete
21739 unit in the closure. Also, completes any incomplete generic
21742 @item @command{ACS REENTER}
21743 @tab @command{GNAT MAKE}@*
21744 Reenters current references to units compiled after last entered
21745 with the @command{ACS ENTER UNIT} command.
21747 @item @command{ACS SET LIBRARY}
21748 @tab Set default (*)@*
21749 Defines a program library to be the compilation context as well
21750 as the target library for compiler output and commands in general.
21752 @item @command{ACS SET PRAGMA}
21753 @tab Edit @file{gnat.adc} (*)@*
21754 Redefines specified values of the library characteristics
21755 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21756 and @code{Float_Representation}.
21758 @item @command{ACS SET SOURCE}
21759 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21760 Defines the source file search list for the @command{ACS COMPILE} command.
21762 @item @command{ACS SHOW LIBRARY}
21763 @tab Directory (*)@*
21764 Lists information about one or more program libraries.
21766 @item @command{ACS SHOW PROGRAM}
21767 @tab [No equivalent]@*
21768 Lists information about the execution closure of one or
21769 more units in the program library.
21771 @item @command{ACS SHOW SOURCE}
21772 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21773 Shows the source file search used when compiling units.
21775 @item @command{ACS SHOW VERSION}
21776 @tab Compile with @option{VERBOSE} option
21777 Displays the version number of the compiler and program library
21780 @item @command{ACS SPAWN}
21781 @tab [No equivalent]@*
21782 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21785 @item @command{ACS VERIFY}
21786 @tab [No equivalent]@*
21787 Performs a series of consistency checks on a program library to
21788 determine whether the library structure and library files are in
21795 @section Input-Output
21798 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21799 Management Services (RMS) to perform operations on
21803 HP Ada and GNAT predefine an identical set of input-
21804 output packages. To make the use of the
21805 generic @code{TEXT_IO} operations more convenient, HP Ada
21806 provides predefined library packages that instantiate the
21807 integer and floating-point operations for the predefined
21808 integer and floating-point types as shown in the following table.
21810 @multitable @columnfractions .45 .55
21811 @item @emph{Package Name} @tab Instantiation
21813 @item @code{INTEGER_TEXT_IO}
21814 @tab @code{INTEGER_IO(INTEGER)}
21816 @item @code{SHORT_INTEGER_TEXT_IO}
21817 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21819 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21820 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21822 @item @code{FLOAT_TEXT_IO}
21823 @tab @code{FLOAT_IO(FLOAT)}
21825 @item @code{LONG_FLOAT_TEXT_IO}
21826 @tab @code{FLOAT_IO(LONG_FLOAT)}
21830 The HP Ada predefined packages and their operations
21831 are implemented using OpenVMS Alpha files and input-output
21832 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21833 Familiarity with the following is recommended:
21835 @item RMS file organizations and access methods
21837 @item OpenVMS file specifications and directories
21839 @item OpenVMS File Definition Language (FDL)
21843 GNAT provides I/O facilities that are completely
21844 compatible with HP Ada. The distribution includes the
21845 standard HP Ada versions of all I/O packages, operating
21846 in a manner compatible with HP Ada. In particular, the
21847 following packages are by default the HP Ada (Ada 83)
21848 versions of these packages rather than the renamings
21849 suggested in Annex J of the Ada Reference Manual:
21851 @item @code{TEXT_IO}
21853 @item @code{SEQUENTIAL_IO}
21855 @item @code{DIRECT_IO}
21859 The use of the standard child package syntax (for
21860 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21862 GNAT provides HP-compatible predefined instantiations
21863 of the @code{TEXT_IO} packages, and also
21864 provides the standard predefined instantiations required
21865 by the @cite{Ada Reference Manual}.
21867 For further information on how GNAT interfaces to the file
21868 system or how I/O is implemented in programs written in
21869 mixed languages, see @ref{Implementation of the Standard I/O,,,
21870 gnat_rm, GNAT Reference Manual}.
21871 This chapter covers the following:
21873 @item Standard I/O packages
21875 @item @code{FORM} strings
21877 @item @code{ADA.DIRECT_IO}
21879 @item @code{ADA.SEQUENTIAL_IO}
21881 @item @code{ADA.TEXT_IO}
21883 @item Stream pointer positioning
21885 @item Reading and writing non-regular files
21887 @item @code{GET_IMMEDIATE}
21889 @item Treating @code{TEXT_IO} files as streams
21896 @node Implementation Limits
21897 @section Implementation Limits
21900 The following table lists implementation limits for HP Ada
21902 @multitable @columnfractions .60 .20 .20
21904 @item @emph{Compilation Parameter}
21909 @item In a subprogram or entry declaration, maximum number of
21910 formal parameters that are of an unconstrained record type
21915 @item Maximum identifier length (number of characters)
21920 @item Maximum number of characters in a source line
21925 @item Maximum collection size (number of bytes)
21930 @item Maximum number of discriminants for a record type
21935 @item Maximum number of formal parameters in an entry or
21936 subprogram declaration
21941 @item Maximum number of dimensions in an array type
21946 @item Maximum number of library units and subunits in a compilation.
21951 @item Maximum number of library units and subunits in an execution.
21956 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21957 or @code{PSECT_OBJECT}
21962 @item Maximum number of enumeration literals in an enumeration type
21968 @item Maximum number of lines in a source file
21973 @item Maximum number of bits in any object
21978 @item Maximum size of the static portion of a stack frame (approximate)
21983 @node Tools and Utilities
21984 @section Tools and Utilities
21987 The following table lists some of the OpenVMS development tools
21988 available for HP Ada, and the corresponding tools for
21989 use with @value{EDITION} on Alpha and I64 platforms.
21990 Aside from the debugger, all the OpenVMS tools identified are part
21991 of the DECset package.
21994 @c Specify table in TeX since Texinfo does a poor job
21998 \settabs\+Language-Sensitive Editor\quad
21999 &Product with HP Ada\quad
22002 &\it Product with HP Ada
22003 & \it Product with @value{EDITION}\cr
22005 \+Code Management System
22009 \+Language-Sensitive Editor
22011 & emacs or HP LSE (Alpha)\cr
22021 & OpenVMS Debug (I64)\cr
22023 \+Source Code Analyzer /
22040 \+Coverage Analyzer
22044 \+Module Management
22046 & Not applicable\cr
22056 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
22057 @c the TeX version above for the printed version
22059 @c @multitable @columnfractions .3 .4 .4
22060 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22062 @tab @i{Tool with HP Ada}
22063 @tab @i{Tool with @value{EDITION}}
22064 @item Code Management@*System
22067 @item Language-Sensitive@*Editor
22069 @tab emacs or HP LSE (Alpha)
22078 @tab OpenVMS Debug (I64)
22079 @item Source Code Analyzer /@*Cross Referencer
22083 @tab HP Digital Test@*Manager (DTM)
22085 @item Performance and@*Coverage Analyzer
22088 @item Module Management@*System
22090 @tab Not applicable
22097 @c **************************************
22098 @node Platform-Specific Information for the Run-Time Libraries
22099 @appendix Platform-Specific Information for the Run-Time Libraries
22100 @cindex Tasking and threads libraries
22101 @cindex Threads libraries and tasking
22102 @cindex Run-time libraries (platform-specific information)
22105 The GNAT run-time implementation may vary with respect to both the
22106 underlying threads library and the exception handling scheme.
22107 For threads support, one or more of the following are supplied:
22109 @item @b{native threads library}, a binding to the thread package from
22110 the underlying operating system
22112 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22113 POSIX thread package
22117 For exception handling, either or both of two models are supplied:
22119 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22120 Most programs should experience a substantial speed improvement by
22121 being compiled with a ZCX run-time.
22122 This is especially true for
22123 tasking applications or applications with many exception handlers.}
22124 @cindex Zero-Cost Exceptions
22125 @cindex ZCX (Zero-Cost Exceptions)
22126 which uses binder-generated tables that
22127 are interrogated at run time to locate a handler
22129 @item @b{setjmp / longjmp} (``SJLJ''),
22130 @cindex setjmp/longjmp Exception Model
22131 @cindex SJLJ (setjmp/longjmp Exception Model)
22132 which uses dynamically-set data to establish
22133 the set of handlers
22137 This appendix summarizes which combinations of threads and exception support
22138 are supplied on various GNAT platforms.
22139 It then shows how to select a particular library either
22140 permanently or temporarily,
22141 explains the properties of (and tradeoffs among) the various threads
22142 libraries, and provides some additional
22143 information about several specific platforms.
22146 * Summary of Run-Time Configurations::
22147 * Specifying a Run-Time Library::
22148 * Choosing the Scheduling Policy::
22149 * Solaris-Specific Considerations::
22150 * Linux-Specific Considerations::
22151 * AIX-Specific Considerations::
22152 * Irix-Specific Considerations::
22153 * RTX-Specific Considerations::
22154 * HP-UX-Specific Considerations::
22157 @node Summary of Run-Time Configurations
22158 @section Summary of Run-Time Configurations
22160 @multitable @columnfractions .30 .70
22161 @item @b{alpha-openvms}
22162 @item @code{@ @ }@i{rts-native (default)}
22163 @item @code{@ @ @ @ }Tasking @tab native VMS threads
22164 @item @code{@ @ @ @ }Exceptions @tab ZCX
22166 @item @b{alpha-tru64}
22167 @item @code{@ @ }@i{rts-native (default)}
22168 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
22169 @item @code{@ @ @ @ }Exceptions @tab ZCX
22171 @item @code{@ @ }@i{rts-sjlj}
22172 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
22173 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22175 @item @b{ia64-hp_linux}
22176 @item @code{@ @ }@i{rts-native (default)}
22177 @item @code{@ @ @ @ }Tasking @tab pthread library
22178 @item @code{@ @ @ @ }Exceptions @tab ZCX
22180 @item @b{ia64-hpux}
22181 @item @code{@ @ }@i{rts-native (default)}
22182 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22183 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22185 @item @b{ia64-openvms}
22186 @item @code{@ @ }@i{rts-native (default)}
22187 @item @code{@ @ @ @ }Tasking @tab native VMS threads
22188 @item @code{@ @ @ @ }Exceptions @tab ZCX
22190 @item @b{ia64-sgi_linux}
22191 @item @code{@ @ }@i{rts-native (default)}
22192 @item @code{@ @ @ @ }Tasking @tab pthread library
22193 @item @code{@ @ @ @ }Exceptions @tab ZCX
22195 @item @b{mips-irix}
22196 @item @code{@ @ }@i{rts-native (default)}
22197 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
22198 @item @code{@ @ @ @ }Exceptions @tab ZCX
22201 @item @code{@ @ }@i{rts-native (default)}
22202 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22203 @item @code{@ @ @ @ }Exceptions @tab ZCX
22205 @item @code{@ @ }@i{rts-sjlj}
22206 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
22207 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22210 @item @code{@ @ }@i{rts-native (default)}
22211 @item @code{@ @ @ @ }Tasking @tab native AIX threads
22212 @item @code{@ @ @ @ }Exceptions @tab ZCX
22214 @item @code{@ @ }@i{rts-sjlj}
22215 @item @code{@ @ @ @ }Tasking @tab native AIX threads
22216 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22218 @item @b{ppc-darwin}
22219 @item @code{@ @ }@i{rts-native (default)}
22220 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
22221 @item @code{@ @ @ @ }Exceptions @tab ZCX
22223 @item @b{sparc-solaris} @tab
22224 @item @code{@ @ }@i{rts-native (default)}
22225 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22226 @item @code{@ @ @ @ }Exceptions @tab ZCX
22228 @item @code{@ @ }@i{rts-pthread}
22229 @item @code{@ @ @ @ }Tasking @tab pthread library
22230 @item @code{@ @ @ @ }Exceptions @tab ZCX
22232 @item @code{@ @ }@i{rts-sjlj}
22233 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22234 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22236 @item @b{sparc64-solaris} @tab
22237 @item @code{@ @ }@i{rts-native (default)}
22238 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22239 @item @code{@ @ @ @ }Exceptions @tab ZCX
22241 @item @b{x86-linux}
22242 @item @code{@ @ }@i{rts-native (default)}
22243 @item @code{@ @ @ @ }Tasking @tab pthread library
22244 @item @code{@ @ @ @ }Exceptions @tab ZCX
22246 @item @code{@ @ }@i{rts-sjlj}
22247 @item @code{@ @ @ @ }Tasking @tab pthread library
22248 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22251 @item @code{@ @ }@i{rts-native (default)}
22252 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
22253 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22255 @item @b{x86-solaris}
22256 @item @code{@ @ }@i{rts-native (default)}
22257 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
22258 @item @code{@ @ @ @ }Exceptions @tab ZCX
22260 @item @code{@ @ }@i{rts-sjlj}
22261 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
22262 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22264 @item @b{x86-windows}
22265 @item @code{@ @ }@i{rts-native (default)}
22266 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
22267 @item @code{@ @ @ @ }Exceptions @tab ZCX
22269 @item @code{@ @ }@i{rts-sjlj}
22270 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
22271 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22273 @item @b{x86-windows-rtx}
22274 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22275 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
22276 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22278 @item @code{@ @ }@i{rts-rtx-w32}
22279 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
22280 @item @code{@ @ @ @ }Exceptions @tab ZCX
22282 @item @b{x86_64-linux}
22283 @item @code{@ @ }@i{rts-native (default)}
22284 @item @code{@ @ @ @ }Tasking @tab pthread library
22285 @item @code{@ @ @ @ }Exceptions @tab ZCX
22287 @item @code{@ @ }@i{rts-sjlj}
22288 @item @code{@ @ @ @ }Tasking @tab pthread library
22289 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22293 @node Specifying a Run-Time Library
22294 @section Specifying a Run-Time Library
22297 The @file{adainclude} subdirectory containing the sources of the GNAT
22298 run-time library, and the @file{adalib} subdirectory containing the
22299 @file{ALI} files and the static and/or shared GNAT library, are located
22300 in the gcc target-dependent area:
22303 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22307 As indicated above, on some platforms several run-time libraries are supplied.
22308 These libraries are installed in the target dependent area and
22309 contain a complete source and binary subdirectory. The detailed description
22310 below explains the differences between the different libraries in terms of
22311 their thread support.
22313 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22314 This default run time is selected by the means of soft links.
22315 For example on x86-linux:
22321 +--- adainclude----------+
22323 +--- adalib-----------+ |
22325 +--- rts-native | |
22327 | +--- adainclude <---+
22329 | +--- adalib <----+
22340 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22341 these soft links can be modified with the following commands:
22345 $ rm -f adainclude adalib
22346 $ ln -s rts-sjlj/adainclude adainclude
22347 $ ln -s rts-sjlj/adalib adalib
22351 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22352 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22353 @file{$target/ada_object_path}.
22355 Selecting another run-time library temporarily can be
22356 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22357 @cindex @option{--RTS} option
22359 @node Choosing the Scheduling Policy
22360 @section Choosing the Scheduling Policy
22363 When using a POSIX threads implementation, you have a choice of several
22364 scheduling policies: @code{SCHED_FIFO},
22365 @cindex @code{SCHED_FIFO} scheduling policy
22367 @cindex @code{SCHED_RR} scheduling policy
22368 and @code{SCHED_OTHER}.
22369 @cindex @code{SCHED_OTHER} scheduling policy
22370 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22371 or @code{SCHED_RR} requires special (e.g., root) privileges.
22373 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22375 @cindex @code{SCHED_FIFO} scheduling policy
22376 you can use one of the following:
22380 @code{pragma Time_Slice (0.0)}
22381 @cindex pragma Time_Slice
22383 the corresponding binder option @option{-T0}
22384 @cindex @option{-T0} option
22386 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22387 @cindex pragma Task_Dispatching_Policy
22391 To specify @code{SCHED_RR},
22392 @cindex @code{SCHED_RR} scheduling policy
22393 you should use @code{pragma Time_Slice} with a
22394 value greater than @code{0.0}, or else use the corresponding @option{-T}
22397 @node Solaris-Specific Considerations
22398 @section Solaris-Specific Considerations
22399 @cindex Solaris Sparc threads libraries
22402 This section addresses some topics related to the various threads libraries
22406 * Solaris Threads Issues::
22409 @node Solaris Threads Issues
22410 @subsection Solaris Threads Issues
22413 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22414 library based on POSIX threads --- @emph{rts-pthread}.
22415 @cindex rts-pthread threads library
22416 This run-time library has the advantage of being mostly shared across all
22417 POSIX-compliant thread implementations, and it also provides under
22418 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22419 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22420 and @code{PTHREAD_PRIO_PROTECT}
22421 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22422 semantics that can be selected using the predefined pragma
22423 @code{Locking_Policy}
22424 @cindex pragma Locking_Policy (under rts-pthread)
22426 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22427 @cindex @code{Inheritance_Locking} (under rts-pthread)
22428 @cindex @code{Ceiling_Locking} (under rts-pthread)
22430 As explained above, the native run-time library is based on the Solaris thread
22431 library (@code{libthread}) and is the default library.
22433 When the Solaris threads library is used (this is the default), programs
22434 compiled with GNAT can automatically take advantage of
22435 and can thus execute on multiple processors.
22436 The user can alternatively specify a processor on which the program should run
22437 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22439 setting the environment variable @env{GNAT_PROCESSOR}
22440 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22441 to one of the following:
22445 Use the default configuration (run the program on all
22446 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22450 Let the run-time implementation choose one processor and run the program on
22453 @item 0 .. Last_Proc
22454 Run the program on the specified processor.
22455 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22456 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22459 @node Linux-Specific Considerations
22460 @section Linux-Specific Considerations
22461 @cindex Linux threads libraries
22464 On GNU/Linux without NPTL support (usually system with GNU C Library
22465 older than 2.3), the signal model is not POSIX compliant, which means
22466 that to send a signal to the process, you need to send the signal to all
22467 threads, e.g.@: by using @code{killpg()}.
22469 @node AIX-Specific Considerations
22470 @section AIX-Specific Considerations
22471 @cindex AIX resolver library
22474 On AIX, the resolver library initializes some internal structure on
22475 the first call to @code{get*by*} functions, which are used to implement
22476 @code{GNAT.Sockets.Get_Host_By_Name} and
22477 @code{GNAT.Sockets.Get_Host_By_Address}.
22478 If such initialization occurs within an Ada task, and the stack size for
22479 the task is the default size, a stack overflow may occur.
22481 To avoid this overflow, the user should either ensure that the first call
22482 to @code{GNAT.Sockets.Get_Host_By_Name} or
22483 @code{GNAT.Sockets.Get_Host_By_Addrss}
22484 occurs in the environment task, or use @code{pragma Storage_Size} to
22485 specify a sufficiently large size for the stack of the task that contains
22488 @node Irix-Specific Considerations
22489 @section Irix-Specific Considerations
22490 @cindex Irix libraries
22493 The GCC support libraries coming with the Irix compiler have moved to
22494 their canonical place with respect to the general Irix ABI related
22495 conventions. Running applications built with the default shared GNAT
22496 run-time now requires the LD_LIBRARY_PATH environment variable to
22497 include this location. A possible way to achieve this is to issue the
22498 following command line on a bash prompt:
22502 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22506 @node RTX-Specific Considerations
22507 @section RTX-Specific Considerations
22508 @cindex RTX libraries
22511 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22512 API. Applications can be built to work in two different modes:
22516 Windows executables that run in Ring 3 to utilize memory protection
22517 (@emph{rts-rtx-w32}).
22520 Real-time subsystem (RTSS) executables that run in Ring 0, where
22521 performance can be optimized with RTSS applications taking precedent
22522 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22523 the Microsoft linker to handle RTSS libraries.
22527 @node HP-UX-Specific Considerations
22528 @section HP-UX-Specific Considerations
22529 @cindex HP-UX Scheduling
22532 On HP-UX, appropriate privileges are required to change the scheduling
22533 parameters of a task. The calling process must have appropriate
22534 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22535 successfully change the scheduling parameters.
22537 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22538 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22539 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22541 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22542 one of the following:
22546 @code{pragma Time_Slice (0.0)}
22547 @cindex pragma Time_Slice
22549 the corresponding binder option @option{-T0}
22550 @cindex @option{-T0} option
22552 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22553 @cindex pragma Task_Dispatching_Policy
22557 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22558 you should use @code{pragma Time_Slice} with a
22559 value greater than @code{0.0}, or use the corresponding @option{-T}
22560 binder option, or set the @code{pragma Task_Dispatching_Policy
22561 (Round_Robin_Within_Priorities)}.
22563 @c *******************************
22564 @node Example of Binder Output File
22565 @appendix Example of Binder Output File
22568 This Appendix displays the source code for @command{gnatbind}'s output
22569 file generated for a simple ``Hello World'' program.
22570 Comments have been added for clarification purposes.
22572 @smallexample @c adanocomment
22576 -- The package is called Ada_Main unless this name is actually used
22577 -- as a unit name in the partition, in which case some other unique
22581 package ada_main is
22583 Elab_Final_Code : Integer;
22584 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22586 -- The main program saves the parameters (argument count,
22587 -- argument values, environment pointer) in global variables
22588 -- for later access by other units including
22589 -- Ada.Command_Line.
22591 gnat_argc : Integer;
22592 gnat_argv : System.Address;
22593 gnat_envp : System.Address;
22595 -- The actual variables are stored in a library routine. This
22596 -- is useful for some shared library situations, where there
22597 -- are problems if variables are not in the library.
22599 pragma Import (C, gnat_argc);
22600 pragma Import (C, gnat_argv);
22601 pragma Import (C, gnat_envp);
22603 -- The exit status is similarly an external location
22605 gnat_exit_status : Integer;
22606 pragma Import (C, gnat_exit_status);
22608 GNAT_Version : constant String :=
22609 "GNAT Version: 6.0.0w (20061115)";
22610 pragma Export (C, GNAT_Version, "__gnat_version");
22612 -- This is the generated adafinal routine that performs
22613 -- finalization at the end of execution. In the case where
22614 -- Ada is the main program, this main program makes a call
22615 -- to adafinal at program termination.
22617 procedure adafinal;
22618 pragma Export (C, adafinal, "adafinal");
22620 -- This is the generated adainit routine that performs
22621 -- initialization at the start of execution. In the case
22622 -- where Ada is the main program, this main program makes
22623 -- a call to adainit at program startup.
22626 pragma Export (C, adainit, "adainit");
22628 -- This routine is called at the start of execution. It is
22629 -- a dummy routine that is used by the debugger to breakpoint
22630 -- at the start of execution.
22632 procedure Break_Start;
22633 pragma Import (C, Break_Start, "__gnat_break_start");
22635 -- This is the actual generated main program (it would be
22636 -- suppressed if the no main program switch were used). As
22637 -- required by standard system conventions, this program has
22638 -- the external name main.
22642 argv : System.Address;
22643 envp : System.Address)
22645 pragma Export (C, main, "main");
22647 -- The following set of constants give the version
22648 -- identification values for every unit in the bound
22649 -- partition. This identification is computed from all
22650 -- dependent semantic units, and corresponds to the
22651 -- string that would be returned by use of the
22652 -- Body_Version or Version attributes.
22654 type Version_32 is mod 2 ** 32;
22655 u00001 : constant Version_32 := 16#7880BEB3#;
22656 u00002 : constant Version_32 := 16#0D24CBD0#;
22657 u00003 : constant Version_32 := 16#3283DBEB#;
22658 u00004 : constant Version_32 := 16#2359F9ED#;
22659 u00005 : constant Version_32 := 16#664FB847#;
22660 u00006 : constant Version_32 := 16#68E803DF#;
22661 u00007 : constant Version_32 := 16#5572E604#;
22662 u00008 : constant Version_32 := 16#46B173D8#;
22663 u00009 : constant Version_32 := 16#156A40CF#;
22664 u00010 : constant Version_32 := 16#033DABE0#;
22665 u00011 : constant Version_32 := 16#6AB38FEA#;
22666 u00012 : constant Version_32 := 16#22B6217D#;
22667 u00013 : constant Version_32 := 16#68A22947#;
22668 u00014 : constant Version_32 := 16#18CC4A56#;
22669 u00015 : constant Version_32 := 16#08258E1B#;
22670 u00016 : constant Version_32 := 16#367D5222#;
22671 u00017 : constant Version_32 := 16#20C9ECA4#;
22672 u00018 : constant Version_32 := 16#50D32CB6#;
22673 u00019 : constant Version_32 := 16#39A8BB77#;
22674 u00020 : constant Version_32 := 16#5CF8FA2B#;
22675 u00021 : constant Version_32 := 16#2F1EB794#;
22676 u00022 : constant Version_32 := 16#31AB6444#;
22677 u00023 : constant Version_32 := 16#1574B6E9#;
22678 u00024 : constant Version_32 := 16#5109C189#;
22679 u00025 : constant Version_32 := 16#56D770CD#;
22680 u00026 : constant Version_32 := 16#02F9DE3D#;
22681 u00027 : constant Version_32 := 16#08AB6B2C#;
22682 u00028 : constant Version_32 := 16#3FA37670#;
22683 u00029 : constant Version_32 := 16#476457A0#;
22684 u00030 : constant Version_32 := 16#731E1B6E#;
22685 u00031 : constant Version_32 := 16#23C2E789#;
22686 u00032 : constant Version_32 := 16#0F1BD6A1#;
22687 u00033 : constant Version_32 := 16#7C25DE96#;
22688 u00034 : constant Version_32 := 16#39ADFFA2#;
22689 u00035 : constant Version_32 := 16#571DE3E7#;
22690 u00036 : constant Version_32 := 16#5EB646AB#;
22691 u00037 : constant Version_32 := 16#4249379B#;
22692 u00038 : constant Version_32 := 16#0357E00A#;
22693 u00039 : constant Version_32 := 16#3784FB72#;
22694 u00040 : constant Version_32 := 16#2E723019#;
22695 u00041 : constant Version_32 := 16#623358EA#;
22696 u00042 : constant Version_32 := 16#107F9465#;
22697 u00043 : constant Version_32 := 16#6843F68A#;
22698 u00044 : constant Version_32 := 16#63305874#;
22699 u00045 : constant Version_32 := 16#31E56CE1#;
22700 u00046 : constant Version_32 := 16#02917970#;
22701 u00047 : constant Version_32 := 16#6CCBA70E#;
22702 u00048 : constant Version_32 := 16#41CD4204#;
22703 u00049 : constant Version_32 := 16#572E3F58#;
22704 u00050 : constant Version_32 := 16#20729FF5#;
22705 u00051 : constant Version_32 := 16#1D4F93E8#;
22706 u00052 : constant Version_32 := 16#30B2EC3D#;
22707 u00053 : constant Version_32 := 16#34054F96#;
22708 u00054 : constant Version_32 := 16#5A199860#;
22709 u00055 : constant Version_32 := 16#0E7F912B#;
22710 u00056 : constant Version_32 := 16#5760634A#;
22711 u00057 : constant Version_32 := 16#5D851835#;
22713 -- The following Export pragmas export the version numbers
22714 -- with symbolic names ending in B (for body) or S
22715 -- (for spec) so that they can be located in a link. The
22716 -- information provided here is sufficient to track down
22717 -- the exact versions of units used in a given build.
22719 pragma Export (C, u00001, "helloB");
22720 pragma Export (C, u00002, "system__standard_libraryB");
22721 pragma Export (C, u00003, "system__standard_libraryS");
22722 pragma Export (C, u00004, "adaS");
22723 pragma Export (C, u00005, "ada__text_ioB");
22724 pragma Export (C, u00006, "ada__text_ioS");
22725 pragma Export (C, u00007, "ada__exceptionsB");
22726 pragma Export (C, u00008, "ada__exceptionsS");
22727 pragma Export (C, u00009, "gnatS");
22728 pragma Export (C, u00010, "gnat__heap_sort_aB");
22729 pragma Export (C, u00011, "gnat__heap_sort_aS");
22730 pragma Export (C, u00012, "systemS");
22731 pragma Export (C, u00013, "system__exception_tableB");
22732 pragma Export (C, u00014, "system__exception_tableS");
22733 pragma Export (C, u00015, "gnat__htableB");
22734 pragma Export (C, u00016, "gnat__htableS");
22735 pragma Export (C, u00017, "system__exceptionsS");
22736 pragma Export (C, u00018, "system__machine_state_operationsB");
22737 pragma Export (C, u00019, "system__machine_state_operationsS");
22738 pragma Export (C, u00020, "system__machine_codeS");
22739 pragma Export (C, u00021, "system__storage_elementsB");
22740 pragma Export (C, u00022, "system__storage_elementsS");
22741 pragma Export (C, u00023, "system__secondary_stackB");
22742 pragma Export (C, u00024, "system__secondary_stackS");
22743 pragma Export (C, u00025, "system__parametersB");
22744 pragma Export (C, u00026, "system__parametersS");
22745 pragma Export (C, u00027, "system__soft_linksB");
22746 pragma Export (C, u00028, "system__soft_linksS");
22747 pragma Export (C, u00029, "system__stack_checkingB");
22748 pragma Export (C, u00030, "system__stack_checkingS");
22749 pragma Export (C, u00031, "system__tracebackB");
22750 pragma Export (C, u00032, "system__tracebackS");
22751 pragma Export (C, u00033, "ada__streamsS");
22752 pragma Export (C, u00034, "ada__tagsB");
22753 pragma Export (C, u00035, "ada__tagsS");
22754 pragma Export (C, u00036, "system__string_opsB");
22755 pragma Export (C, u00037, "system__string_opsS");
22756 pragma Export (C, u00038, "interfacesS");
22757 pragma Export (C, u00039, "interfaces__c_streamsB");
22758 pragma Export (C, u00040, "interfaces__c_streamsS");
22759 pragma Export (C, u00041, "system__file_ioB");
22760 pragma Export (C, u00042, "system__file_ioS");
22761 pragma Export (C, u00043, "ada__finalizationB");
22762 pragma Export (C, u00044, "ada__finalizationS");
22763 pragma Export (C, u00045, "system__finalization_rootB");
22764 pragma Export (C, u00046, "system__finalization_rootS");
22765 pragma Export (C, u00047, "system__finalization_implementationB");
22766 pragma Export (C, u00048, "system__finalization_implementationS");
22767 pragma Export (C, u00049, "system__string_ops_concat_3B");
22768 pragma Export (C, u00050, "system__string_ops_concat_3S");
22769 pragma Export (C, u00051, "system__stream_attributesB");
22770 pragma Export (C, u00052, "system__stream_attributesS");
22771 pragma Export (C, u00053, "ada__io_exceptionsS");
22772 pragma Export (C, u00054, "system__unsigned_typesS");
22773 pragma Export (C, u00055, "system__file_control_blockS");
22774 pragma Export (C, u00056, "ada__finalization__list_controllerB");
22775 pragma Export (C, u00057, "ada__finalization__list_controllerS");
22777 -- BEGIN ELABORATION ORDER
22780 -- gnat.heap_sort_a (spec)
22781 -- gnat.heap_sort_a (body)
22782 -- gnat.htable (spec)
22783 -- gnat.htable (body)
22784 -- interfaces (spec)
22786 -- system.machine_code (spec)
22787 -- system.parameters (spec)
22788 -- system.parameters (body)
22789 -- interfaces.c_streams (spec)
22790 -- interfaces.c_streams (body)
22791 -- system.standard_library (spec)
22792 -- ada.exceptions (spec)
22793 -- system.exception_table (spec)
22794 -- system.exception_table (body)
22795 -- ada.io_exceptions (spec)
22796 -- system.exceptions (spec)
22797 -- system.storage_elements (spec)
22798 -- system.storage_elements (body)
22799 -- system.machine_state_operations (spec)
22800 -- system.machine_state_operations (body)
22801 -- system.secondary_stack (spec)
22802 -- system.stack_checking (spec)
22803 -- system.soft_links (spec)
22804 -- system.soft_links (body)
22805 -- system.stack_checking (body)
22806 -- system.secondary_stack (body)
22807 -- system.standard_library (body)
22808 -- system.string_ops (spec)
22809 -- system.string_ops (body)
22812 -- ada.streams (spec)
22813 -- system.finalization_root (spec)
22814 -- system.finalization_root (body)
22815 -- system.string_ops_concat_3 (spec)
22816 -- system.string_ops_concat_3 (body)
22817 -- system.traceback (spec)
22818 -- system.traceback (body)
22819 -- ada.exceptions (body)
22820 -- system.unsigned_types (spec)
22821 -- system.stream_attributes (spec)
22822 -- system.stream_attributes (body)
22823 -- system.finalization_implementation (spec)
22824 -- system.finalization_implementation (body)
22825 -- ada.finalization (spec)
22826 -- ada.finalization (body)
22827 -- ada.finalization.list_controller (spec)
22828 -- ada.finalization.list_controller (body)
22829 -- system.file_control_block (spec)
22830 -- system.file_io (spec)
22831 -- system.file_io (body)
22832 -- ada.text_io (spec)
22833 -- ada.text_io (body)
22835 -- END ELABORATION ORDER
22839 -- The following source file name pragmas allow the generated file
22840 -- names to be unique for different main programs. They are needed
22841 -- since the package name will always be Ada_Main.
22843 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22844 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22846 -- Generated package body for Ada_Main starts here
22848 package body ada_main is
22850 -- The actual finalization is performed by calling the
22851 -- library routine in System.Standard_Library.Adafinal
22853 procedure Do_Finalize;
22854 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22861 procedure adainit is
22863 -- These booleans are set to True once the associated unit has
22864 -- been elaborated. It is also used to avoid elaborating the
22865 -- same unit twice.
22868 pragma Import (Ada, E040, "interfaces__c_streams_E");
22871 pragma Import (Ada, E008, "ada__exceptions_E");
22874 pragma Import (Ada, E014, "system__exception_table_E");
22877 pragma Import (Ada, E053, "ada__io_exceptions_E");
22880 pragma Import (Ada, E017, "system__exceptions_E");
22883 pragma Import (Ada, E024, "system__secondary_stack_E");
22886 pragma Import (Ada, E030, "system__stack_checking_E");
22889 pragma Import (Ada, E028, "system__soft_links_E");
22892 pragma Import (Ada, E035, "ada__tags_E");
22895 pragma Import (Ada, E033, "ada__streams_E");
22898 pragma Import (Ada, E046, "system__finalization_root_E");
22901 pragma Import (Ada, E048, "system__finalization_implementation_E");
22904 pragma Import (Ada, E044, "ada__finalization_E");
22907 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22910 pragma Import (Ada, E055, "system__file_control_block_E");
22913 pragma Import (Ada, E042, "system__file_io_E");
22916 pragma Import (Ada, E006, "ada__text_io_E");
22918 -- Set_Globals is a library routine that stores away the
22919 -- value of the indicated set of global values in global
22920 -- variables within the library.
22922 procedure Set_Globals
22923 (Main_Priority : Integer;
22924 Time_Slice_Value : Integer;
22925 WC_Encoding : Character;
22926 Locking_Policy : Character;
22927 Queuing_Policy : Character;
22928 Task_Dispatching_Policy : Character;
22929 Adafinal : System.Address;
22930 Unreserve_All_Interrupts : Integer;
22931 Exception_Tracebacks : Integer);
22932 @findex __gnat_set_globals
22933 pragma Import (C, Set_Globals, "__gnat_set_globals");
22935 -- SDP_Table_Build is a library routine used to build the
22936 -- exception tables. See unit Ada.Exceptions in files
22937 -- a-except.ads/adb for full details of how zero cost
22938 -- exception handling works. This procedure, the call to
22939 -- it, and the two following tables are all omitted if the
22940 -- build is in longjmp/setjmp exception mode.
22942 @findex SDP_Table_Build
22943 @findex Zero Cost Exceptions
22944 procedure SDP_Table_Build
22945 (SDP_Addresses : System.Address;
22946 SDP_Count : Natural;
22947 Elab_Addresses : System.Address;
22948 Elab_Addr_Count : Natural);
22949 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22951 -- Table of Unit_Exception_Table addresses. Used for zero
22952 -- cost exception handling to build the top level table.
22954 ST : aliased constant array (1 .. 23) of System.Address := (
22956 Ada.Text_Io'UET_Address,
22957 Ada.Exceptions'UET_Address,
22958 Gnat.Heap_Sort_A'UET_Address,
22959 System.Exception_Table'UET_Address,
22960 System.Machine_State_Operations'UET_Address,
22961 System.Secondary_Stack'UET_Address,
22962 System.Parameters'UET_Address,
22963 System.Soft_Links'UET_Address,
22964 System.Stack_Checking'UET_Address,
22965 System.Traceback'UET_Address,
22966 Ada.Streams'UET_Address,
22967 Ada.Tags'UET_Address,
22968 System.String_Ops'UET_Address,
22969 Interfaces.C_Streams'UET_Address,
22970 System.File_Io'UET_Address,
22971 Ada.Finalization'UET_Address,
22972 System.Finalization_Root'UET_Address,
22973 System.Finalization_Implementation'UET_Address,
22974 System.String_Ops_Concat_3'UET_Address,
22975 System.Stream_Attributes'UET_Address,
22976 System.File_Control_Block'UET_Address,
22977 Ada.Finalization.List_Controller'UET_Address);
22979 -- Table of addresses of elaboration routines. Used for
22980 -- zero cost exception handling to make sure these
22981 -- addresses are included in the top level procedure
22984 EA : aliased constant array (1 .. 23) of System.Address := (
22985 adainit'Code_Address,
22986 Do_Finalize'Code_Address,
22987 Ada.Exceptions'Elab_Spec'Address,
22988 System.Exceptions'Elab_Spec'Address,
22989 Interfaces.C_Streams'Elab_Spec'Address,
22990 System.Exception_Table'Elab_Body'Address,
22991 Ada.Io_Exceptions'Elab_Spec'Address,
22992 System.Stack_Checking'Elab_Spec'Address,
22993 System.Soft_Links'Elab_Body'Address,
22994 System.Secondary_Stack'Elab_Body'Address,
22995 Ada.Tags'Elab_Spec'Address,
22996 Ada.Tags'Elab_Body'Address,
22997 Ada.Streams'Elab_Spec'Address,
22998 System.Finalization_Root'Elab_Spec'Address,
22999 Ada.Exceptions'Elab_Body'Address,
23000 System.Finalization_Implementation'Elab_Spec'Address,
23001 System.Finalization_Implementation'Elab_Body'Address,
23002 Ada.Finalization'Elab_Spec'Address,
23003 Ada.Finalization.List_Controller'Elab_Spec'Address,
23004 System.File_Control_Block'Elab_Spec'Address,
23005 System.File_Io'Elab_Body'Address,
23006 Ada.Text_Io'Elab_Spec'Address,
23007 Ada.Text_Io'Elab_Body'Address);
23009 -- Start of processing for adainit
23013 -- Call SDP_Table_Build to build the top level procedure
23014 -- table for zero cost exception handling (omitted in
23015 -- longjmp/setjmp mode).
23017 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23019 -- Call Set_Globals to record various information for
23020 -- this partition. The values are derived by the binder
23021 -- from information stored in the ali files by the compiler.
23023 @findex __gnat_set_globals
23025 (Main_Priority => -1,
23026 -- Priority of main program, -1 if no pragma Priority used
23028 Time_Slice_Value => -1,
23029 -- Time slice from Time_Slice pragma, -1 if none used
23031 WC_Encoding => 'b',
23032 -- Wide_Character encoding used, default is brackets
23034 Locking_Policy => ' ',
23035 -- Locking_Policy used, default of space means not
23036 -- specified, otherwise it is the first character of
23037 -- the policy name.
23039 Queuing_Policy => ' ',
23040 -- Queuing_Policy used, default of space means not
23041 -- specified, otherwise it is the first character of
23042 -- the policy name.
23044 Task_Dispatching_Policy => ' ',
23045 -- Task_Dispatching_Policy used, default of space means
23046 -- not specified, otherwise first character of the
23049 Adafinal => System.Null_Address,
23050 -- Address of Adafinal routine, not used anymore
23052 Unreserve_All_Interrupts => 0,
23053 -- Set true if pragma Unreserve_All_Interrupts was used
23055 Exception_Tracebacks => 0);
23056 -- Indicates if exception tracebacks are enabled
23058 Elab_Final_Code := 1;
23060 -- Now we have the elaboration calls for all units in the partition.
23061 -- The Elab_Spec and Elab_Body attributes generate references to the
23062 -- implicit elaboration procedures generated by the compiler for
23063 -- each unit that requires elaboration.
23066 Interfaces.C_Streams'Elab_Spec;
23070 Ada.Exceptions'Elab_Spec;
23073 System.Exception_Table'Elab_Body;
23077 Ada.Io_Exceptions'Elab_Spec;
23081 System.Exceptions'Elab_Spec;
23085 System.Stack_Checking'Elab_Spec;
23088 System.Soft_Links'Elab_Body;
23093 System.Secondary_Stack'Elab_Body;
23097 Ada.Tags'Elab_Spec;
23100 Ada.Tags'Elab_Body;
23104 Ada.Streams'Elab_Spec;
23108 System.Finalization_Root'Elab_Spec;
23112 Ada.Exceptions'Elab_Body;
23116 System.Finalization_Implementation'Elab_Spec;
23119 System.Finalization_Implementation'Elab_Body;
23123 Ada.Finalization'Elab_Spec;
23127 Ada.Finalization.List_Controller'Elab_Spec;
23131 System.File_Control_Block'Elab_Spec;
23135 System.File_Io'Elab_Body;
23139 Ada.Text_Io'Elab_Spec;
23142 Ada.Text_Io'Elab_Body;
23146 Elab_Final_Code := 0;
23154 procedure adafinal is
23163 -- main is actually a function, as in the ANSI C standard,
23164 -- defined to return the exit status. The three parameters
23165 -- are the argument count, argument values and environment
23168 @findex Main Program
23171 argv : System.Address;
23172 envp : System.Address)
23175 -- The initialize routine performs low level system
23176 -- initialization using a standard library routine which
23177 -- sets up signal handling and performs any other
23178 -- required setup. The routine can be found in file
23181 @findex __gnat_initialize
23182 procedure initialize;
23183 pragma Import (C, initialize, "__gnat_initialize");
23185 -- The finalize routine performs low level system
23186 -- finalization using a standard library routine. The
23187 -- routine is found in file a-final.c and in the standard
23188 -- distribution is a dummy routine that does nothing, so
23189 -- really this is a hook for special user finalization.
23191 @findex __gnat_finalize
23192 procedure finalize;
23193 pragma Import (C, finalize, "__gnat_finalize");
23195 -- We get to the main program of the partition by using
23196 -- pragma Import because if we try to with the unit and
23197 -- call it Ada style, then not only do we waste time
23198 -- recompiling it, but also, we don't really know the right
23199 -- switches (e.g.@: identifier character set) to be used
23202 procedure Ada_Main_Program;
23203 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23205 -- Start of processing for main
23208 -- Save global variables
23214 -- Call low level system initialization
23218 -- Call our generated Ada initialization routine
23222 -- This is the point at which we want the debugger to get
23227 -- Now we call the main program of the partition
23231 -- Perform Ada finalization
23235 -- Perform low level system finalization
23239 -- Return the proper exit status
23240 return (gnat_exit_status);
23243 -- This section is entirely comments, so it has no effect on the
23244 -- compilation of the Ada_Main package. It provides the list of
23245 -- object files and linker options, as well as some standard
23246 -- libraries needed for the link. The gnatlink utility parses
23247 -- this b~hello.adb file to read these comment lines to generate
23248 -- the appropriate command line arguments for the call to the
23249 -- system linker. The BEGIN/END lines are used for sentinels for
23250 -- this parsing operation.
23252 -- The exact file names will of course depend on the environment,
23253 -- host/target and location of files on the host system.
23255 @findex Object file list
23256 -- BEGIN Object file/option list
23259 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23260 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23261 -- END Object file/option list
23267 The Ada code in the above example is exactly what is generated by the
23268 binder. We have added comments to more clearly indicate the function
23269 of each part of the generated @code{Ada_Main} package.
23271 The code is standard Ada in all respects, and can be processed by any
23272 tools that handle Ada. In particular, it is possible to use the debugger
23273 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23274 suppose that for reasons that you do not understand, your program is crashing
23275 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23276 you can place a breakpoint on the call:
23278 @smallexample @c ada
23279 Ada.Text_Io'Elab_Body;
23283 and trace the elaboration routine for this package to find out where
23284 the problem might be (more usually of course you would be debugging
23285 elaboration code in your own application).
23287 @node Elaboration Order Handling in GNAT
23288 @appendix Elaboration Order Handling in GNAT
23289 @cindex Order of elaboration
23290 @cindex Elaboration control
23293 * Elaboration Code::
23294 * Checking the Elaboration Order::
23295 * Controlling the Elaboration Order::
23296 * Controlling Elaboration in GNAT - Internal Calls::
23297 * Controlling Elaboration in GNAT - External Calls::
23298 * Default Behavior in GNAT - Ensuring Safety::
23299 * Treatment of Pragma Elaborate::
23300 * Elaboration Issues for Library Tasks::
23301 * Mixing Elaboration Models::
23302 * What to Do If the Default Elaboration Behavior Fails::
23303 * Elaboration for Access-to-Subprogram Values::
23304 * Summary of Procedures for Elaboration Control::
23305 * Other Elaboration Order Considerations::
23309 This chapter describes the handling of elaboration code in Ada and
23310 in GNAT, and discusses how the order of elaboration of program units can
23311 be controlled in GNAT, either automatically or with explicit programming
23314 @node Elaboration Code
23315 @section Elaboration Code
23318 Ada provides rather general mechanisms for executing code at elaboration
23319 time, that is to say before the main program starts executing. Such code arises
23323 @item Initializers for variables.
23324 Variables declared at the library level, in package specs or bodies, can
23325 require initialization that is performed at elaboration time, as in:
23326 @smallexample @c ada
23328 Sqrt_Half : Float := Sqrt (0.5);
23332 @item Package initialization code
23333 Code in a @code{BEGIN-END} section at the outer level of a package body is
23334 executed as part of the package body elaboration code.
23336 @item Library level task allocators
23337 Tasks that are declared using task allocators at the library level
23338 start executing immediately and hence can execute at elaboration time.
23342 Subprogram calls are possible in any of these contexts, which means that
23343 any arbitrary part of the program may be executed as part of the elaboration
23344 code. It is even possible to write a program which does all its work at
23345 elaboration time, with a null main program, although stylistically this
23346 would usually be considered an inappropriate way to structure
23349 An important concern arises in the context of elaboration code:
23350 we have to be sure that it is executed in an appropriate order. What we
23351 have is a series of elaboration code sections, potentially one section
23352 for each unit in the program. It is important that these execute
23353 in the correct order. Correctness here means that, taking the above
23354 example of the declaration of @code{Sqrt_Half},
23355 if some other piece of
23356 elaboration code references @code{Sqrt_Half},
23357 then it must run after the
23358 section of elaboration code that contains the declaration of
23361 There would never be any order of elaboration problem if we made a rule
23362 that whenever you @code{with} a unit, you must elaborate both the spec and body
23363 of that unit before elaborating the unit doing the @code{with}'ing:
23365 @smallexample @c ada
23369 package Unit_2 is @dots{}
23375 would require that both the body and spec of @code{Unit_1} be elaborated
23376 before the spec of @code{Unit_2}. However, a rule like that would be far too
23377 restrictive. In particular, it would make it impossible to have routines
23378 in separate packages that were mutually recursive.
23380 You might think that a clever enough compiler could look at the actual
23381 elaboration code and determine an appropriate correct order of elaboration,
23382 but in the general case, this is not possible. Consider the following
23385 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23387 the variable @code{Sqrt_1}, which is declared in the elaboration code
23388 of the body of @code{Unit_1}:
23390 @smallexample @c ada
23392 Sqrt_1 : Float := Sqrt (0.1);
23397 The elaboration code of the body of @code{Unit_1} also contains:
23399 @smallexample @c ada
23402 if expression_1 = 1 then
23403 Q := Unit_2.Func_2;
23410 @code{Unit_2} is exactly parallel,
23411 it has a procedure @code{Func_2} that references
23412 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23413 the body @code{Unit_2}:
23415 @smallexample @c ada
23417 Sqrt_2 : Float := Sqrt (0.1);
23422 The elaboration code of the body of @code{Unit_2} also contains:
23424 @smallexample @c ada
23427 if expression_2 = 2 then
23428 Q := Unit_1.Func_1;
23435 Now the question is, which of the following orders of elaboration is
23460 If you carefully analyze the flow here, you will see that you cannot tell
23461 at compile time the answer to this question.
23462 If @code{expression_1} is not equal to 1,
23463 and @code{expression_2} is not equal to 2,
23464 then either order is acceptable, because neither of the function calls is
23465 executed. If both tests evaluate to true, then neither order is acceptable
23466 and in fact there is no correct order.
23468 If one of the two expressions is true, and the other is false, then one
23469 of the above orders is correct, and the other is incorrect. For example,
23470 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23471 then the call to @code{Func_1}
23472 will occur, but not the call to @code{Func_2.}
23473 This means that it is essential
23474 to elaborate the body of @code{Unit_1} before
23475 the body of @code{Unit_2}, so the first
23476 order of elaboration is correct and the second is wrong.
23478 By making @code{expression_1} and @code{expression_2}
23479 depend on input data, or perhaps
23480 the time of day, we can make it impossible for the compiler or binder
23481 to figure out which of these expressions will be true, and hence it
23482 is impossible to guarantee a safe order of elaboration at run time.
23484 @node Checking the Elaboration Order
23485 @section Checking the Elaboration Order
23488 In some languages that involve the same kind of elaboration problems,
23489 e.g.@: Java and C++, the programmer is expected to worry about these
23490 ordering problems himself, and it is common to
23491 write a program in which an incorrect elaboration order gives
23492 surprising results, because it references variables before they
23494 Ada is designed to be a safe language, and a programmer-beware approach is
23495 clearly not sufficient. Consequently, the language provides three lines
23499 @item Standard rules
23500 Some standard rules restrict the possible choice of elaboration
23501 order. In particular, if you @code{with} a unit, then its spec is always
23502 elaborated before the unit doing the @code{with}. Similarly, a parent
23503 spec is always elaborated before the child spec, and finally
23504 a spec is always elaborated before its corresponding body.
23506 @item Dynamic elaboration checks
23507 @cindex Elaboration checks
23508 @cindex Checks, elaboration
23509 Dynamic checks are made at run time, so that if some entity is accessed
23510 before it is elaborated (typically by means of a subprogram call)
23511 then the exception (@code{Program_Error}) is raised.
23513 @item Elaboration control
23514 Facilities are provided for the programmer to specify the desired order
23518 Let's look at these facilities in more detail. First, the rules for
23519 dynamic checking. One possible rule would be simply to say that the
23520 exception is raised if you access a variable which has not yet been
23521 elaborated. The trouble with this approach is that it could require
23522 expensive checks on every variable reference. Instead Ada has two
23523 rules which are a little more restrictive, but easier to check, and
23527 @item Restrictions on calls
23528 A subprogram can only be called at elaboration time if its body
23529 has been elaborated. The rules for elaboration given above guarantee
23530 that the spec of the subprogram has been elaborated before the
23531 call, but not the body. If this rule is violated, then the
23532 exception @code{Program_Error} is raised.
23534 @item Restrictions on instantiations
23535 A generic unit can only be instantiated if the body of the generic
23536 unit has been elaborated. Again, the rules for elaboration given above
23537 guarantee that the spec of the generic unit has been elaborated
23538 before the instantiation, but not the body. If this rule is
23539 violated, then the exception @code{Program_Error} is raised.
23543 The idea is that if the body has been elaborated, then any variables
23544 it references must have been elaborated; by checking for the body being
23545 elaborated we guarantee that none of its references causes any
23546 trouble. As we noted above, this is a little too restrictive, because a
23547 subprogram that has no non-local references in its body may in fact be safe
23548 to call. However, it really would be unsafe to rely on this, because
23549 it would mean that the caller was aware of details of the implementation
23550 in the body. This goes against the basic tenets of Ada.
23552 A plausible implementation can be described as follows.
23553 A Boolean variable is associated with each subprogram
23554 and each generic unit. This variable is initialized to False, and is set to
23555 True at the point body is elaborated. Every call or instantiation checks the
23556 variable, and raises @code{Program_Error} if the variable is False.
23558 Note that one might think that it would be good enough to have one Boolean
23559 variable for each package, but that would not deal with cases of trying
23560 to call a body in the same package as the call
23561 that has not been elaborated yet.
23562 Of course a compiler may be able to do enough analysis to optimize away
23563 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23564 does such optimizations, but still the easiest conceptual model is to
23565 think of there being one variable per subprogram.
23567 @node Controlling the Elaboration Order
23568 @section Controlling the Elaboration Order
23571 In the previous section we discussed the rules in Ada which ensure
23572 that @code{Program_Error} is raised if an incorrect elaboration order is
23573 chosen. This prevents erroneous executions, but we need mechanisms to
23574 specify a correct execution and avoid the exception altogether.
23575 To achieve this, Ada provides a number of features for controlling
23576 the order of elaboration. We discuss these features in this section.
23578 First, there are several ways of indicating to the compiler that a given
23579 unit has no elaboration problems:
23582 @item packages that do not require a body
23583 A library package that does not require a body does not permit
23584 a body (this rule was introduced in Ada 95).
23585 Thus if we have a such a package, as in:
23587 @smallexample @c ada
23590 package Definitions is
23592 type m is new integer;
23594 type a is array (1 .. 10) of m;
23595 type b is array (1 .. 20) of m;
23603 A package that @code{with}'s @code{Definitions} may safely instantiate
23604 @code{Definitions.Subp} because the compiler can determine that there
23605 definitely is no package body to worry about in this case
23608 @cindex pragma Pure
23610 Places sufficient restrictions on a unit to guarantee that
23611 no call to any subprogram in the unit can result in an
23612 elaboration problem. This means that the compiler does not need
23613 to worry about the point of elaboration of such units, and in
23614 particular, does not need to check any calls to any subprograms
23617 @item pragma Preelaborate
23618 @findex Preelaborate
23619 @cindex pragma Preelaborate
23620 This pragma places slightly less stringent restrictions on a unit than
23622 but these restrictions are still sufficient to ensure that there
23623 are no elaboration problems with any calls to the unit.
23625 @item pragma Elaborate_Body
23626 @findex Elaborate_Body
23627 @cindex pragma Elaborate_Body
23628 This pragma requires that the body of a unit be elaborated immediately
23629 after its spec. Suppose a unit @code{A} has such a pragma,
23630 and unit @code{B} does
23631 a @code{with} of unit @code{A}. Recall that the standard rules require
23632 the spec of unit @code{A}
23633 to be elaborated before the @code{with}'ing unit; given the pragma in
23634 @code{A}, we also know that the body of @code{A}
23635 will be elaborated before @code{B}, so
23636 that calls to @code{A} are safe and do not need a check.
23641 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23643 @code{Elaborate_Body} does not guarantee that the program is
23644 free of elaboration problems, because it may not be possible
23645 to satisfy the requested elaboration order.
23646 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23648 marks @code{Unit_1} as @code{Elaborate_Body},
23649 and not @code{Unit_2,} then the order of
23650 elaboration will be:
23662 Now that means that the call to @code{Func_1} in @code{Unit_2}
23663 need not be checked,
23664 it must be safe. But the call to @code{Func_2} in
23665 @code{Unit_1} may still fail if
23666 @code{Expression_1} is equal to 1,
23667 and the programmer must still take
23668 responsibility for this not being the case.
23670 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23671 eliminated, except for calls entirely within a body, which are
23672 in any case fully under programmer control. However, using the pragma
23673 everywhere is not always possible.
23674 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23675 we marked both of them as having pragma @code{Elaborate_Body}, then
23676 clearly there would be no possible elaboration order.
23678 The above pragmas allow a server to guarantee safe use by clients, and
23679 clearly this is the preferable approach. Consequently a good rule
23680 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23681 and if this is not possible,
23682 mark them as @code{Elaborate_Body} if possible.
23683 As we have seen, there are situations where neither of these
23684 three pragmas can be used.
23685 So we also provide methods for clients to control the
23686 order of elaboration of the servers on which they depend:
23689 @item pragma Elaborate (unit)
23691 @cindex pragma Elaborate
23692 This pragma is placed in the context clause, after a @code{with} clause,
23693 and it requires that the body of the named unit be elaborated before
23694 the unit in which the pragma occurs. The idea is to use this pragma
23695 if the current unit calls at elaboration time, directly or indirectly,
23696 some subprogram in the named unit.
23698 @item pragma Elaborate_All (unit)
23699 @findex Elaborate_All
23700 @cindex pragma Elaborate_All
23701 This is a stronger version of the Elaborate pragma. Consider the
23705 Unit A @code{with}'s unit B and calls B.Func in elab code
23706 Unit B @code{with}'s unit C, and B.Func calls C.Func
23710 Now if we put a pragma @code{Elaborate (B)}
23711 in unit @code{A}, this ensures that the
23712 body of @code{B} is elaborated before the call, but not the
23713 body of @code{C}, so
23714 the call to @code{C.Func} could still cause @code{Program_Error} to
23717 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23718 not only that the body of the named unit be elaborated before the
23719 unit doing the @code{with}, but also the bodies of all units that the
23720 named unit uses, following @code{with} links transitively. For example,
23721 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23723 not only that the body of @code{B} be elaborated before @code{A},
23725 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23729 We are now in a position to give a usage rule in Ada for avoiding
23730 elaboration problems, at least if dynamic dispatching and access to
23731 subprogram values are not used. We will handle these cases separately
23734 The rule is simple. If a unit has elaboration code that can directly or
23735 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23736 a generic package in a @code{with}'ed unit,
23737 then if the @code{with}'ed unit does not have
23738 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23739 a pragma @code{Elaborate_All}
23740 for the @code{with}'ed unit. By following this rule a client is
23741 assured that calls can be made without risk of an exception.
23743 For generic subprogram instantiations, the rule can be relaxed to
23744 require only a pragma @code{Elaborate} since elaborating the body
23745 of a subprogram cannot cause any transitive elaboration (we are
23746 not calling the subprogram in this case, just elaborating its
23749 If this rule is not followed, then a program may be in one of four
23753 @item No order exists
23754 No order of elaboration exists which follows the rules, taking into
23755 account any @code{Elaborate}, @code{Elaborate_All},
23756 or @code{Elaborate_Body} pragmas. In
23757 this case, an Ada compiler must diagnose the situation at bind
23758 time, and refuse to build an executable program.
23760 @item One or more orders exist, all incorrect
23761 One or more acceptable elaboration orders exist, and all of them
23762 generate an elaboration order problem. In this case, the binder
23763 can build an executable program, but @code{Program_Error} will be raised
23764 when the program is run.
23766 @item Several orders exist, some right, some incorrect
23767 One or more acceptable elaboration orders exists, and some of them
23768 work, and some do not. The programmer has not controlled
23769 the order of elaboration, so the binder may or may not pick one of
23770 the correct orders, and the program may or may not raise an
23771 exception when it is run. This is the worst case, because it means
23772 that the program may fail when moved to another compiler, or even
23773 another version of the same compiler.
23775 @item One or more orders exists, all correct
23776 One ore more acceptable elaboration orders exist, and all of them
23777 work. In this case the program runs successfully. This state of
23778 affairs can be guaranteed by following the rule we gave above, but
23779 may be true even if the rule is not followed.
23783 Note that one additional advantage of following our rules on the use
23784 of @code{Elaborate} and @code{Elaborate_All}
23785 is that the program continues to stay in the ideal (all orders OK) state
23786 even if maintenance
23787 changes some bodies of some units. Conversely, if a program that does
23788 not follow this rule happens to be safe at some point, this state of affairs
23789 may deteriorate silently as a result of maintenance changes.
23791 You may have noticed that the above discussion did not mention
23792 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23793 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23794 code in the body makes calls to some other unit, so it is still necessary
23795 to use @code{Elaborate_All} on such units.
23797 @node Controlling Elaboration in GNAT - Internal Calls
23798 @section Controlling Elaboration in GNAT - Internal Calls
23801 In the case of internal calls, i.e., calls within a single package, the
23802 programmer has full control over the order of elaboration, and it is up
23803 to the programmer to elaborate declarations in an appropriate order. For
23806 @smallexample @c ada
23809 function One return Float;
23813 function One return Float is
23822 will obviously raise @code{Program_Error} at run time, because function
23823 One will be called before its body is elaborated. In this case GNAT will
23824 generate a warning that the call will raise @code{Program_Error}:
23830 2. function One return Float;
23832 4. Q : Float := One;
23834 >>> warning: cannot call "One" before body is elaborated
23835 >>> warning: Program_Error will be raised at run time
23838 6. function One return Float is
23851 Note that in this particular case, it is likely that the call is safe, because
23852 the function @code{One} does not access any global variables.
23853 Nevertheless in Ada, we do not want the validity of the check to depend on
23854 the contents of the body (think about the separate compilation case), so this
23855 is still wrong, as we discussed in the previous sections.
23857 The error is easily corrected by rearranging the declarations so that the
23858 body of @code{One} appears before the declaration containing the call
23859 (note that in Ada 95 and Ada 2005,
23860 declarations can appear in any order, so there is no restriction that
23861 would prevent this reordering, and if we write:
23863 @smallexample @c ada
23866 function One return Float;
23868 function One return Float is
23879 then all is well, no warning is generated, and no
23880 @code{Program_Error} exception
23882 Things are more complicated when a chain of subprograms is executed:
23884 @smallexample @c ada
23887 function A return Integer;
23888 function B return Integer;
23889 function C return Integer;
23891 function B return Integer is begin return A; end;
23892 function C return Integer is begin return B; end;
23896 function A return Integer is begin return 1; end;
23902 Now the call to @code{C}
23903 at elaboration time in the declaration of @code{X} is correct, because
23904 the body of @code{C} is already elaborated,
23905 and the call to @code{B} within the body of
23906 @code{C} is correct, but the call
23907 to @code{A} within the body of @code{B} is incorrect, because the body
23908 of @code{A} has not been elaborated, so @code{Program_Error}
23909 will be raised on the call to @code{A}.
23910 In this case GNAT will generate a
23911 warning that @code{Program_Error} may be
23912 raised at the point of the call. Let's look at the warning:
23918 2. function A return Integer;
23919 3. function B return Integer;
23920 4. function C return Integer;
23922 6. function B return Integer is begin return A; end;
23924 >>> warning: call to "A" before body is elaborated may
23925 raise Program_Error
23926 >>> warning: "B" called at line 7
23927 >>> warning: "C" called at line 9
23929 7. function C return Integer is begin return B; end;
23931 9. X : Integer := C;
23933 11. function A return Integer is begin return 1; end;
23943 Note that the message here says ``may raise'', instead of the direct case,
23944 where the message says ``will be raised''. That's because whether
23946 actually called depends in general on run-time flow of control.
23947 For example, if the body of @code{B} said
23949 @smallexample @c ada
23952 function B return Integer is
23954 if some-condition-depending-on-input-data then
23965 then we could not know until run time whether the incorrect call to A would
23966 actually occur, so @code{Program_Error} might
23967 or might not be raised. It is possible for a compiler to
23968 do a better job of analyzing bodies, to
23969 determine whether or not @code{Program_Error}
23970 might be raised, but it certainly
23971 couldn't do a perfect job (that would require solving the halting problem
23972 and is provably impossible), and because this is a warning anyway, it does
23973 not seem worth the effort to do the analysis. Cases in which it
23974 would be relevant are rare.
23976 In practice, warnings of either of the forms given
23977 above will usually correspond to
23978 real errors, and should be examined carefully and eliminated.
23979 In the rare case where a warning is bogus, it can be suppressed by any of
23980 the following methods:
23984 Compile with the @option{-gnatws} switch set
23987 Suppress @code{Elaboration_Check} for the called subprogram
23990 Use pragma @code{Warnings_Off} to turn warnings off for the call
23994 For the internal elaboration check case,
23995 GNAT by default generates the
23996 necessary run-time checks to ensure
23997 that @code{Program_Error} is raised if any
23998 call fails an elaboration check. Of course this can only happen if a
23999 warning has been issued as described above. The use of pragma
24000 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24001 some of these checks, meaning that it may be possible (but is not
24002 guaranteed) for a program to be able to call a subprogram whose body
24003 is not yet elaborated, without raising a @code{Program_Error} exception.
24005 @node Controlling Elaboration in GNAT - External Calls
24006 @section Controlling Elaboration in GNAT - External Calls
24009 The previous section discussed the case in which the execution of a
24010 particular thread of elaboration code occurred entirely within a
24011 single unit. This is the easy case to handle, because a programmer
24012 has direct and total control over the order of elaboration, and
24013 furthermore, checks need only be generated in cases which are rare
24014 and which the compiler can easily detect.
24015 The situation is more complex when separate compilation is taken into account.
24016 Consider the following:
24018 @smallexample @c ada
24022 function Sqrt (Arg : Float) return Float;
24025 package body Math is
24026 function Sqrt (Arg : Float) return Float is
24035 X : Float := Math.Sqrt (0.5);
24048 where @code{Main} is the main program. When this program is executed, the
24049 elaboration code must first be executed, and one of the jobs of the
24050 binder is to determine the order in which the units of a program are
24051 to be elaborated. In this case we have four units: the spec and body
24053 the spec of @code{Stuff} and the body of @code{Main}).
24054 In what order should the four separate sections of elaboration code
24057 There are some restrictions in the order of elaboration that the binder
24058 can choose. In particular, if unit U has a @code{with}
24059 for a package @code{X}, then you
24060 are assured that the spec of @code{X}
24061 is elaborated before U , but you are
24062 not assured that the body of @code{X}
24063 is elaborated before U.
24064 This means that in the above case, the binder is allowed to choose the
24075 but that's not good, because now the call to @code{Math.Sqrt}
24076 that happens during
24077 the elaboration of the @code{Stuff}
24078 spec happens before the body of @code{Math.Sqrt} is
24079 elaborated, and hence causes @code{Program_Error} exception to be raised.
24080 At first glance, one might say that the binder is misbehaving, because
24081 obviously you want to elaborate the body of something you @code{with}
24083 that is not a general rule that can be followed in all cases. Consider
24085 @smallexample @c ada
24088 package X is @dots{}
24090 package Y is @dots{}
24093 package body Y is @dots{}
24096 package body X is @dots{}
24102 This is a common arrangement, and, apart from the order of elaboration
24103 problems that might arise in connection with elaboration code, this works fine.
24104 A rule that says that you must first elaborate the body of anything you
24105 @code{with} cannot work in this case:
24106 the body of @code{X} @code{with}'s @code{Y},
24107 which means you would have to
24108 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24110 you have to elaborate the body of @code{X} first, but @dots{} and we have a
24111 loop that cannot be broken.
24113 It is true that the binder can in many cases guess an order of elaboration
24114 that is unlikely to cause a @code{Program_Error}
24115 exception to be raised, and it tries to do so (in the
24116 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24118 elaborate the body of @code{Math} right after its spec, so all will be well).
24120 However, a program that blindly relies on the binder to be helpful can
24121 get into trouble, as we discussed in the previous sections, so
24123 provides a number of facilities for assisting the programmer in
24124 developing programs that are robust with respect to elaboration order.
24126 @node Default Behavior in GNAT - Ensuring Safety
24127 @section Default Behavior in GNAT - Ensuring Safety
24130 The default behavior in GNAT ensures elaboration safety. In its
24131 default mode GNAT implements the
24132 rule we previously described as the right approach. Let's restate it:
24136 @emph{If a unit has elaboration code that can directly or indirectly make a
24137 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24138 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24139 does not have pragma @code{Pure} or
24140 @code{Preelaborate}, then the client should have an
24141 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24143 @emph{In the case of instantiating a generic subprogram, it is always
24144 sufficient to have only an @code{Elaborate} pragma for the
24145 @code{with}'ed unit.}
24149 By following this rule a client is assured that calls and instantiations
24150 can be made without risk of an exception.
24152 In this mode GNAT traces all calls that are potentially made from
24153 elaboration code, and puts in any missing implicit @code{Elaborate}
24154 and @code{Elaborate_All} pragmas.
24155 The advantage of this approach is that no elaboration problems
24156 are possible if the binder can find an elaboration order that is
24157 consistent with these implicit @code{Elaborate} and
24158 @code{Elaborate_All} pragmas. The
24159 disadvantage of this approach is that no such order may exist.
24161 If the binder does not generate any diagnostics, then it means that it has
24162 found an elaboration order that is guaranteed to be safe. However, the binder
24163 may still be relying on implicitly generated @code{Elaborate} and
24164 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24167 If it is important to guarantee portability, then the compilations should
24170 (warn on elaboration problems) switch. This will cause warning messages
24171 to be generated indicating the missing @code{Elaborate} and
24172 @code{Elaborate_All} pragmas.
24173 Consider the following source program:
24175 @smallexample @c ada
24180 m : integer := k.r;
24187 where it is clear that there
24188 should be a pragma @code{Elaborate_All}
24189 for unit @code{k}. An implicit pragma will be generated, and it is
24190 likely that the binder will be able to honor it. However, if you want
24191 to port this program to some other Ada compiler than GNAT.
24192 it is safer to include the pragma explicitly in the source. If this
24193 unit is compiled with the
24195 switch, then the compiler outputs a warning:
24202 3. m : integer := k.r;
24204 >>> warning: call to "r" may raise Program_Error
24205 >>> warning: missing pragma Elaborate_All for "k"
24213 and these warnings can be used as a guide for supplying manually
24214 the missing pragmas. It is usually a bad idea to use this warning
24215 option during development. That's because it will warn you when
24216 you need to put in a pragma, but cannot warn you when it is time
24217 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24218 unnecessary dependencies and even false circularities.
24220 This default mode is more restrictive than the Ada Reference
24221 Manual, and it is possible to construct programs which will compile
24222 using the dynamic model described there, but will run into a
24223 circularity using the safer static model we have described.
24225 Of course any Ada compiler must be able to operate in a mode
24226 consistent with the requirements of the Ada Reference Manual,
24227 and in particular must have the capability of implementing the
24228 standard dynamic model of elaboration with run-time checks.
24230 In GNAT, this standard mode can be achieved either by the use of
24231 the @option{-gnatE} switch on the compiler (@command{gcc} or
24232 @command{gnatmake}) command, or by the use of the configuration pragma:
24234 @smallexample @c ada
24235 pragma Elaboration_Checks (DYNAMIC);
24239 Either approach will cause the unit affected to be compiled using the
24240 standard dynamic run-time elaboration checks described in the Ada
24241 Reference Manual. The static model is generally preferable, since it
24242 is clearly safer to rely on compile and link time checks rather than
24243 run-time checks. However, in the case of legacy code, it may be
24244 difficult to meet the requirements of the static model. This
24245 issue is further discussed in
24246 @ref{What to Do If the Default Elaboration Behavior Fails}.
24248 Note that the static model provides a strict subset of the allowed
24249 behavior and programs of the Ada Reference Manual, so if you do
24250 adhere to the static model and no circularities exist,
24251 then you are assured that your program will
24252 work using the dynamic model, providing that you remove any
24253 pragma Elaborate statements from the source.
24255 @node Treatment of Pragma Elaborate
24256 @section Treatment of Pragma Elaborate
24257 @cindex Pragma Elaborate
24260 The use of @code{pragma Elaborate}
24261 should generally be avoided in Ada 95 and Ada 2005 programs,
24262 since there is no guarantee that transitive calls
24263 will be properly handled. Indeed at one point, this pragma was placed
24264 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24266 Now that's a bit restrictive. In practice, the case in which
24267 @code{pragma Elaborate} is useful is when the caller knows that there
24268 are no transitive calls, or that the called unit contains all necessary
24269 transitive @code{pragma Elaborate} statements, and legacy code often
24270 contains such uses.
24272 Strictly speaking the static mode in GNAT should ignore such pragmas,
24273 since there is no assurance at compile time that the necessary safety
24274 conditions are met. In practice, this would cause GNAT to be incompatible
24275 with correctly written Ada 83 code that had all necessary
24276 @code{pragma Elaborate} statements in place. Consequently, we made the
24277 decision that GNAT in its default mode will believe that if it encounters
24278 a @code{pragma Elaborate} then the programmer knows what they are doing,
24279 and it will trust that no elaboration errors can occur.
24281 The result of this decision is two-fold. First to be safe using the
24282 static mode, you should remove all @code{pragma Elaborate} statements.
24283 Second, when fixing circularities in existing code, you can selectively
24284 use @code{pragma Elaborate} statements to convince the static mode of
24285 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24288 When using the static mode with @option{-gnatwl}, any use of
24289 @code{pragma Elaborate} will generate a warning about possible
24292 @node Elaboration Issues for Library Tasks
24293 @section Elaboration Issues for Library Tasks
24294 @cindex Library tasks, elaboration issues
24295 @cindex Elaboration of library tasks
24298 In this section we examine special elaboration issues that arise for
24299 programs that declare library level tasks.
24301 Generally the model of execution of an Ada program is that all units are
24302 elaborated, and then execution of the program starts. However, the
24303 declaration of library tasks definitely does not fit this model. The
24304 reason for this is that library tasks start as soon as they are declared
24305 (more precisely, as soon as the statement part of the enclosing package
24306 body is reached), that is to say before elaboration
24307 of the program is complete. This means that if such a task calls a
24308 subprogram, or an entry in another task, the callee may or may not be
24309 elaborated yet, and in the standard
24310 Reference Manual model of dynamic elaboration checks, you can even
24311 get timing dependent Program_Error exceptions, since there can be
24312 a race between the elaboration code and the task code.
24314 The static model of elaboration in GNAT seeks to avoid all such
24315 dynamic behavior, by being conservative, and the conservative
24316 approach in this particular case is to assume that all the code
24317 in a task body is potentially executed at elaboration time if
24318 a task is declared at the library level.
24320 This can definitely result in unexpected circularities. Consider
24321 the following example
24323 @smallexample @c ada
24329 type My_Int is new Integer;
24331 function Ident (M : My_Int) return My_Int;
24335 package body Decls is
24336 task body Lib_Task is
24342 function Ident (M : My_Int) return My_Int is
24350 procedure Put_Val (Arg : Decls.My_Int);
24354 package body Utils is
24355 procedure Put_Val (Arg : Decls.My_Int) is
24357 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24364 Decls.Lib_Task.Start;
24369 If the above example is compiled in the default static elaboration
24370 mode, then a circularity occurs. The circularity comes from the call
24371 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24372 this call occurs in elaboration code, we need an implicit pragma
24373 @code{Elaborate_All} for @code{Utils}. This means that not only must
24374 the spec and body of @code{Utils} be elaborated before the body
24375 of @code{Decls}, but also the spec and body of any unit that is
24376 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24377 the body of @code{Decls}. This is the transitive implication of
24378 pragma @code{Elaborate_All} and it makes sense, because in general
24379 the body of @code{Put_Val} might have a call to something in a
24380 @code{with'ed} unit.
24382 In this case, the body of Utils (actually its spec) @code{with's}
24383 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24384 must be elaborated before itself, in case there is a call from the
24385 body of @code{Utils}.
24387 Here is the exact chain of events we are worrying about:
24391 In the body of @code{Decls} a call is made from within the body of a library
24392 task to a subprogram in the package @code{Utils}. Since this call may
24393 occur at elaboration time (given that the task is activated at elaboration
24394 time), we have to assume the worst, i.e., that the
24395 call does happen at elaboration time.
24398 This means that the body and spec of @code{Util} must be elaborated before
24399 the body of @code{Decls} so that this call does not cause an access before
24403 Within the body of @code{Util}, specifically within the body of
24404 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24408 One such @code{with}'ed package is package @code{Decls}, so there
24409 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24410 In fact there is such a call in this example, but we would have to
24411 assume that there was such a call even if it were not there, since
24412 we are not supposed to write the body of @code{Decls} knowing what
24413 is in the body of @code{Utils}; certainly in the case of the
24414 static elaboration model, the compiler does not know what is in
24415 other bodies and must assume the worst.
24418 This means that the spec and body of @code{Decls} must also be
24419 elaborated before we elaborate the unit containing the call, but
24420 that unit is @code{Decls}! This means that the body of @code{Decls}
24421 must be elaborated before itself, and that's a circularity.
24425 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24426 the body of @code{Decls} you will get a true Ada Reference Manual
24427 circularity that makes the program illegal.
24429 In practice, we have found that problems with the static model of
24430 elaboration in existing code often arise from library tasks, so
24431 we must address this particular situation.
24433 Note that if we compile and run the program above, using the dynamic model of
24434 elaboration (that is to say use the @option{-gnatE} switch),
24435 then it compiles, binds,
24436 links, and runs, printing the expected result of 2. Therefore in some sense
24437 the circularity here is only apparent, and we need to capture
24438 the properties of this program that distinguish it from other library-level
24439 tasks that have real elaboration problems.
24441 We have four possible answers to this question:
24446 Use the dynamic model of elaboration.
24448 If we use the @option{-gnatE} switch, then as noted above, the program works.
24449 Why is this? If we examine the task body, it is apparent that the task cannot
24451 @code{accept} statement until after elaboration has been completed, because
24452 the corresponding entry call comes from the main program, not earlier.
24453 This is why the dynamic model works here. But that's really giving
24454 up on a precise analysis, and we prefer to take this approach only if we cannot
24456 problem in any other manner. So let us examine two ways to reorganize
24457 the program to avoid the potential elaboration problem.
24460 Split library tasks into separate packages.
24462 Write separate packages, so that library tasks are isolated from
24463 other declarations as much as possible. Let us look at a variation on
24466 @smallexample @c ada
24474 package body Decls1 is
24475 task body Lib_Task is
24483 type My_Int is new Integer;
24484 function Ident (M : My_Int) return My_Int;
24488 package body Decls2 is
24489 function Ident (M : My_Int) return My_Int is
24497 procedure Put_Val (Arg : Decls2.My_Int);
24501 package body Utils is
24502 procedure Put_Val (Arg : Decls2.My_Int) is
24504 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24511 Decls1.Lib_Task.Start;
24516 All we have done is to split @code{Decls} into two packages, one
24517 containing the library task, and one containing everything else. Now
24518 there is no cycle, and the program compiles, binds, links and executes
24519 using the default static model of elaboration.
24522 Declare separate task types.
24524 A significant part of the problem arises because of the use of the
24525 single task declaration form. This means that the elaboration of
24526 the task type, and the elaboration of the task itself (i.e.@: the
24527 creation of the task) happen at the same time. A good rule
24528 of style in Ada is to always create explicit task types. By
24529 following the additional step of placing task objects in separate
24530 packages from the task type declaration, many elaboration problems
24531 are avoided. Here is another modified example of the example program:
24533 @smallexample @c ada
24535 task type Lib_Task_Type is
24539 type My_Int is new Integer;
24541 function Ident (M : My_Int) return My_Int;
24545 package body Decls is
24546 task body Lib_Task_Type is
24552 function Ident (M : My_Int) return My_Int is
24560 procedure Put_Val (Arg : Decls.My_Int);
24564 package body Utils is
24565 procedure Put_Val (Arg : Decls.My_Int) is
24567 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24573 Lib_Task : Decls.Lib_Task_Type;
24579 Declst.Lib_Task.Start;
24584 What we have done here is to replace the @code{task} declaration in
24585 package @code{Decls} with a @code{task type} declaration. Then we
24586 introduce a separate package @code{Declst} to contain the actual
24587 task object. This separates the elaboration issues for
24588 the @code{task type}
24589 declaration, which causes no trouble, from the elaboration issues
24590 of the task object, which is also unproblematic, since it is now independent
24591 of the elaboration of @code{Utils}.
24592 This separation of concerns also corresponds to
24593 a generally sound engineering principle of separating declarations
24594 from instances. This version of the program also compiles, binds, links,
24595 and executes, generating the expected output.
24598 Use No_Entry_Calls_In_Elaboration_Code restriction.
24599 @cindex No_Entry_Calls_In_Elaboration_Code
24601 The previous two approaches described how a program can be restructured
24602 to avoid the special problems caused by library task bodies. in practice,
24603 however, such restructuring may be difficult to apply to existing legacy code,
24604 so we must consider solutions that do not require massive rewriting.
24606 Let us consider more carefully why our original sample program works
24607 under the dynamic model of elaboration. The reason is that the code
24608 in the task body blocks immediately on the @code{accept}
24609 statement. Now of course there is nothing to prohibit elaboration
24610 code from making entry calls (for example from another library level task),
24611 so we cannot tell in isolation that
24612 the task will not execute the accept statement during elaboration.
24614 However, in practice it is very unusual to see elaboration code
24615 make any entry calls, and the pattern of tasks starting
24616 at elaboration time and then immediately blocking on @code{accept} or
24617 @code{select} statements is very common. What this means is that
24618 the compiler is being too pessimistic when it analyzes the
24619 whole package body as though it might be executed at elaboration
24622 If we know that the elaboration code contains no entry calls, (a very safe
24623 assumption most of the time, that could almost be made the default
24624 behavior), then we can compile all units of the program under control
24625 of the following configuration pragma:
24628 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24632 This pragma can be placed in the @file{gnat.adc} file in the usual
24633 manner. If we take our original unmodified program and compile it
24634 in the presence of a @file{gnat.adc} containing the above pragma,
24635 then once again, we can compile, bind, link, and execute, obtaining
24636 the expected result. In the presence of this pragma, the compiler does
24637 not trace calls in a task body, that appear after the first @code{accept}
24638 or @code{select} statement, and therefore does not report a potential
24639 circularity in the original program.
24641 The compiler will check to the extent it can that the above
24642 restriction is not violated, but it is not always possible to do a
24643 complete check at compile time, so it is important to use this
24644 pragma only if the stated restriction is in fact met, that is to say
24645 no task receives an entry call before elaboration of all units is completed.
24649 @node Mixing Elaboration Models
24650 @section Mixing Elaboration Models
24652 So far, we have assumed that the entire program is either compiled
24653 using the dynamic model or static model, ensuring consistency. It
24654 is possible to mix the two models, but rules have to be followed
24655 if this mixing is done to ensure that elaboration checks are not
24658 The basic rule is that @emph{a unit compiled with the static model cannot
24659 be @code{with'ed} by a unit compiled with the dynamic model}. The
24660 reason for this is that in the static model, a unit assumes that
24661 its clients guarantee to use (the equivalent of) pragma
24662 @code{Elaborate_All} so that no elaboration checks are required
24663 in inner subprograms, and this assumption is violated if the
24664 client is compiled with dynamic checks.
24666 The precise rule is as follows. A unit that is compiled with dynamic
24667 checks can only @code{with} a unit that meets at least one of the
24668 following criteria:
24673 The @code{with'ed} unit is itself compiled with dynamic elaboration
24674 checks (that is with the @option{-gnatE} switch.
24677 The @code{with'ed} unit is an internal GNAT implementation unit from
24678 the System, Interfaces, Ada, or GNAT hierarchies.
24681 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24684 The @code{with'ing} unit (that is the client) has an explicit pragma
24685 @code{Elaborate_All} for the @code{with'ed} unit.
24690 If this rule is violated, that is if a unit with dynamic elaboration
24691 checks @code{with's} a unit that does not meet one of the above four
24692 criteria, then the binder (@code{gnatbind}) will issue a warning
24693 similar to that in the following example:
24696 warning: "x.ads" has dynamic elaboration checks and with's
24697 warning: "y.ads" which has static elaboration checks
24701 These warnings indicate that the rule has been violated, and that as a result
24702 elaboration checks may be missed in the resulting executable file.
24703 This warning may be suppressed using the @option{-ws} binder switch
24704 in the usual manner.
24706 One useful application of this mixing rule is in the case of a subsystem
24707 which does not itself @code{with} units from the remainder of the
24708 application. In this case, the entire subsystem can be compiled with
24709 dynamic checks to resolve a circularity in the subsystem, while
24710 allowing the main application that uses this subsystem to be compiled
24711 using the more reliable default static model.
24713 @node What to Do If the Default Elaboration Behavior Fails
24714 @section What to Do If the Default Elaboration Behavior Fails
24717 If the binder cannot find an acceptable order, it outputs detailed
24718 diagnostics. For example:
24724 error: elaboration circularity detected
24725 info: "proc (body)" must be elaborated before "pack (body)"
24726 info: reason: Elaborate_All probably needed in unit "pack (body)"
24727 info: recompile "pack (body)" with -gnatwl
24728 info: for full details
24729 info: "proc (body)"
24730 info: is needed by its spec:
24731 info: "proc (spec)"
24732 info: which is withed by:
24733 info: "pack (body)"
24734 info: "pack (body)" must be elaborated before "proc (body)"
24735 info: reason: pragma Elaborate in unit "proc (body)"
24741 In this case we have a cycle that the binder cannot break. On the one
24742 hand, there is an explicit pragma Elaborate in @code{proc} for
24743 @code{pack}. This means that the body of @code{pack} must be elaborated
24744 before the body of @code{proc}. On the other hand, there is elaboration
24745 code in @code{pack} that calls a subprogram in @code{proc}. This means
24746 that for maximum safety, there should really be a pragma
24747 Elaborate_All in @code{pack} for @code{proc} which would require that
24748 the body of @code{proc} be elaborated before the body of
24749 @code{pack}. Clearly both requirements cannot be satisfied.
24750 Faced with a circularity of this kind, you have three different options.
24753 @item Fix the program
24754 The most desirable option from the point of view of long-term maintenance
24755 is to rearrange the program so that the elaboration problems are avoided.
24756 One useful technique is to place the elaboration code into separate
24757 child packages. Another is to move some of the initialization code to
24758 explicitly called subprograms, where the program controls the order
24759 of initialization explicitly. Although this is the most desirable option,
24760 it may be impractical and involve too much modification, especially in
24761 the case of complex legacy code.
24763 @item Perform dynamic checks
24764 If the compilations are done using the
24766 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24767 manner. Dynamic checks are generated for all calls that could possibly result
24768 in raising an exception. With this switch, the compiler does not generate
24769 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24770 exactly as specified in the @cite{Ada Reference Manual}.
24771 The binder will generate
24772 an executable program that may or may not raise @code{Program_Error}, and then
24773 it is the programmer's job to ensure that it does not raise an exception. Note
24774 that it is important to compile all units with the switch, it cannot be used
24777 @item Suppress checks
24778 The drawback of dynamic checks is that they generate a
24779 significant overhead at run time, both in space and time. If you
24780 are absolutely sure that your program cannot raise any elaboration
24781 exceptions, and you still want to use the dynamic elaboration model,
24782 then you can use the configuration pragma
24783 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24784 example this pragma could be placed in the @file{gnat.adc} file.
24786 @item Suppress checks selectively
24787 When you know that certain calls or instantiations in elaboration code cannot
24788 possibly lead to an elaboration error, and the binder nevertheless complains
24789 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24790 elaboration circularities, it is possible to remove those warnings locally and
24791 obtain a program that will bind. Clearly this can be unsafe, and it is the
24792 responsibility of the programmer to make sure that the resulting program has no
24793 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24794 used with different granularity to suppress warnings and break elaboration
24799 Place the pragma that names the called subprogram in the declarative part
24800 that contains the call.
24803 Place the pragma in the declarative part, without naming an entity. This
24804 disables warnings on all calls in the corresponding declarative region.
24807 Place the pragma in the package spec that declares the called subprogram,
24808 and name the subprogram. This disables warnings on all elaboration calls to
24812 Place the pragma in the package spec that declares the called subprogram,
24813 without naming any entity. This disables warnings on all elaboration calls to
24814 all subprograms declared in this spec.
24816 @item Use Pragma Elaborate
24817 As previously described in section @xref{Treatment of Pragma Elaborate},
24818 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24819 that no elaboration checks are required on calls to the designated unit.
24820 There may be cases in which the caller knows that no transitive calls
24821 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24822 case where @code{pragma Elaborate_All} would cause a circularity.
24826 These five cases are listed in order of decreasing safety, and therefore
24827 require increasing programmer care in their application. Consider the
24830 @smallexample @c adanocomment
24832 function F1 return Integer;
24837 function F2 return Integer;
24838 function Pure (x : integer) return integer;
24839 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
24840 -- pragma Suppress (Elaboration_Check); -- (4)
24844 package body Pack1 is
24845 function F1 return Integer is
24849 Val : integer := Pack2.Pure (11); -- Elab. call (1)
24852 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
24853 -- pragma Suppress(Elaboration_Check); -- (2)
24855 X1 := Pack2.F2 + 1; -- Elab. call (2)
24860 package body Pack2 is
24861 function F2 return Integer is
24865 function Pure (x : integer) return integer is
24867 return x ** 3 - 3 * x;
24871 with Pack1, Ada.Text_IO;
24874 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24877 In the absence of any pragmas, an attempt to bind this program produces
24878 the following diagnostics:
24884 error: elaboration circularity detected
24885 info: "pack1 (body)" must be elaborated before "pack1 (body)"
24886 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
24887 info: recompile "pack1 (body)" with -gnatwl for full details
24888 info: "pack1 (body)"
24889 info: must be elaborated along with its spec:
24890 info: "pack1 (spec)"
24891 info: which is withed by:
24892 info: "pack2 (body)"
24893 info: which must be elaborated along with its spec:
24894 info: "pack2 (spec)"
24895 info: which is withed by:
24896 info: "pack1 (body)"
24899 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24900 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24901 F2 is safe, even though F2 calls F1, because the call appears after the
24902 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24903 remove the warning on the call. It is also possible to use pragma (2)
24904 because there are no other potentially unsafe calls in the block.
24907 The call to @code{Pure} is safe because this function does not depend on the
24908 state of @code{Pack2}. Therefore any call to this function is safe, and it
24909 is correct to place pragma (3) in the corresponding package spec.
24912 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24913 warnings on all calls to functions declared therein. Note that this is not
24914 necessarily safe, and requires more detailed examination of the subprogram
24915 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24916 be already elaborated.
24920 It is hard to generalize on which of these four approaches should be
24921 taken. Obviously if it is possible to fix the program so that the default
24922 treatment works, this is preferable, but this may not always be practical.
24923 It is certainly simple enough to use
24925 but the danger in this case is that, even if the GNAT binder
24926 finds a correct elaboration order, it may not always do so,
24927 and certainly a binder from another Ada compiler might not. A
24928 combination of testing and analysis (for which the warnings generated
24931 switch can be useful) must be used to ensure that the program is free
24932 of errors. One switch that is useful in this testing is the
24933 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24936 Normally the binder tries to find an order that has the best chance
24937 of avoiding elaboration problems. However, if this switch is used, the binder
24938 plays a devil's advocate role, and tries to choose the order that
24939 has the best chance of failing. If your program works even with this
24940 switch, then it has a better chance of being error free, but this is still
24943 For an example of this approach in action, consider the C-tests (executable
24944 tests) from the ACVC suite. If these are compiled and run with the default
24945 treatment, then all but one of them succeed without generating any error
24946 diagnostics from the binder. However, there is one test that fails, and
24947 this is not surprising, because the whole point of this test is to ensure
24948 that the compiler can handle cases where it is impossible to determine
24949 a correct order statically, and it checks that an exception is indeed
24950 raised at run time.
24952 This one test must be compiled and run using the
24954 switch, and then it passes. Alternatively, the entire suite can
24955 be run using this switch. It is never wrong to run with the dynamic
24956 elaboration switch if your code is correct, and we assume that the
24957 C-tests are indeed correct (it is less efficient, but efficiency is
24958 not a factor in running the ACVC tests.)
24960 @node Elaboration for Access-to-Subprogram Values
24961 @section Elaboration for Access-to-Subprogram Values
24962 @cindex Access-to-subprogram
24965 Access-to-subprogram types (introduced in Ada 95) complicate
24966 the handling of elaboration. The trouble is that it becomes
24967 impossible to tell at compile time which procedure
24968 is being called. This means that it is not possible for the binder
24969 to analyze the elaboration requirements in this case.
24971 If at the point at which the access value is created
24972 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24973 the body of the subprogram is
24974 known to have been elaborated, then the access value is safe, and its use
24975 does not require a check. This may be achieved by appropriate arrangement
24976 of the order of declarations if the subprogram is in the current unit,
24977 or, if the subprogram is in another unit, by using pragma
24978 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24979 on the referenced unit.
24981 If the referenced body is not known to have been elaborated at the point
24982 the access value is created, then any use of the access value must do a
24983 dynamic check, and this dynamic check will fail and raise a
24984 @code{Program_Error} exception if the body has not been elaborated yet.
24985 GNAT will generate the necessary checks, and in addition, if the
24987 switch is set, will generate warnings that such checks are required.
24989 The use of dynamic dispatching for tagged types similarly generates
24990 a requirement for dynamic checks, and premature calls to any primitive
24991 operation of a tagged type before the body of the operation has been
24992 elaborated, will result in the raising of @code{Program_Error}.
24994 @node Summary of Procedures for Elaboration Control
24995 @section Summary of Procedures for Elaboration Control
24996 @cindex Elaboration control
24999 First, compile your program with the default options, using none of
25000 the special elaboration control switches. If the binder successfully
25001 binds your program, then you can be confident that, apart from issues
25002 raised by the use of access-to-subprogram types and dynamic dispatching,
25003 the program is free of elaboration errors. If it is important that the
25004 program be portable, then use the
25006 switch to generate warnings about missing @code{Elaborate} or
25007 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25009 If the program fails to bind using the default static elaboration
25010 handling, then you can fix the program to eliminate the binder
25011 message, or recompile the entire program with the
25012 @option{-gnatE} switch to generate dynamic elaboration checks,
25013 and, if you are sure there really are no elaboration problems,
25014 use a global pragma @code{Suppress (Elaboration_Check)}.
25016 @node Other Elaboration Order Considerations
25017 @section Other Elaboration Order Considerations
25019 This section has been entirely concerned with the issue of finding a valid
25020 elaboration order, as defined by the Ada Reference Manual. In a case
25021 where several elaboration orders are valid, the task is to find one
25022 of the possible valid elaboration orders (and the static model in GNAT
25023 will ensure that this is achieved).
25025 The purpose of the elaboration rules in the Ada Reference Manual is to
25026 make sure that no entity is accessed before it has been elaborated. For
25027 a subprogram, this means that the spec and body must have been elaborated
25028 before the subprogram is called. For an object, this means that the object
25029 must have been elaborated before its value is read or written. A violation
25030 of either of these two requirements is an access before elaboration order,
25031 and this section has been all about avoiding such errors.
25033 In the case where more than one order of elaboration is possible, in the
25034 sense that access before elaboration errors are avoided, then any one of
25035 the orders is ``correct'' in the sense that it meets the requirements of
25036 the Ada Reference Manual, and no such error occurs.
25038 However, it may be the case for a given program, that there are
25039 constraints on the order of elaboration that come not from consideration
25040 of avoiding elaboration errors, but rather from extra-lingual logic
25041 requirements. Consider this example:
25043 @smallexample @c ada
25044 with Init_Constants;
25045 package Constants is
25050 package Init_Constants is
25051 procedure P; -- require a body
25052 end Init_Constants;
25055 package body Init_Constants is
25056 procedure P is begin null; end;
25060 end Init_Constants;
25064 Z : Integer := Constants.X + Constants.Y;
25068 with Text_IO; use Text_IO;
25071 Put_Line (Calc.Z'Img);
25076 In this example, there is more than one valid order of elaboration. For
25077 example both the following are correct orders:
25080 Init_Constants spec
25083 Init_Constants body
25088 Init_Constants spec
25089 Init_Constants body
25096 There is no language rule to prefer one or the other, both are correct
25097 from an order of elaboration point of view. But the programmatic effects
25098 of the two orders are very different. In the first, the elaboration routine
25099 of @code{Calc} initializes @code{Z} to zero, and then the main program
25100 runs with this value of zero. But in the second order, the elaboration
25101 routine of @code{Calc} runs after the body of Init_Constants has set
25102 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25105 One could perhaps by applying pretty clever non-artificial intelligence
25106 to the situation guess that it is more likely that the second order of
25107 elaboration is the one desired, but there is no formal linguistic reason
25108 to prefer one over the other. In fact in this particular case, GNAT will
25109 prefer the second order, because of the rule that bodies are elaborated
25110 as soon as possible, but it's just luck that this is what was wanted
25111 (if indeed the second order was preferred).
25113 If the program cares about the order of elaboration routines in a case like
25114 this, it is important to specify the order required. In this particular
25115 case, that could have been achieved by adding to the spec of Calc:
25117 @smallexample @c ada
25118 pragma Elaborate_All (Constants);
25122 which requires that the body (if any) and spec of @code{Constants},
25123 as well as the body and spec of any unit @code{with}'ed by
25124 @code{Constants} be elaborated before @code{Calc} is elaborated.
25126 Clearly no automatic method can always guess which alternative you require,
25127 and if you are working with legacy code that had constraints of this kind
25128 which were not properly specified by adding @code{Elaborate} or
25129 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25130 compilers can choose different orders.
25132 However, GNAT does attempt to diagnose the common situation where there
25133 are uninitialized variables in the visible part of a package spec, and the
25134 corresponding package body has an elaboration block that directly or
25135 indirectly initialized one or more of these variables. This is the situation
25136 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25137 a warning that suggests this addition if it detects this situation.
25139 The @code{gnatbind}
25140 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25141 out problems. This switch causes bodies to be elaborated as late as possible
25142 instead of as early as possible. In the example above, it would have forced
25143 the choice of the first elaboration order. If you get different results
25144 when using this switch, and particularly if one set of results is right,
25145 and one is wrong as far as you are concerned, it shows that you have some
25146 missing @code{Elaborate} pragmas. For the example above, we have the
25150 gnatmake -f -q main
25153 gnatmake -f -q main -bargs -p
25159 It is of course quite unlikely that both these results are correct, so
25160 it is up to you in a case like this to investigate the source of the
25161 difference, by looking at the two elaboration orders that are chosen,
25162 and figuring out which is correct, and then adding the necessary
25163 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25167 @c *******************************
25168 @node Conditional Compilation
25169 @appendix Conditional Compilation
25170 @c *******************************
25171 @cindex Conditional compilation
25174 It is often necessary to arrange for a single source program
25175 to serve multiple purposes, where it is compiled in different
25176 ways to achieve these different goals. Some examples of the
25177 need for this feature are
25180 @item Adapting a program to a different hardware environment
25181 @item Adapting a program to a different target architecture
25182 @item Turning debugging features on and off
25183 @item Arranging for a program to compile with different compilers
25187 In C, or C++, the typical approach would be to use the preprocessor
25188 that is defined as part of the language. The Ada language does not
25189 contain such a feature. This is not an oversight, but rather a very
25190 deliberate design decision, based on the experience that overuse of
25191 the preprocessing features in C and C++ can result in programs that
25192 are extremely difficult to maintain. For example, if we have ten
25193 switches that can be on or off, this means that there are a thousand
25194 separate programs, any one of which might not even be syntactically
25195 correct, and even if syntactically correct, the resulting program
25196 might not work correctly. Testing all combinations can quickly become
25199 Nevertheless, the need to tailor programs certainly exists, and in
25200 this Appendix we will discuss how this can
25201 be achieved using Ada in general, and GNAT in particular.
25204 * Use of Boolean Constants::
25205 * Debugging - A Special Case::
25206 * Conditionalizing Declarations::
25207 * Use of Alternative Implementations::
25211 @node Use of Boolean Constants
25212 @section Use of Boolean Constants
25215 In the case where the difference is simply which code
25216 sequence is executed, the cleanest solution is to use Boolean
25217 constants to control which code is executed.
25219 @smallexample @c ada
25221 FP_Initialize_Required : constant Boolean := True;
25223 if FP_Initialize_Required then
25230 Not only will the code inside the @code{if} statement not be executed if
25231 the constant Boolean is @code{False}, but it will also be completely
25232 deleted from the program.
25233 However, the code is only deleted after the @code{if} statement
25234 has been checked for syntactic and semantic correctness.
25235 (In contrast, with preprocessors the code is deleted before the
25236 compiler ever gets to see it, so it is not checked until the switch
25238 @cindex Preprocessors (contrasted with conditional compilation)
25240 Typically the Boolean constants will be in a separate package,
25243 @smallexample @c ada
25246 FP_Initialize_Required : constant Boolean := True;
25247 Reset_Available : constant Boolean := False;
25254 The @code{Config} package exists in multiple forms for the various targets,
25255 with an appropriate script selecting the version of @code{Config} needed.
25256 Then any other unit requiring conditional compilation can do a @code{with}
25257 of @code{Config} to make the constants visible.
25260 @node Debugging - A Special Case
25261 @section Debugging - A Special Case
25264 A common use of conditional code is to execute statements (for example
25265 dynamic checks, or output of intermediate results) under control of a
25266 debug switch, so that the debugging behavior can be turned on and off.
25267 This can be done using a Boolean constant to control whether the code
25270 @smallexample @c ada
25273 Put_Line ("got to the first stage!");
25281 @smallexample @c ada
25283 if Debugging and then Temperature > 999.0 then
25284 raise Temperature_Crazy;
25290 Since this is a common case, there are special features to deal with
25291 this in a convenient manner. For the case of tests, Ada 2005 has added
25292 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25293 @cindex pragma @code{Assert}
25294 on the @code{Assert} pragma that has always been available in GNAT, so this
25295 feature may be used with GNAT even if you are not using Ada 2005 features.
25296 The use of pragma @code{Assert} is described in
25297 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25298 example, the last test could be written:
25300 @smallexample @c ada
25301 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
25307 @smallexample @c ada
25308 pragma Assert (Temperature <= 999.0);
25312 In both cases, if assertions are active and the temperature is excessive,
25313 the exception @code{Assert_Failure} will be raised, with the given string in
25314 the first case or a string indicating the location of the pragma in the second
25315 case used as the exception message.
25317 You can turn assertions on and off by using the @code{Assertion_Policy}
25319 @cindex pragma @code{Assertion_Policy}
25320 This is an Ada 2005 pragma which is implemented in all modes by
25321 GNAT, but only in the latest versions of GNAT which include Ada 2005
25322 capability. Alternatively, you can use the @option{-gnata} switch
25323 @cindex @option{-gnata} switch
25324 to enable assertions from the command line (this is recognized by all versions
25327 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25328 @code{Debug} can be used:
25329 @cindex pragma @code{Debug}
25331 @smallexample @c ada
25332 pragma Debug (Put_Line ("got to the first stage!"));
25336 If debug pragmas are enabled, the argument, which must be of the form of
25337 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25338 Only one call can be present, but of course a special debugging procedure
25339 containing any code you like can be included in the program and then
25340 called in a pragma @code{Debug} argument as needed.
25342 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25343 construct is that pragma @code{Debug} can appear in declarative contexts,
25344 such as at the very beginning of a procedure, before local declarations have
25347 Debug pragmas are enabled using either the @option{-gnata} switch that also
25348 controls assertions, or with a separate Debug_Policy pragma.
25349 @cindex pragma @code{Debug_Policy}
25350 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25351 in Ada 95 and Ada 83 programs as well), and is analogous to
25352 pragma @code{Assertion_Policy} to control assertions.
25354 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25355 and thus they can appear in @file{gnat.adc} if you are not using a
25356 project file, or in the file designated to contain configuration pragmas
25358 They then apply to all subsequent compilations. In practice the use of
25359 the @option{-gnata} switch is often the most convenient method of controlling
25360 the status of these pragmas.
25362 Note that a pragma is not a statement, so in contexts where a statement
25363 sequence is required, you can't just write a pragma on its own. You have
25364 to add a @code{null} statement.
25366 @smallexample @c ada
25369 @dots{} -- some statements
25371 pragma Assert (Num_Cases < 10);
25378 @node Conditionalizing Declarations
25379 @section Conditionalizing Declarations
25382 In some cases, it may be necessary to conditionalize declarations to meet
25383 different requirements. For example we might want a bit string whose length
25384 is set to meet some hardware message requirement.
25386 In some cases, it may be possible to do this using declare blocks controlled
25387 by conditional constants:
25389 @smallexample @c ada
25391 if Small_Machine then
25393 X : Bit_String (1 .. 10);
25399 X : Large_Bit_String (1 .. 1000);
25408 Note that in this approach, both declarations are analyzed by the
25409 compiler so this can only be used where both declarations are legal,
25410 even though one of them will not be used.
25412 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25413 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25414 that are parameterized by these constants. For example
25416 @smallexample @c ada
25419 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25425 If @code{Bits_Per_Word} is set to 32, this generates either
25427 @smallexample @c ada
25430 Field1 at 0 range 0 .. 32;
25436 for the big endian case, or
25438 @smallexample @c ada
25441 Field1 at 0 range 10 .. 32;
25447 for the little endian case. Since a powerful subset of Ada expression
25448 notation is usable for creating static constants, clever use of this
25449 feature can often solve quite difficult problems in conditionalizing
25450 compilation (note incidentally that in Ada 95, the little endian
25451 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25452 need to define this one yourself).
25455 @node Use of Alternative Implementations
25456 @section Use of Alternative Implementations
25459 In some cases, none of the approaches described above are adequate. This
25460 can occur for example if the set of declarations required is radically
25461 different for two different configurations.
25463 In this situation, the official Ada way of dealing with conditionalizing
25464 such code is to write separate units for the different cases. As long as
25465 this does not result in excessive duplication of code, this can be done
25466 without creating maintenance problems. The approach is to share common
25467 code as far as possible, and then isolate the code and declarations
25468 that are different. Subunits are often a convenient method for breaking
25469 out a piece of a unit that is to be conditionalized, with separate files
25470 for different versions of the subunit for different targets, where the
25471 build script selects the right one to give to the compiler.
25472 @cindex Subunits (and conditional compilation)
25474 As an example, consider a situation where a new feature in Ada 2005
25475 allows something to be done in a really nice way. But your code must be able
25476 to compile with an Ada 95 compiler. Conceptually you want to say:
25478 @smallexample @c ada
25481 @dots{} neat Ada 2005 code
25483 @dots{} not quite as neat Ada 95 code
25489 where @code{Ada_2005} is a Boolean constant.
25491 But this won't work when @code{Ada_2005} is set to @code{False},
25492 since the @code{then} clause will be illegal for an Ada 95 compiler.
25493 (Recall that although such unreachable code would eventually be deleted
25494 by the compiler, it still needs to be legal. If it uses features
25495 introduced in Ada 2005, it will be illegal in Ada 95.)
25497 So instead we write
25499 @smallexample @c ada
25500 procedure Insert is separate;
25504 Then we have two files for the subunit @code{Insert}, with the two sets of
25506 If the package containing this is called @code{File_Queries}, then we might
25510 @item @file{file_queries-insert-2005.adb}
25511 @item @file{file_queries-insert-95.adb}
25515 and the build script renames the appropriate file to
25518 file_queries-insert.adb
25522 and then carries out the compilation.
25524 This can also be done with project files' naming schemes. For example:
25526 @smallexample @c project
25527 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25531 Note also that with project files it is desirable to use a different extension
25532 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25533 conflict may arise through another commonly used feature: to declare as part
25534 of the project a set of directories containing all the sources obeying the
25535 default naming scheme.
25537 The use of alternative units is certainly feasible in all situations,
25538 and for example the Ada part of the GNAT run-time is conditionalized
25539 based on the target architecture using this approach. As a specific example,
25540 consider the implementation of the AST feature in VMS. There is one
25548 which is the same for all architectures, and three bodies:
25552 used for all non-VMS operating systems
25553 @item s-asthan-vms-alpha.adb
25554 used for VMS on the Alpha
25555 @item s-asthan-vms-ia64.adb
25556 used for VMS on the ia64
25560 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25561 this operating system feature is not available, and the two remaining
25562 versions interface with the corresponding versions of VMS to provide
25563 VMS-compatible AST handling. The GNAT build script knows the architecture
25564 and operating system, and automatically selects the right version,
25565 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25567 Another style for arranging alternative implementations is through Ada's
25568 access-to-subprogram facility.
25569 In case some functionality is to be conditionally included,
25570 you can declare an access-to-procedure variable @code{Ref} that is initialized
25571 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25573 In some library package, set @code{Ref} to @code{Proc'Access} for some
25574 procedure @code{Proc} that performs the relevant processing.
25575 The initialization only occurs if the library package is included in the
25577 The same idea can also be implemented using tagged types and dispatching
25581 @node Preprocessing
25582 @section Preprocessing
25583 @cindex Preprocessing
25586 Although it is quite possible to conditionalize code without the use of
25587 C-style preprocessing, as described earlier in this section, it is
25588 nevertheless convenient in some cases to use the C approach. Moreover,
25589 older Ada compilers have often provided some preprocessing capability,
25590 so legacy code may depend on this approach, even though it is not
25593 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25594 extent on the various preprocessors that have been used
25595 with legacy code on other compilers, to enable easier transition).
25597 The preprocessor may be used in two separate modes. It can be used quite
25598 separately from the compiler, to generate a separate output source file
25599 that is then fed to the compiler as a separate step. This is the
25600 @code{gnatprep} utility, whose use is fully described in
25601 @ref{Preprocessing Using gnatprep}.
25602 @cindex @code{gnatprep}
25604 The preprocessing language allows such constructs as
25608 #if DEBUG or PRIORITY > 4 then
25609 bunch of declarations
25611 completely different bunch of declarations
25617 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25618 defined either on the command line or in a separate file.
25620 The other way of running the preprocessor is even closer to the C style and
25621 often more convenient. In this approach the preprocessing is integrated into
25622 the compilation process. The compiler is fed the preprocessor input which
25623 includes @code{#if} lines etc, and then the compiler carries out the
25624 preprocessing internally and processes the resulting output.
25625 For more details on this approach, see @ref{Integrated Preprocessing}.
25628 @c *******************************
25629 @node Inline Assembler
25630 @appendix Inline Assembler
25631 @c *******************************
25634 If you need to write low-level software that interacts directly
25635 with the hardware, Ada provides two ways to incorporate assembly
25636 language code into your program. First, you can import and invoke
25637 external routines written in assembly language, an Ada feature fully
25638 supported by GNAT@. However, for small sections of code it may be simpler
25639 or more efficient to include assembly language statements directly
25640 in your Ada source program, using the facilities of the implementation-defined
25641 package @code{System.Machine_Code}, which incorporates the gcc
25642 Inline Assembler. The Inline Assembler approach offers a number of advantages,
25643 including the following:
25646 @item No need to use non-Ada tools
25647 @item Consistent interface over different targets
25648 @item Automatic usage of the proper calling conventions
25649 @item Access to Ada constants and variables
25650 @item Definition of intrinsic routines
25651 @item Possibility of inlining a subprogram comprising assembler code
25652 @item Code optimizer can take Inline Assembler code into account
25655 This chapter presents a series of examples to show you how to use
25656 the Inline Assembler. Although it focuses on the Intel x86,
25657 the general approach applies also to other processors.
25658 It is assumed that you are familiar with Ada
25659 and with assembly language programming.
25662 * Basic Assembler Syntax::
25663 * A Simple Example of Inline Assembler::
25664 * Output Variables in Inline Assembler::
25665 * Input Variables in Inline Assembler::
25666 * Inlining Inline Assembler Code::
25667 * Other Asm Functionality::
25670 @c ---------------------------------------------------------------------------
25671 @node Basic Assembler Syntax
25672 @section Basic Assembler Syntax
25675 The assembler used by GNAT and gcc is based not on the Intel assembly
25676 language, but rather on a language that descends from the AT&T Unix
25677 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25678 The following table summarizes the main features of @emph{as} syntax
25679 and points out the differences from the Intel conventions.
25680 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25681 pre-processor) documentation for further information.
25684 @item Register names
25685 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25687 Intel: No extra punctuation; for example @code{eax}
25689 @item Immediate operand
25690 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25692 Intel: No extra punctuation; for example @code{4}
25695 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25697 Intel: No extra punctuation; for example @code{loc}
25699 @item Memory contents
25700 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25702 Intel: Square brackets; for example @code{[loc]}
25704 @item Register contents
25705 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25707 Intel: Square brackets; for example @code{[eax]}
25709 @item Hexadecimal numbers
25710 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25712 Intel: Trailing ``h''; for example @code{A0h}
25715 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25718 Intel: Implicit, deduced by assembler; for example @code{mov}
25720 @item Instruction repetition
25721 gcc / @emph{as}: Split into two lines; for example
25727 Intel: Keep on one line; for example @code{rep stosl}
25729 @item Order of operands
25730 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25732 Intel: Destination first; for example @code{mov eax, 4}
25735 @c ---------------------------------------------------------------------------
25736 @node A Simple Example of Inline Assembler
25737 @section A Simple Example of Inline Assembler
25740 The following example will generate a single assembly language statement,
25741 @code{nop}, which does nothing. Despite its lack of run-time effect,
25742 the example will be useful in illustrating the basics of
25743 the Inline Assembler facility.
25745 @smallexample @c ada
25747 with System.Machine_Code; use System.Machine_Code;
25748 procedure Nothing is
25755 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25756 here it takes one parameter, a @emph{template string} that must be a static
25757 expression and that will form the generated instruction.
25758 @code{Asm} may be regarded as a compile-time procedure that parses
25759 the template string and additional parameters (none here),
25760 from which it generates a sequence of assembly language instructions.
25762 The examples in this chapter will illustrate several of the forms
25763 for invoking @code{Asm}; a complete specification of the syntax
25764 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25767 Under the standard GNAT conventions, the @code{Nothing} procedure
25768 should be in a file named @file{nothing.adb}.
25769 You can build the executable in the usual way:
25773 However, the interesting aspect of this example is not its run-time behavior
25774 but rather the generated assembly code.
25775 To see this output, invoke the compiler as follows:
25777 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25779 where the options are:
25783 compile only (no bind or link)
25785 generate assembler listing
25786 @item -fomit-frame-pointer
25787 do not set up separate stack frames
25789 do not add runtime checks
25792 This gives a human-readable assembler version of the code. The resulting
25793 file will have the same name as the Ada source file, but with a @code{.s}
25794 extension. In our example, the file @file{nothing.s} has the following
25799 .file "nothing.adb"
25801 ___gnu_compiled_ada:
25804 .globl __ada_nothing
25816 The assembly code you included is clearly indicated by
25817 the compiler, between the @code{#APP} and @code{#NO_APP}
25818 delimiters. The character before the 'APP' and 'NOAPP'
25819 can differ on different targets. For example, GNU/Linux uses '#APP' while
25820 on NT you will see '/APP'.
25822 If you make a mistake in your assembler code (such as using the
25823 wrong size modifier, or using a wrong operand for the instruction) GNAT
25824 will report this error in a temporary file, which will be deleted when
25825 the compilation is finished. Generating an assembler file will help
25826 in such cases, since you can assemble this file separately using the
25827 @emph{as} assembler that comes with gcc.
25829 Assembling the file using the command
25832 as @file{nothing.s}
25835 will give you error messages whose lines correspond to the assembler
25836 input file, so you can easily find and correct any mistakes you made.
25837 If there are no errors, @emph{as} will generate an object file
25838 @file{nothing.out}.
25840 @c ---------------------------------------------------------------------------
25841 @node Output Variables in Inline Assembler
25842 @section Output Variables in Inline Assembler
25845 The examples in this section, showing how to access the processor flags,
25846 illustrate how to specify the destination operands for assembly language
25849 @smallexample @c ada
25851 with Interfaces; use Interfaces;
25852 with Ada.Text_IO; use Ada.Text_IO;
25853 with System.Machine_Code; use System.Machine_Code;
25854 procedure Get_Flags is
25855 Flags : Unsigned_32;
25858 Asm ("pushfl" & LF & HT & -- push flags on stack
25859 "popl %%eax" & LF & HT & -- load eax with flags
25860 "movl %%eax, %0", -- store flags in variable
25861 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25862 Put_Line ("Flags register:" & Flags'Img);
25867 In order to have a nicely aligned assembly listing, we have separated
25868 multiple assembler statements in the Asm template string with linefeed
25869 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25870 The resulting section of the assembly output file is:
25877 movl %eax, -40(%ebp)
25882 It would have been legal to write the Asm invocation as:
25885 Asm ("pushfl popl %%eax movl %%eax, %0")
25888 but in the generated assembler file, this would come out as:
25892 pushfl popl %eax movl %eax, -40(%ebp)
25896 which is not so convenient for the human reader.
25898 We use Ada comments
25899 at the end of each line to explain what the assembler instructions
25900 actually do. This is a useful convention.
25902 When writing Inline Assembler instructions, you need to precede each register
25903 and variable name with a percent sign. Since the assembler already requires
25904 a percent sign at the beginning of a register name, you need two consecutive
25905 percent signs for such names in the Asm template string, thus @code{%%eax}.
25906 In the generated assembly code, one of the percent signs will be stripped off.
25908 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25909 variables: operands you later define using @code{Input} or @code{Output}
25910 parameters to @code{Asm}.
25911 An output variable is illustrated in
25912 the third statement in the Asm template string:
25916 The intent is to store the contents of the eax register in a variable that can
25917 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
25918 necessarily work, since the compiler might optimize by using a register
25919 to hold Flags, and the expansion of the @code{movl} instruction would not be
25920 aware of this optimization. The solution is not to store the result directly
25921 but rather to advise the compiler to choose the correct operand form;
25922 that is the purpose of the @code{%0} output variable.
25924 Information about the output variable is supplied in the @code{Outputs}
25925 parameter to @code{Asm}:
25927 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25930 The output is defined by the @code{Asm_Output} attribute of the target type;
25931 the general format is
25933 Type'Asm_Output (constraint_string, variable_name)
25936 The constraint string directs the compiler how
25937 to store/access the associated variable. In the example
25939 Unsigned_32'Asm_Output ("=m", Flags);
25941 the @code{"m"} (memory) constraint tells the compiler that the variable
25942 @code{Flags} should be stored in a memory variable, thus preventing
25943 the optimizer from keeping it in a register. In contrast,
25945 Unsigned_32'Asm_Output ("=r", Flags);
25947 uses the @code{"r"} (register) constraint, telling the compiler to
25948 store the variable in a register.
25950 If the constraint is preceded by the equal character (@strong{=}), it tells
25951 the compiler that the variable will be used to store data into it.
25953 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25954 allowing the optimizer to choose whatever it deems best.
25956 There are a fairly large number of constraints, but the ones that are
25957 most useful (for the Intel x86 processor) are the following:
25963 global (i.e.@: can be stored anywhere)
25981 use one of eax, ebx, ecx or edx
25983 use one of eax, ebx, ecx, edx, esi or edi
25986 The full set of constraints is described in the gcc and @emph{as}
25987 documentation; note that it is possible to combine certain constraints
25988 in one constraint string.
25990 You specify the association of an output variable with an assembler operand
25991 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25993 @smallexample @c ada
25995 Asm ("pushfl" & LF & HT & -- push flags on stack
25996 "popl %%eax" & LF & HT & -- load eax with flags
25997 "movl %%eax, %0", -- store flags in variable
25998 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26002 @code{%0} will be replaced in the expanded code by the appropriate operand,
26004 the compiler decided for the @code{Flags} variable.
26006 In general, you may have any number of output variables:
26009 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26011 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26012 of @code{Asm_Output} attributes
26016 @smallexample @c ada
26018 Asm ("movl %%eax, %0" & LF & HT &
26019 "movl %%ebx, %1" & LF & HT &
26021 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
26022 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
26023 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
26027 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26028 in the Ada program.
26030 As a variation on the @code{Get_Flags} example, we can use the constraints
26031 string to direct the compiler to store the eax register into the @code{Flags}
26032 variable, instead of including the store instruction explicitly in the
26033 @code{Asm} template string:
26035 @smallexample @c ada
26037 with Interfaces; use Interfaces;
26038 with Ada.Text_IO; use Ada.Text_IO;
26039 with System.Machine_Code; use System.Machine_Code;
26040 procedure Get_Flags_2 is
26041 Flags : Unsigned_32;
26044 Asm ("pushfl" & LF & HT & -- push flags on stack
26045 "popl %%eax", -- save flags in eax
26046 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26047 Put_Line ("Flags register:" & Flags'Img);
26053 The @code{"a"} constraint tells the compiler that the @code{Flags}
26054 variable will come from the eax register. Here is the resulting code:
26062 movl %eax,-40(%ebp)
26067 The compiler generated the store of eax into Flags after
26068 expanding the assembler code.
26070 Actually, there was no need to pop the flags into the eax register;
26071 more simply, we could just pop the flags directly into the program variable:
26073 @smallexample @c ada
26075 with Interfaces; use Interfaces;
26076 with Ada.Text_IO; use Ada.Text_IO;
26077 with System.Machine_Code; use System.Machine_Code;
26078 procedure Get_Flags_3 is
26079 Flags : Unsigned_32;
26082 Asm ("pushfl" & LF & HT & -- push flags on stack
26083 "pop %0", -- save flags in Flags
26084 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26085 Put_Line ("Flags register:" & Flags'Img);
26090 @c ---------------------------------------------------------------------------
26091 @node Input Variables in Inline Assembler
26092 @section Input Variables in Inline Assembler
26095 The example in this section illustrates how to specify the source operands
26096 for assembly language statements.
26097 The program simply increments its input value by 1:
26099 @smallexample @c ada
26101 with Interfaces; use Interfaces;
26102 with Ada.Text_IO; use Ada.Text_IO;
26103 with System.Machine_Code; use System.Machine_Code;
26104 procedure Increment is
26106 function Incr (Value : Unsigned_32) return Unsigned_32 is
26107 Result : Unsigned_32;
26110 Outputs => Unsigned_32'Asm_Output ("=a", Result),
26111 Inputs => Unsigned_32'Asm_Input ("a", Value));
26115 Value : Unsigned_32;
26119 Put_Line ("Value before is" & Value'Img);
26120 Value := Incr (Value);
26121 Put_Line ("Value after is" & Value'Img);
26126 The @code{Outputs} parameter to @code{Asm} specifies
26127 that the result will be in the eax register and that it is to be stored
26128 in the @code{Result} variable.
26130 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26131 but with an @code{Asm_Input} attribute.
26132 The @code{"="} constraint, indicating an output value, is not present.
26134 You can have multiple input variables, in the same way that you can have more
26135 than one output variable.
26137 The parameter count (%0, %1) etc, still starts at the first output statement,
26138 and continues with the input statements.
26140 Just as the @code{Outputs} parameter causes the register to be stored into the
26141 target variable after execution of the assembler statements, so does the
26142 @code{Inputs} parameter cause its variable to be loaded into the register
26143 before execution of the assembler statements.
26145 Thus the effect of the @code{Asm} invocation is:
26147 @item load the 32-bit value of @code{Value} into eax
26148 @item execute the @code{incl %eax} instruction
26149 @item store the contents of eax into the @code{Result} variable
26152 The resulting assembler file (with @option{-O2} optimization) contains:
26155 _increment__incr.1:
26168 @c ---------------------------------------------------------------------------
26169 @node Inlining Inline Assembler Code
26170 @section Inlining Inline Assembler Code
26173 For a short subprogram such as the @code{Incr} function in the previous
26174 section, the overhead of the call and return (creating / deleting the stack
26175 frame) can be significant, compared to the amount of code in the subprogram
26176 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26177 which directs the compiler to expand invocations of the subprogram at the
26178 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26179 Here is the resulting program:
26181 @smallexample @c ada
26183 with Interfaces; use Interfaces;
26184 with Ada.Text_IO; use Ada.Text_IO;
26185 with System.Machine_Code; use System.Machine_Code;
26186 procedure Increment_2 is
26188 function Incr (Value : Unsigned_32) return Unsigned_32 is
26189 Result : Unsigned_32;
26192 Outputs => Unsigned_32'Asm_Output ("=a", Result),
26193 Inputs => Unsigned_32'Asm_Input ("a", Value));
26196 pragma Inline (Increment);
26198 Value : Unsigned_32;
26202 Put_Line ("Value before is" & Value'Img);
26203 Value := Increment (Value);
26204 Put_Line ("Value after is" & Value'Img);
26209 Compile the program with both optimization (@option{-O2}) and inlining
26210 (@option{-gnatn}) enabled.
26212 The @code{Incr} function is still compiled as usual, but at the
26213 point in @code{Increment} where our function used to be called:
26218 call _increment__incr.1
26223 the code for the function body directly appears:
26236 thus saving the overhead of stack frame setup and an out-of-line call.
26238 @c ---------------------------------------------------------------------------
26239 @node Other Asm Functionality
26240 @section Other @code{Asm} Functionality
26243 This section describes two important parameters to the @code{Asm}
26244 procedure: @code{Clobber}, which identifies register usage;
26245 and @code{Volatile}, which inhibits unwanted optimizations.
26248 * The Clobber Parameter::
26249 * The Volatile Parameter::
26252 @c ---------------------------------------------------------------------------
26253 @node The Clobber Parameter
26254 @subsection The @code{Clobber} Parameter
26257 One of the dangers of intermixing assembly language and a compiled language
26258 such as Ada is that the compiler needs to be aware of which registers are
26259 being used by the assembly code. In some cases, such as the earlier examples,
26260 the constraint string is sufficient to indicate register usage (e.g.,
26262 the eax register). But more generally, the compiler needs an explicit
26263 identification of the registers that are used by the Inline Assembly
26266 Using a register that the compiler doesn't know about
26267 could be a side effect of an instruction (like @code{mull}
26268 storing its result in both eax and edx).
26269 It can also arise from explicit register usage in your
26270 assembly code; for example:
26273 Asm ("movl %0, %%ebx" & LF & HT &
26275 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26276 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
26280 where the compiler (since it does not analyze the @code{Asm} template string)
26281 does not know you are using the ebx register.
26283 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26284 to identify the registers that will be used by your assembly code:
26288 Asm ("movl %0, %%ebx" & LF & HT &
26290 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26291 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
26296 The Clobber parameter is a static string expression specifying the
26297 register(s) you are using. Note that register names are @emph{not} prefixed
26298 by a percent sign. Also, if more than one register is used then their names
26299 are separated by commas; e.g., @code{"eax, ebx"}
26301 The @code{Clobber} parameter has several additional uses:
26303 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26304 @item Use ``register'' name @code{memory} if you changed a memory location
26307 @c ---------------------------------------------------------------------------
26308 @node The Volatile Parameter
26309 @subsection The @code{Volatile} Parameter
26310 @cindex Volatile parameter
26313 Compiler optimizations in the presence of Inline Assembler may sometimes have
26314 unwanted effects. For example, when an @code{Asm} invocation with an input
26315 variable is inside a loop, the compiler might move the loading of the input
26316 variable outside the loop, regarding it as a one-time initialization.
26318 If this effect is not desired, you can disable such optimizations by setting
26319 the @code{Volatile} parameter to @code{True}; for example:
26321 @smallexample @c ada
26323 Asm ("movl %0, %%ebx" & LF & HT &
26325 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26326 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
26332 By default, @code{Volatile} is set to @code{False} unless there is no
26333 @code{Outputs} parameter.
26335 Although setting @code{Volatile} to @code{True} prevents unwanted
26336 optimizations, it will also disable other optimizations that might be
26337 important for efficiency. In general, you should set @code{Volatile}
26338 to @code{True} only if the compiler's optimizations have created
26340 @c END OF INLINE ASSEMBLER CHAPTER
26341 @c ===============================
26343 @c ***********************************
26344 @c * Compatibility and Porting Guide *
26345 @c ***********************************
26346 @node Compatibility and Porting Guide
26347 @appendix Compatibility and Porting Guide
26350 This chapter describes the compatibility issues that may arise between
26351 GNAT and other Ada compilation systems (including those for Ada 83),
26352 and shows how GNAT can expedite porting
26353 applications developed in other Ada environments.
26356 * Compatibility with Ada 83::
26357 * Compatibility between Ada 95 and Ada 2005::
26358 * Implementation-dependent characteristics::
26359 * Compatibility with Other Ada Systems::
26360 * Representation Clauses::
26362 @c Brief section is only in non-VMS version
26363 @c Full chapter is in VMS version
26364 * Compatibility with HP Ada 83::
26367 * Transitioning to 64-Bit GNAT for OpenVMS::
26371 @node Compatibility with Ada 83
26372 @section Compatibility with Ada 83
26373 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26376 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
26377 particular, the design intention was that the difficulties associated
26378 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26379 that occur when moving from one Ada 83 system to another.
26381 However, there are a number of points at which there are minor
26382 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
26383 full details of these issues,
26384 and should be consulted for a complete treatment.
26386 following subsections treat the most likely issues to be encountered.
26389 * Legal Ada 83 programs that are illegal in Ada 95::
26390 * More deterministic semantics::
26391 * Changed semantics::
26392 * Other language compatibility issues::
26395 @node Legal Ada 83 programs that are illegal in Ada 95
26396 @subsection Legal Ada 83 programs that are illegal in Ada 95
26398 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26399 Ada 95 and thus also in Ada 2005:
26402 @item Character literals
26403 Some uses of character literals are ambiguous. Since Ada 95 has introduced
26404 @code{Wide_Character} as a new predefined character type, some uses of
26405 character literals that were legal in Ada 83 are illegal in Ada 95.
26407 @smallexample @c ada
26408 for Char in 'A' .. 'Z' loop @dots{} end loop;
26412 The problem is that @code{'A'} and @code{'Z'} could be from either
26413 @code{Character} or @code{Wide_Character}. The simplest correction
26414 is to make the type explicit; e.g.:
26415 @smallexample @c ada
26416 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
26419 @item New reserved words
26420 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26421 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26422 Existing Ada 83 code using any of these identifiers must be edited to
26423 use some alternative name.
26425 @item Freezing rules
26426 The rules in Ada 95 are slightly different with regard to the point at
26427 which entities are frozen, and representation pragmas and clauses are
26428 not permitted past the freeze point. This shows up most typically in
26429 the form of an error message complaining that a representation item
26430 appears too late, and the appropriate corrective action is to move
26431 the item nearer to the declaration of the entity to which it refers.
26433 A particular case is that representation pragmas
26436 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26438 cannot be applied to a subprogram body. If necessary, a separate subprogram
26439 declaration must be introduced to which the pragma can be applied.
26441 @item Optional bodies for library packages
26442 In Ada 83, a package that did not require a package body was nevertheless
26443 allowed to have one. This lead to certain surprises in compiling large
26444 systems (situations in which the body could be unexpectedly ignored by the
26445 binder). In Ada 95, if a package does not require a body then it is not
26446 permitted to have a body. To fix this problem, simply remove a redundant
26447 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26448 into the spec that makes the body required. One approach is to add a private
26449 part to the package declaration (if necessary), and define a parameterless
26450 procedure called @code{Requires_Body}, which must then be given a dummy
26451 procedure body in the package body, which then becomes required.
26452 Another approach (assuming that this does not introduce elaboration
26453 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26454 since one effect of this pragma is to require the presence of a package body.
26456 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26457 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26458 @code{Constraint_Error}.
26459 This means that it is illegal to have separate exception handlers for
26460 the two exceptions. The fix is simply to remove the handler for the
26461 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26462 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26464 @item Indefinite subtypes in generics
26465 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26466 as the actual for a generic formal private type, but then the instantiation
26467 would be illegal if there were any instances of declarations of variables
26468 of this type in the generic body. In Ada 95, to avoid this clear violation
26469 of the methodological principle known as the ``contract model'',
26470 the generic declaration explicitly indicates whether
26471 or not such instantiations are permitted. If a generic formal parameter
26472 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26473 subtype name, then it can be instantiated with indefinite types, but no
26474 stand-alone variables can be declared of this type. Any attempt to declare
26475 such a variable will result in an illegality at the time the generic is
26476 declared. If the @code{(<>)} notation is not used, then it is illegal
26477 to instantiate the generic with an indefinite type.
26478 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26479 It will show up as a compile time error, and
26480 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26483 @node More deterministic semantics
26484 @subsection More deterministic semantics
26488 Conversions from real types to integer types round away from 0. In Ada 83
26489 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
26490 implementation freedom was intended to support unbiased rounding in
26491 statistical applications, but in practice it interfered with portability.
26492 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26493 is required. Numeric code may be affected by this change in semantics.
26494 Note, though, that this issue is no worse than already existed in Ada 83
26495 when porting code from one vendor to another.
26498 The Real-Time Annex introduces a set of policies that define the behavior of
26499 features that were implementation dependent in Ada 83, such as the order in
26500 which open select branches are executed.
26503 @node Changed semantics
26504 @subsection Changed semantics
26507 The worst kind of incompatibility is one where a program that is legal in
26508 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26509 possible in Ada 83. Fortunately this is extremely rare, but the one
26510 situation that you should be alert to is the change in the predefined type
26511 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26514 @item Range of type @code{Character}
26515 The range of @code{Standard.Character} is now the full 256 characters
26516 of Latin-1, whereas in most Ada 83 implementations it was restricted
26517 to 128 characters. Although some of the effects of
26518 this change will be manifest in compile-time rejection of legal
26519 Ada 83 programs it is possible for a working Ada 83 program to have
26520 a different effect in Ada 95, one that was not permitted in Ada 83.
26521 As an example, the expression
26522 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26523 delivers @code{255} as its value.
26524 In general, you should look at the logic of any
26525 character-processing Ada 83 program and see whether it needs to be adapted
26526 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
26527 character handling package that may be relevant if code needs to be adapted
26528 to account for the additional Latin-1 elements.
26529 The desirable fix is to
26530 modify the program to accommodate the full character set, but in some cases
26531 it may be convenient to define a subtype or derived type of Character that
26532 covers only the restricted range.
26536 @node Other language compatibility issues
26537 @subsection Other language compatibility issues
26540 @item @option{-gnat83} switch
26541 All implementations of GNAT provide a switch that causes GNAT to operate
26542 in Ada 83 mode. In this mode, some but not all compatibility problems
26543 of the type described above are handled automatically. For example, the
26544 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26545 as identifiers as in Ada 83.
26547 in practice, it is usually advisable to make the necessary modifications
26548 to the program to remove the need for using this switch.
26549 See @ref{Compiling Different Versions of Ada}.
26551 @item Support for removed Ada 83 pragmas and attributes
26552 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26553 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
26554 compilers are allowed, but not required, to implement these missing
26555 elements. In contrast with some other compilers, GNAT implements all
26556 such pragmas and attributes, eliminating this compatibility concern. These
26557 include @code{pragma Interface} and the floating point type attributes
26558 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26562 @node Compatibility between Ada 95 and Ada 2005
26563 @section Compatibility between Ada 95 and Ada 2005
26564 @cindex Compatibility between Ada 95 and Ada 2005
26567 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26568 a number of incompatibilities. Several are enumerated below;
26569 for a complete description please see the
26570 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26571 @cite{Rationale for Ada 2005}.
26574 @item New reserved words.
26575 The words @code{interface}, @code{overriding} and @code{synchronized} are
26576 reserved in Ada 2005.
26577 A pre-Ada 2005 program that uses any of these as an identifier will be
26580 @item New declarations in predefined packages.
26581 A number of packages in the predefined environment contain new declarations:
26582 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26583 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26584 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26585 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26586 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26587 If an Ada 95 program does a @code{with} and @code{use} of any of these
26588 packages, the new declarations may cause name clashes.
26590 @item Access parameters.
26591 A nondispatching subprogram with an access parameter cannot be renamed
26592 as a dispatching operation. This was permitted in Ada 95.
26594 @item Access types, discriminants, and constraints.
26595 Rule changes in this area have led to some incompatibilities; for example,
26596 constrained subtypes of some access types are not permitted in Ada 2005.
26598 @item Aggregates for limited types.
26599 The allowance of aggregates for limited types in Ada 2005 raises the
26600 possibility of ambiguities in legal Ada 95 programs, since additional types
26601 now need to be considered in expression resolution.
26603 @item Fixed-point multiplication and division.
26604 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26605 were legal in Ada 95 and invoked the predefined versions of these operations,
26607 The ambiguity may be resolved either by applying a type conversion to the
26608 expression, or by explicitly invoking the operation from package
26611 @item Return-by-reference types.
26612 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
26613 can declare a function returning a value from an anonymous access type.
26617 @node Implementation-dependent characteristics
26618 @section Implementation-dependent characteristics
26620 Although the Ada language defines the semantics of each construct as
26621 precisely as practical, in some situations (for example for reasons of
26622 efficiency, or where the effect is heavily dependent on the host or target
26623 platform) the implementation is allowed some freedom. In porting Ada 83
26624 code to GNAT, you need to be aware of whether / how the existing code
26625 exercised such implementation dependencies. Such characteristics fall into
26626 several categories, and GNAT offers specific support in assisting the
26627 transition from certain Ada 83 compilers.
26630 * Implementation-defined pragmas::
26631 * Implementation-defined attributes::
26633 * Elaboration order::
26634 * Target-specific aspects::
26637 @node Implementation-defined pragmas
26638 @subsection Implementation-defined pragmas
26641 Ada compilers are allowed to supplement the language-defined pragmas, and
26642 these are a potential source of non-portability. All GNAT-defined pragmas
26643 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26644 Reference Manual}, and these include several that are specifically
26645 intended to correspond to other vendors' Ada 83 pragmas.
26646 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26647 For compatibility with HP Ada 83, GNAT supplies the pragmas
26648 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26649 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26650 and @code{Volatile}.
26651 Other relevant pragmas include @code{External} and @code{Link_With}.
26652 Some vendor-specific
26653 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26655 avoiding compiler rejection of units that contain such pragmas; they are not
26656 relevant in a GNAT context and hence are not otherwise implemented.
26658 @node Implementation-defined attributes
26659 @subsection Implementation-defined attributes
26661 Analogous to pragmas, the set of attributes may be extended by an
26662 implementation. All GNAT-defined attributes are described in
26663 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26664 Manual}, and these include several that are specifically intended
26665 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
26666 the attribute @code{VADS_Size} may be useful. For compatibility with HP
26667 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26671 @subsection Libraries
26673 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
26674 code uses vendor-specific libraries then there are several ways to manage
26675 this in Ada 95 or Ada 2005:
26678 If the source code for the libraries (specs and bodies) are
26679 available, then the libraries can be migrated in the same way as the
26682 If the source code for the specs but not the bodies are
26683 available, then you can reimplement the bodies.
26685 Some features introduced by Ada 95 obviate the need for library support. For
26686 example most Ada 83 vendors supplied a package for unsigned integers. The
26687 Ada 95 modular type feature is the preferred way to handle this need, so
26688 instead of migrating or reimplementing the unsigned integer package it may
26689 be preferable to retrofit the application using modular types.
26692 @node Elaboration order
26693 @subsection Elaboration order
26695 The implementation can choose any elaboration order consistent with the unit
26696 dependency relationship. This freedom means that some orders can result in
26697 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26698 to invoke a subprogram its body has been elaborated, or to instantiate a
26699 generic before the generic body has been elaborated. By default GNAT
26700 attempts to choose a safe order (one that will not encounter access before
26701 elaboration problems) by implicitly inserting @code{Elaborate} or
26702 @code{Elaborate_All} pragmas where
26703 needed. However, this can lead to the creation of elaboration circularities
26704 and a resulting rejection of the program by gnatbind. This issue is
26705 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26706 In brief, there are several
26707 ways to deal with this situation:
26711 Modify the program to eliminate the circularities, e.g.@: by moving
26712 elaboration-time code into explicitly-invoked procedures
26714 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26715 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26716 @code{Elaborate_All}
26717 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26718 (by selectively suppressing elaboration checks via pragma
26719 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26722 @node Target-specific aspects
26723 @subsection Target-specific aspects
26725 Low-level applications need to deal with machine addresses, data
26726 representations, interfacing with assembler code, and similar issues. If
26727 such an Ada 83 application is being ported to different target hardware (for
26728 example where the byte endianness has changed) then you will need to
26729 carefully examine the program logic; the porting effort will heavily depend
26730 on the robustness of the original design. Moreover, Ada 95 (and thus
26731 Ada 2005) are sometimes
26732 incompatible with typical Ada 83 compiler practices regarding implicit
26733 packing, the meaning of the Size attribute, and the size of access values.
26734 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26736 @node Compatibility with Other Ada Systems
26737 @section Compatibility with Other Ada Systems
26740 If programs avoid the use of implementation dependent and
26741 implementation defined features, as documented in the @cite{Ada
26742 Reference Manual}, there should be a high degree of portability between
26743 GNAT and other Ada systems. The following are specific items which
26744 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26745 compilers, but do not affect porting code to GNAT@.
26746 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26747 the following issues may or may not arise for Ada 2005 programs
26748 when other compilers appear.)
26751 @item Ada 83 Pragmas and Attributes
26752 Ada 95 compilers are allowed, but not required, to implement the missing
26753 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26754 GNAT implements all such pragmas and attributes, eliminating this as
26755 a compatibility concern, but some other Ada 95 compilers reject these
26756 pragmas and attributes.
26758 @item Specialized Needs Annexes
26759 GNAT implements the full set of special needs annexes. At the
26760 current time, it is the only Ada 95 compiler to do so. This means that
26761 programs making use of these features may not be portable to other Ada
26762 95 compilation systems.
26764 @item Representation Clauses
26765 Some other Ada 95 compilers implement only the minimal set of
26766 representation clauses required by the Ada 95 reference manual. GNAT goes
26767 far beyond this minimal set, as described in the next section.
26770 @node Representation Clauses
26771 @section Representation Clauses
26774 The Ada 83 reference manual was quite vague in describing both the minimal
26775 required implementation of representation clauses, and also their precise
26776 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
26777 minimal set of capabilities required is still quite limited.
26779 GNAT implements the full required set of capabilities in
26780 Ada 95 and Ada 2005, but also goes much further, and in particular
26781 an effort has been made to be compatible with existing Ada 83 usage to the
26782 greatest extent possible.
26784 A few cases exist in which Ada 83 compiler behavior is incompatible with
26785 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
26786 intentional or accidental dependence on specific implementation dependent
26787 characteristics of these Ada 83 compilers. The following is a list of
26788 the cases most likely to arise in existing Ada 83 code.
26791 @item Implicit Packing
26792 Some Ada 83 compilers allowed a Size specification to cause implicit
26793 packing of an array or record. This could cause expensive implicit
26794 conversions for change of representation in the presence of derived
26795 types, and the Ada design intends to avoid this possibility.
26796 Subsequent AI's were issued to make it clear that such implicit
26797 change of representation in response to a Size clause is inadvisable,
26798 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26799 Reference Manuals as implementation advice that is followed by GNAT@.
26800 The problem will show up as an error
26801 message rejecting the size clause. The fix is simply to provide
26802 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26803 a Component_Size clause.
26805 @item Meaning of Size Attribute
26806 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26807 the minimal number of bits required to hold values of the type. For example,
26808 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26809 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
26810 some 32 in this situation. This problem will usually show up as a compile
26811 time error, but not always. It is a good idea to check all uses of the
26812 'Size attribute when porting Ada 83 code. The GNAT specific attribute
26813 Object_Size can provide a useful way of duplicating the behavior of
26814 some Ada 83 compiler systems.
26816 @item Size of Access Types
26817 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26818 and that therefore it will be the same size as a System.Address value. This
26819 assumption is true for GNAT in most cases with one exception. For the case of
26820 a pointer to an unconstrained array type (where the bounds may vary from one
26821 value of the access type to another), the default is to use a ``fat pointer'',
26822 which is represented as two separate pointers, one to the bounds, and one to
26823 the array. This representation has a number of advantages, including improved
26824 efficiency. However, it may cause some difficulties in porting existing Ada 83
26825 code which makes the assumption that, for example, pointers fit in 32 bits on
26826 a machine with 32-bit addressing.
26828 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26829 access types in this case (where the designated type is an unconstrained array
26830 type). These thin pointers are indeed the same size as a System.Address value.
26831 To specify a thin pointer, use a size clause for the type, for example:
26833 @smallexample @c ada
26834 type X is access all String;
26835 for X'Size use Standard'Address_Size;
26839 which will cause the type X to be represented using a single pointer.
26840 When using this representation, the bounds are right behind the array.
26841 This representation is slightly less efficient, and does not allow quite
26842 such flexibility in the use of foreign pointers or in using the
26843 Unrestricted_Access attribute to create pointers to non-aliased objects.
26844 But for any standard portable use of the access type it will work in
26845 a functionally correct manner and allow porting of existing code.
26846 Note that another way of forcing a thin pointer representation
26847 is to use a component size clause for the element size in an array,
26848 or a record representation clause for an access field in a record.
26852 @c This brief section is only in the non-VMS version
26853 @c The complete chapter on HP Ada is in the VMS version
26854 @node Compatibility with HP Ada 83
26855 @section Compatibility with HP Ada 83
26858 The VMS version of GNAT fully implements all the pragmas and attributes
26859 provided by HP Ada 83, as well as providing the standard HP Ada 83
26860 libraries, including Starlet. In addition, data layouts and parameter
26861 passing conventions are highly compatible. This means that porting
26862 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26863 most other porting efforts. The following are some of the most
26864 significant differences between GNAT and HP Ada 83.
26867 @item Default floating-point representation
26868 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26869 it is VMS format. GNAT does implement the necessary pragmas
26870 (Long_Float, Float_Representation) for changing this default.
26873 The package System in GNAT exactly corresponds to the definition in the
26874 Ada 95 reference manual, which means that it excludes many of the
26875 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
26876 that contains the additional definitions, and a special pragma,
26877 Extend_System allows this package to be treated transparently as an
26878 extension of package System.
26881 The definitions provided by Aux_DEC are exactly compatible with those
26882 in the HP Ada 83 version of System, with one exception.
26883 HP Ada provides the following declarations:
26885 @smallexample @c ada
26886 TO_ADDRESS (INTEGER)
26887 TO_ADDRESS (UNSIGNED_LONGWORD)
26888 TO_ADDRESS (@i{universal_integer})
26892 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26893 an extension to Ada 83 not strictly compatible with the reference manual.
26894 In GNAT, we are constrained to be exactly compatible with the standard,
26895 and this means we cannot provide this capability. In HP Ada 83, the
26896 point of this definition is to deal with a call like:
26898 @smallexample @c ada
26899 TO_ADDRESS (16#12777#);
26903 Normally, according to the Ada 83 standard, one would expect this to be
26904 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26905 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
26906 definition using @i{universal_integer} takes precedence.
26908 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26909 is not possible to be 100% compatible. Since there are many programs using
26910 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26911 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26912 declarations provided in the GNAT version of AUX_Dec are:
26914 @smallexample @c ada
26915 function To_Address (X : Integer) return Address;
26916 pragma Pure_Function (To_Address);
26918 function To_Address_Long (X : Unsigned_Longword)
26920 pragma Pure_Function (To_Address_Long);
26924 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26925 change the name to TO_ADDRESS_LONG@.
26927 @item Task_Id values
26928 The Task_Id values assigned will be different in the two systems, and GNAT
26929 does not provide a specified value for the Task_Id of the environment task,
26930 which in GNAT is treated like any other declared task.
26934 For full details on these and other less significant compatibility issues,
26935 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26936 Overview and Comparison on HP Platforms}.
26938 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26939 attributes are recognized, although only a subset of them can sensibly
26940 be implemented. The description of pragmas in @ref{Implementation
26941 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26942 indicates whether or not they are applicable to non-VMS systems.
26946 @node Transitioning to 64-Bit GNAT for OpenVMS
26947 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26950 This section is meant to assist users of pre-2006 @value{EDITION}
26951 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26952 the version of the GNAT technology supplied in 2006 and later for
26953 OpenVMS on both Alpha and I64.
26956 * Introduction to transitioning::
26957 * Migration of 32 bit code::
26958 * Taking advantage of 64 bit addressing::
26959 * Technical details::
26962 @node Introduction to transitioning
26963 @subsection Introduction
26966 64-bit @value{EDITION} for Open VMS has been designed to meet
26971 Providing a full conforming implementation of Ada 95 and Ada 2005
26974 Allowing maximum backward compatibility, thus easing migration of existing
26978 Supplying a path for exploiting the full 64-bit address range
26982 Ada's strong typing semantics has made it
26983 impractical to have different 32-bit and 64-bit modes. As soon as
26984 one object could possibly be outside the 32-bit address space, this
26985 would make it necessary for the @code{System.Address} type to be 64 bits.
26986 In particular, this would cause inconsistencies if 32-bit code is
26987 called from 64-bit code that raises an exception.
26989 This issue has been resolved by always using 64-bit addressing
26990 at the system level, but allowing for automatic conversions between
26991 32-bit and 64-bit addresses where required. Thus users who
26992 do not currently require 64-bit addressing capabilities, can
26993 recompile their code with only minimal changes (and indeed
26994 if the code is written in portable Ada, with no assumptions about
26995 the size of the @code{Address} type, then no changes at all are necessary).
26997 this approach provides a simple, gradual upgrade path to future
26998 use of larger memories than available for 32-bit systems.
26999 Also, newly written applications or libraries will by default
27000 be fully compatible with future systems exploiting 64-bit
27001 addressing capabilities.
27003 @ref{Migration of 32 bit code}, will focus on porting applications
27004 that do not require more than 2 GB of
27005 addressable memory. This code will be referred to as
27006 @emph{32-bit code}.
27007 For applications intending to exploit the full 64-bit address space,
27008 @ref{Taking advantage of 64 bit addressing},
27009 will consider further changes that may be required.
27010 Such code will be referred to below as @emph{64-bit code}.
27012 @node Migration of 32 bit code
27013 @subsection Migration of 32-bit code
27017 * Access types and 32/64-bit allocation::
27018 * Unchecked conversions::
27019 * Predefined constants::
27020 * Interfacing with C::
27021 * 32/64-bit descriptors::
27022 * Experience with source compatibility::
27025 @node Address types
27026 @subsubsection Address types
27029 To solve the problem of mixing 64-bit and 32-bit addressing,
27030 while maintaining maximum backward compatibility, the following
27031 approach has been taken:
27035 @code{System.Address} always has a size of 64 bits
27036 @cindex @code{System.Address} size
27037 @cindex @code{Address} size
27040 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
27041 @cindex @code{System.Short_Address} size
27042 @cindex @code{Short_Address} size
27046 Since @code{System.Short_Address} is a subtype of @code{System.Address},
27047 a @code{Short_Address}
27048 may be used where an @code{Address} is required, and vice versa, without
27049 needing explicit type conversions.
27050 By virtue of the Open VMS parameter passing conventions,
27052 and exported subprograms that have 32-bit address parameters are
27053 compatible with those that have 64-bit address parameters.
27054 (See @ref{Making code 64 bit clean} for details.)
27056 The areas that may need attention are those where record types have
27057 been defined that contain components of the type @code{System.Address}, and
27058 where objects of this type are passed to code expecting a record layout with
27061 Different compilers on different platforms cannot be
27062 expected to represent the same type in the same way,
27063 since alignment constraints
27064 and other system-dependent properties affect the compiler's decision.
27065 For that reason, Ada code
27066 generally uses representation clauses to specify the expected
27067 layout where required.
27069 If such a representation clause uses 32 bits for a component having
27070 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
27071 will detect that error and produce a specific diagnostic message.
27072 The developer should then determine whether the representation
27073 should be 64 bits or not and make either of two changes:
27074 change the size to 64 bits and leave the type as @code{System.Address}, or
27075 leave the size as 32 bits and change the type to @code{System.Short_Address}.
27076 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
27077 required in any code setting or accessing the field; the compiler will
27078 automatically perform any needed conversions between address
27081 @node Access types and 32/64-bit allocation
27082 @subsubsection Access types and 32/64-bit allocation
27083 @cindex 32-bit allocation
27084 @cindex 64-bit allocation
27087 By default, objects designated by access values are always allocated in
27088 the 64-bit address space, and access values themselves are represented
27089 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
27090 is required (for example if the address of an allocated object is assigned
27091 to a @code{Short_Address} variable), then several alternatives are available:
27095 A pool-specific access type (ie, an @w{Ada 83} access type, whose
27096 definition is @code{access T} versus @code{access all T} or
27097 @code{access constant T}), may be declared with a @code{'Size} representation
27098 clause that establishes the size as 32 bits.
27099 In such circumstances allocations for that type will
27100 be from the 32-bit heap. Such a clause is not permitted
27101 for a general access type (declared with @code{access all} or
27102 @code{access constant}) as values of such types must be able to refer
27103 to any object of the designated type, including objects residing outside
27104 the 32-bit address range. Existing @w{Ada 83} code will not contain such
27105 type definitions, however, since general access types were introduced
27109 Switches for @command{GNAT BIND} control whether the internal GNAT
27110 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
27111 @cindex @code{__gnat_malloc}
27112 The switches are respectively @option{-H64} (the default) and
27114 @cindex @option{-H32} (@command{gnatbind})
27115 @cindex @option{-H64} (@command{gnatbind})
27118 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
27119 @cindex @code{GNAT$NO_MALLOC_64} environment variable
27120 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
27121 If this variable is left
27122 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
27123 then the default (64-bit) allocation is used.
27124 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
27125 then 32-bit allocation is used. The gnatbind qualifiers described above
27126 override this logical name.
27129 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
27130 @cindex @option{-mno-malloc64} (^gcc^gcc^)
27131 at a low level to convert explicit calls to @code{malloc} and related
27132 functions from the C run-time library so that they perform allocations
27133 in the 32-bit heap.
27134 Since all internal allocations from GNAT use @code{__gnat_malloc},
27135 this switch is not required unless the program makes explicit calls on
27136 @code{malloc} (or related functions) from interfaced C code.
27140 @node Unchecked conversions
27141 @subsubsection Unchecked conversions
27144 In the case of an @code{Unchecked_Conversion} where the source type is a
27145 64-bit access type or the type @code{System.Address}, and the target
27146 type is a 32-bit type, the compiler will generate a warning.
27147 Even though the generated code will still perform the required
27148 conversions, it is highly recommended in these cases to use
27149 respectively a 32-bit access type or @code{System.Short_Address}
27150 as the source type.
27152 @node Predefined constants
27153 @subsubsection Predefined constants
27156 The following table shows the correspondence between pre-2006 versions of
27157 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
27160 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
27161 @item @b{Constant} @tab @b{Old} @tab @b{New}
27162 @item @code{System.Word_Size} @tab 32 @tab 64
27163 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
27164 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
27165 @item @code{System.Address_Size} @tab 32 @tab 64
27169 If you need to refer to the specific
27170 memory size of a 32-bit implementation, instead of the
27171 actual memory size, use @code{System.Short_Memory_Size}
27172 rather than @code{System.Memory_Size}.
27173 Similarly, references to @code{System.Address_Size} may need
27174 to be replaced by @code{System.Short_Address'Size}.
27175 The program @command{gnatfind} may be useful for locating
27176 references to the above constants, so that you can verify that they
27179 @node Interfacing with C
27180 @subsubsection Interfacing with C
27183 In order to minimize the impact of the transition to 64-bit addresses on
27184 legacy programs, some fundamental types in the @code{Interfaces.C}
27185 package hierarchy continue to be represented in 32 bits.
27186 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
27187 This eases integration with the default HP C layout choices, for example
27188 as found in the system routines in @code{DECC$SHR.EXE}.
27189 Because of this implementation choice, the type fully compatible with
27190 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
27191 Depending on the context the compiler will issue a
27192 warning or an error when type @code{Address} is used, alerting the user to a
27193 potential problem. Otherwise 32-bit programs that use
27194 @code{Interfaces.C} should normally not require code modifications
27196 The other issue arising with C interfacing concerns pragma @code{Convention}.
27197 For VMS 64-bit systems, there is an issue of the appropriate default size
27198 of C convention pointers in the absence of an explicit size clause. The HP
27199 C compiler can choose either 32 or 64 bits depending on compiler options.
27200 GNAT chooses 32-bits rather than 64-bits in the default case where no size
27201 clause is given. This proves a better choice for porting 32-bit legacy
27202 applications. In order to have a 64-bit representation, it is necessary to
27203 specify a size representation clause. For example:
27205 @smallexample @c ada
27206 type int_star is access Interfaces.C.int;
27207 pragma Convention(C, int_star);
27208 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
27211 @node 32/64-bit descriptors
27212 @subsubsection 32/64-bit descriptors
27215 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
27216 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
27217 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
27218 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
27219 @cindex @code{Short_Descriptor} mechanism for imported subprograms
27221 If the configuration pragma @code{Short_Descriptors} is supplied, then
27222 all descriptors will be 32 bits.
27223 @cindex pragma @code{Short_Descriptors}
27225 @node Experience with source compatibility
27226 @subsubsection Experience with source compatibility
27229 The Security Server and STARLET on I64 provide an interesting ``test case''
27230 for source compatibility issues, since it is in such system code
27231 where assumptions about @code{Address} size might be expected to occur.
27232 Indeed, there were a small number of occasions in the Security Server
27233 file @file{jibdef.ads}
27234 where a representation clause for a record type specified
27235 32 bits for a component of type @code{Address}.
27236 All of these errors were detected by the compiler.
27237 The repair was obvious and immediate; to simply replace @code{Address} by
27238 @code{Short_Address}.
27240 In the case of STARLET, there were several record types that should
27241 have had representation clauses but did not. In these record types
27242 there was an implicit assumption that an @code{Address} value occupied
27244 These compiled without error, but their usage resulted in run-time error
27245 returns from STARLET system calls.
27246 Future GNAT technology enhancements may include a tool that detects and flags
27247 these sorts of potential source code porting problems.
27249 @c ****************************************
27250 @node Taking advantage of 64 bit addressing
27251 @subsection Taking advantage of 64-bit addressing
27254 * Making code 64 bit clean::
27255 * Allocating memory from the 64 bit storage pool::
27256 * Restrictions on use of 64 bit objects::
27257 * STARLET and other predefined libraries::
27260 @node Making code 64 bit clean
27261 @subsubsection Making code 64-bit clean
27264 In order to prevent problems that may occur when (parts of) a
27265 system start using memory outside the 32-bit address range,
27266 we recommend some additional guidelines:
27270 For imported subprograms that take parameters of the
27271 type @code{System.Address}, ensure that these subprograms can
27272 indeed handle 64-bit addresses. If not, or when in doubt,
27273 change the subprogram declaration to specify
27274 @code{System.Short_Address} instead.
27277 Resolve all warnings related to size mismatches in
27278 unchecked conversions. Failing to do so causes
27279 erroneous execution if the source object is outside
27280 the 32-bit address space.
27283 (optional) Explicitly use the 32-bit storage pool
27284 for access types used in a 32-bit context, or use
27285 generic access types where possible
27286 (@pxref{Restrictions on use of 64 bit objects}).
27290 If these rules are followed, the compiler will automatically insert
27291 any necessary checks to ensure that no addresses or access values
27292 passed to 32-bit code ever refer to objects outside the 32-bit
27294 Any attempt to do this will raise @code{Constraint_Error}.
27296 @node Allocating memory from the 64 bit storage pool
27297 @subsubsection Allocating memory from the 64-bit storage pool
27300 By default, all allocations -- for both pool-specific and general
27301 access types -- use the 64-bit storage pool. To override
27302 this default, for an individual access type or globally, see
27303 @ref{Access types and 32/64-bit allocation}.
27305 @node Restrictions on use of 64 bit objects
27306 @subsubsection Restrictions on use of 64-bit objects
27309 Taking the address of an object allocated from a 64-bit storage pool,
27310 and then passing this address to a subprogram expecting
27311 @code{System.Short_Address},
27312 or assigning it to a variable of type @code{Short_Address}, will cause
27313 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27314 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27315 no exception is raised and execution
27316 will become erroneous.
27318 @node STARLET and other predefined libraries
27319 @subsubsection STARLET and other predefined libraries
27322 All code that comes as part of GNAT is 64-bit clean, but the
27323 restrictions given in @ref{Restrictions on use of 64 bit objects},
27324 still apply. Look at the package
27325 specs to see in which contexts objects allocated
27326 in 64-bit address space are acceptable.
27328 @node Technical details
27329 @subsection Technical details
27332 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
27333 Ada standard with respect to the type of @code{System.Address}. Previous
27334 versions of @value{EDITION} have defined this type as private and implemented it as a
27337 In order to allow defining @code{System.Short_Address} as a proper subtype,
27338 and to match the implicit sign extension in parameter passing,
27339 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
27340 visible (i.e., non-private) integer type.
27341 Standard operations on the type, such as the binary operators ``+'', ``-'',
27342 etc., that take @code{Address} operands and return an @code{Address} result,
27343 have been hidden by declaring these
27344 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
27345 ambiguities that would otherwise result from overloading.
27346 (Note that, although @code{Address} is a visible integer type,
27347 good programming practice dictates against exploiting the type's
27348 integer properties such as literals, since this will compromise
27351 Defining @code{Address} as a visible integer type helps achieve
27352 maximum compatibility for existing Ada code,
27353 without sacrificing the capabilities of the 64-bit architecture.
27356 @c ************************************************
27358 @node Microsoft Windows Topics
27359 @appendix Microsoft Windows Topics
27365 This chapter describes topics that are specific to the Microsoft Windows
27366 platforms (NT, 2000, and XP Professional).
27369 * Using GNAT on Windows::
27370 * Using a network installation of GNAT::
27371 * CONSOLE and WINDOWS subsystems::
27372 * Temporary Files::
27373 * Mixed-Language Programming on Windows::
27374 * Windows Calling Conventions::
27375 * Introduction to Dynamic Link Libraries (DLLs)::
27376 * Using DLLs with GNAT::
27377 * Building DLLs with GNAT Project files::
27378 * Building DLLs with GNAT::
27379 * Building DLLs with gnatdll::
27380 * GNAT and Windows Resources::
27381 * Debugging a DLL::
27382 * Setting Stack Size from gnatlink::
27383 * Setting Heap Size from gnatlink::
27386 @node Using GNAT on Windows
27387 @section Using GNAT on Windows
27390 One of the strengths of the GNAT technology is that its tool set
27391 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27392 @code{gdb} debugger, etc.) is used in the same way regardless of the
27395 On Windows this tool set is complemented by a number of Microsoft-specific
27396 tools that have been provided to facilitate interoperability with Windows
27397 when this is required. With these tools:
27402 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27406 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27407 relocatable and non-relocatable DLLs are supported).
27410 You can build Ada DLLs for use in other applications. These applications
27411 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27412 relocatable and non-relocatable Ada DLLs are supported.
27415 You can include Windows resources in your Ada application.
27418 You can use or create COM/DCOM objects.
27422 Immediately below are listed all known general GNAT-for-Windows restrictions.
27423 Other restrictions about specific features like Windows Resources and DLLs
27424 are listed in separate sections below.
27429 It is not possible to use @code{GetLastError} and @code{SetLastError}
27430 when tasking, protected records, or exceptions are used. In these
27431 cases, in order to implement Ada semantics, the GNAT run-time system
27432 calls certain Win32 routines that set the last error variable to 0 upon
27433 success. It should be possible to use @code{GetLastError} and
27434 @code{SetLastError} when tasking, protected record, and exception
27435 features are not used, but it is not guaranteed to work.
27438 It is not possible to link against Microsoft libraries except for
27439 import libraries. Interfacing must be done by the mean of DLLs.
27442 When the compilation environment is located on FAT32 drives, users may
27443 experience recompilations of the source files that have not changed if
27444 Daylight Saving Time (DST) state has changed since the last time files
27445 were compiled. NTFS drives do not have this problem.
27448 No components of the GNAT toolset use any entries in the Windows
27449 registry. The only entries that can be created are file associations and
27450 PATH settings, provided the user has chosen to create them at installation
27451 time, as well as some minimal book-keeping information needed to correctly
27452 uninstall or integrate different GNAT products.
27455 @node Using a network installation of GNAT
27456 @section Using a network installation of GNAT
27459 Make sure the system on which GNAT is installed is accessible from the
27460 current machine, i.e., the install location is shared over the network.
27461 Shared resources are accessed on Windows by means of UNC paths, which
27462 have the format @code{\\server\sharename\path}
27464 In order to use such a network installation, simply add the UNC path of the
27465 @file{bin} directory of your GNAT installation in front of your PATH. For
27466 example, if GNAT is installed in @file{\GNAT} directory of a share location
27467 called @file{c-drive} on a machine @file{LOKI}, the following command will
27470 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27472 Be aware that every compilation using the network installation results in the
27473 transfer of large amounts of data across the network and will likely cause
27474 serious performance penalty.
27476 @node CONSOLE and WINDOWS subsystems
27477 @section CONSOLE and WINDOWS subsystems
27478 @cindex CONSOLE Subsystem
27479 @cindex WINDOWS Subsystem
27483 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27484 (which is the default subsystem) will always create a console when
27485 launching the application. This is not something desirable when the
27486 application has a Windows GUI. To get rid of this console the
27487 application must be using the @code{WINDOWS} subsystem. To do so
27488 the @option{-mwindows} linker option must be specified.
27491 $ gnatmake winprog -largs -mwindows
27494 @node Temporary Files
27495 @section Temporary Files
27496 @cindex Temporary files
27499 It is possible to control where temporary files gets created by setting
27500 the @env{TMP} environment variable. The file will be created:
27503 @item Under the directory pointed to by the @env{TMP} environment variable if
27504 this directory exists.
27506 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27507 set (or not pointing to a directory) and if this directory exists.
27509 @item Under the current working directory otherwise.
27513 This allows you to determine exactly where the temporary
27514 file will be created. This is particularly useful in networked
27515 environments where you may not have write access to some
27518 @node Mixed-Language Programming on Windows
27519 @section Mixed-Language Programming on Windows
27522 Developing pure Ada applications on Windows is no different than on
27523 other GNAT-supported platforms. However, when developing or porting an
27524 application that contains a mix of Ada and C/C++, the choice of your
27525 Windows C/C++ development environment conditions your overall
27526 interoperability strategy.
27528 If you use @command{gcc} to compile the non-Ada part of your application,
27529 there are no Windows-specific restrictions that affect the overall
27530 interoperability with your Ada code. If you do want to use the
27531 Microsoft tools for your non-Ada code, you have two choices:
27535 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27536 application. In this case, use the Microsoft or whatever environment to
27537 build the DLL and use GNAT to build your executable
27538 (@pxref{Using DLLs with GNAT}).
27541 Or you can encapsulate your Ada code in a DLL to be linked with the
27542 other part of your application. In this case, use GNAT to build the DLL
27543 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27544 or whatever environment to build your executable.
27547 @node Windows Calling Conventions
27548 @section Windows Calling Conventions
27552 This section pertain only to Win32. On Win64 there is a single native
27553 calling convention. All convention specifiers are ignored on this
27557 * C Calling Convention::
27558 * Stdcall Calling Convention::
27559 * Win32 Calling Convention::
27560 * DLL Calling Convention::
27564 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27565 (callee), there are several ways to push @code{G}'s parameters on the
27566 stack and there are several possible scenarios to clean up the stack
27567 upon @code{G}'s return. A calling convention is an agreed upon software
27568 protocol whereby the responsibilities between the caller (@code{F}) and
27569 the callee (@code{G}) are clearly defined. Several calling conventions
27570 are available for Windows:
27574 @code{C} (Microsoft defined)
27577 @code{Stdcall} (Microsoft defined)
27580 @code{Win32} (GNAT specific)
27583 @code{DLL} (GNAT specific)
27586 @node C Calling Convention
27587 @subsection @code{C} Calling Convention
27590 This is the default calling convention used when interfacing to C/C++
27591 routines compiled with either @command{gcc} or Microsoft Visual C++.
27593 In the @code{C} calling convention subprogram parameters are pushed on the
27594 stack by the caller from right to left. The caller itself is in charge of
27595 cleaning up the stack after the call. In addition, the name of a routine
27596 with @code{C} calling convention is mangled by adding a leading underscore.
27598 The name to use on the Ada side when importing (or exporting) a routine
27599 with @code{C} calling convention is the name of the routine. For
27600 instance the C function:
27603 int get_val (long);
27607 should be imported from Ada as follows:
27609 @smallexample @c ada
27611 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27612 pragma Import (C, Get_Val, External_Name => "get_val");
27617 Note that in this particular case the @code{External_Name} parameter could
27618 have been omitted since, when missing, this parameter is taken to be the
27619 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27620 is missing, as in the above example, this parameter is set to be the
27621 @code{External_Name} with a leading underscore.
27623 When importing a variable defined in C, you should always use the @code{C}
27624 calling convention unless the object containing the variable is part of a
27625 DLL (in which case you should use the @code{Stdcall} calling
27626 convention, @pxref{Stdcall Calling Convention}).
27628 @node Stdcall Calling Convention
27629 @subsection @code{Stdcall} Calling Convention
27632 This convention, which was the calling convention used for Pascal
27633 programs, is used by Microsoft for all the routines in the Win32 API for
27634 efficiency reasons. It must be used to import any routine for which this
27635 convention was specified.
27637 In the @code{Stdcall} calling convention subprogram parameters are pushed
27638 on the stack by the caller from right to left. The callee (and not the
27639 caller) is in charge of cleaning the stack on routine exit. In addition,
27640 the name of a routine with @code{Stdcall} calling convention is mangled by
27641 adding a leading underscore (as for the @code{C} calling convention) and a
27642 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27643 bytes) of the parameters passed to the routine.
27645 The name to use on the Ada side when importing a C routine with a
27646 @code{Stdcall} calling convention is the name of the C routine. The leading
27647 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27648 the compiler. For instance the Win32 function:
27651 @b{APIENTRY} int get_val (long);
27655 should be imported from Ada as follows:
27657 @smallexample @c ada
27659 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27660 pragma Import (Stdcall, Get_Val);
27661 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27666 As for the @code{C} calling convention, when the @code{External_Name}
27667 parameter is missing, it is taken to be the name of the Ada entity in lower
27668 case. If instead of writing the above import pragma you write:
27670 @smallexample @c ada
27672 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27673 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27678 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27679 of specifying the @code{External_Name} parameter you specify the
27680 @code{Link_Name} as in the following example:
27682 @smallexample @c ada
27684 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27685 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27690 then the imported routine is @code{retrieve_val}, that is, there is no
27691 decoration at all. No leading underscore and no Stdcall suffix
27692 @code{@@}@code{@var{nn}}.
27695 This is especially important as in some special cases a DLL's entry
27696 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27697 name generated for a call has it.
27700 It is also possible to import variables defined in a DLL by using an
27701 import pragma for a variable. As an example, if a DLL contains a
27702 variable defined as:
27709 then, to access this variable from Ada you should write:
27711 @smallexample @c ada
27713 My_Var : Interfaces.C.int;
27714 pragma Import (Stdcall, My_Var);
27719 Note that to ease building cross-platform bindings this convention
27720 will be handled as a @code{C} calling convention on non-Windows platforms.
27722 @node Win32 Calling Convention
27723 @subsection @code{Win32} Calling Convention
27726 This convention, which is GNAT-specific is fully equivalent to the
27727 @code{Stdcall} calling convention described above.
27729 @node DLL Calling Convention
27730 @subsection @code{DLL} Calling Convention
27733 This convention, which is GNAT-specific is fully equivalent to the
27734 @code{Stdcall} calling convention described above.
27736 @node Introduction to Dynamic Link Libraries (DLLs)
27737 @section Introduction to Dynamic Link Libraries (DLLs)
27741 A Dynamically Linked Library (DLL) is a library that can be shared by
27742 several applications running under Windows. A DLL can contain any number of
27743 routines and variables.
27745 One advantage of DLLs is that you can change and enhance them without
27746 forcing all the applications that depend on them to be relinked or
27747 recompiled. However, you should be aware than all calls to DLL routines are
27748 slower since, as you will understand below, such calls are indirect.
27750 To illustrate the remainder of this section, suppose that an application
27751 wants to use the services of a DLL @file{API.dll}. To use the services
27752 provided by @file{API.dll} you must statically link against the DLL or
27753 an import library which contains a jump table with an entry for each
27754 routine and variable exported by the DLL. In the Microsoft world this
27755 import library is called @file{API.lib}. When using GNAT this import
27756 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27757 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27759 After you have linked your application with the DLL or the import library
27760 and you run your application, here is what happens:
27764 Your application is loaded into memory.
27767 The DLL @file{API.dll} is mapped into the address space of your
27768 application. This means that:
27772 The DLL will use the stack of the calling thread.
27775 The DLL will use the virtual address space of the calling process.
27778 The DLL will allocate memory from the virtual address space of the calling
27782 Handles (pointers) can be safely exchanged between routines in the DLL
27783 routines and routines in the application using the DLL.
27787 The entries in the jump table (from the import library @file{libAPI.dll.a}
27788 or @file{API.lib} or automatically created when linking against a DLL)
27789 which is part of your application are initialized with the addresses
27790 of the routines and variables in @file{API.dll}.
27793 If present in @file{API.dll}, routines @code{DllMain} or
27794 @code{DllMainCRTStartup} are invoked. These routines typically contain
27795 the initialization code needed for the well-being of the routines and
27796 variables exported by the DLL.
27800 There is an additional point which is worth mentioning. In the Windows
27801 world there are two kind of DLLs: relocatable and non-relocatable
27802 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27803 in the target application address space. If the addresses of two
27804 non-relocatable DLLs overlap and these happen to be used by the same
27805 application, a conflict will occur and the application will run
27806 incorrectly. Hence, when possible, it is always preferable to use and
27807 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27808 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27809 User's Guide) removes the debugging symbols from the DLL but the DLL can
27810 still be relocated.
27812 As a side note, an interesting difference between Microsoft DLLs and
27813 Unix shared libraries, is the fact that on most Unix systems all public
27814 routines are exported by default in a Unix shared library, while under
27815 Windows it is possible (but not required) to list exported routines in
27816 a definition file (@pxref{The Definition File}).
27818 @node Using DLLs with GNAT
27819 @section Using DLLs with GNAT
27822 * Creating an Ada Spec for the DLL Services::
27823 * Creating an Import Library::
27827 To use the services of a DLL, say @file{API.dll}, in your Ada application
27832 The Ada spec for the routines and/or variables you want to access in
27833 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27834 header files provided with the DLL.
27837 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27838 mentioned an import library is a statically linked library containing the
27839 import table which will be filled at load time to point to the actual
27840 @file{API.dll} routines. Sometimes you don't have an import library for the
27841 DLL you want to use. The following sections will explain how to build
27842 one. Note that this is optional.
27845 The actual DLL, @file{API.dll}.
27849 Once you have all the above, to compile an Ada application that uses the
27850 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27851 you simply issue the command
27854 $ gnatmake my_ada_app -largs -lAPI
27858 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27859 tells the GNAT linker to look for an import library. The linker will
27860 look for a library name in this specific order:
27863 @item @file{libAPI.dll.a}
27864 @item @file{API.dll.a}
27865 @item @file{libAPI.a}
27866 @item @file{API.lib}
27867 @item @file{libAPI.dll}
27868 @item @file{API.dll}
27871 The first three are the GNU style import libraries. The third is the
27872 Microsoft style import libraries. The last two are the actual DLL names.
27874 Note that if the Ada package spec for @file{API.dll} contains the
27877 @smallexample @c ada
27878 pragma Linker_Options ("-lAPI");
27882 you do not have to add @option{-largs -lAPI} at the end of the
27883 @command{gnatmake} command.
27885 If any one of the items above is missing you will have to create it
27886 yourself. The following sections explain how to do so using as an
27887 example a fictitious DLL called @file{API.dll}.
27889 @node Creating an Ada Spec for the DLL Services
27890 @subsection Creating an Ada Spec for the DLL Services
27893 A DLL typically comes with a C/C++ header file which provides the
27894 definitions of the routines and variables exported by the DLL. The Ada
27895 equivalent of this header file is a package spec that contains definitions
27896 for the imported entities. If the DLL you intend to use does not come with
27897 an Ada spec you have to generate one such spec yourself. For example if
27898 the header file of @file{API.dll} is a file @file{api.h} containing the
27899 following two definitions:
27911 then the equivalent Ada spec could be:
27913 @smallexample @c ada
27916 with Interfaces.C.Strings;
27921 function Get (Str : C.Strings.Chars_Ptr) return C.int;
27924 pragma Import (C, Get);
27925 pragma Import (DLL, Some_Var);
27932 Note that a variable is
27933 @strong{always imported with a DLL convention}. A function
27934 can have @code{C} or @code{Stdcall} convention.
27935 (@pxref{Windows Calling Conventions}).
27937 @node Creating an Import Library
27938 @subsection Creating an Import Library
27939 @cindex Import library
27942 * The Definition File::
27943 * GNAT-Style Import Library::
27944 * Microsoft-Style Import Library::
27948 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27949 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27950 with @file{API.dll} you can skip this section. You can also skip this
27951 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27952 as in this case it is possible to link directly against the
27953 DLL. Otherwise read on.
27955 @node The Definition File
27956 @subsubsection The Definition File
27957 @cindex Definition file
27961 As previously mentioned, and unlike Unix systems, the list of symbols
27962 that are exported from a DLL must be provided explicitly in Windows.
27963 The main goal of a definition file is precisely that: list the symbols
27964 exported by a DLL. A definition file (usually a file with a @code{.def}
27965 suffix) has the following structure:
27970 @r{[}LIBRARY @var{name}@r{]}
27971 @r{[}DESCRIPTION @var{string}@r{]}
27981 @item LIBRARY @var{name}
27982 This section, which is optional, gives the name of the DLL.
27984 @item DESCRIPTION @var{string}
27985 This section, which is optional, gives a description string that will be
27986 embedded in the import library.
27989 This section gives the list of exported symbols (procedures, functions or
27990 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27991 section of @file{API.def} looks like:
28005 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28006 (@pxref{Windows Calling Conventions}) for a Stdcall
28007 calling convention function in the exported symbols list.
28010 There can actually be other sections in a definition file, but these
28011 sections are not relevant to the discussion at hand.
28013 @node GNAT-Style Import Library
28014 @subsubsection GNAT-Style Import Library
28017 To create a static import library from @file{API.dll} with the GNAT tools
28018 you should proceed as follows:
28022 Create the definition file @file{API.def} (@pxref{The Definition File}).
28023 For that use the @code{dll2def} tool as follows:
28026 $ dll2def API.dll > API.def
28030 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28031 to standard output the list of entry points in the DLL. Note that if
28032 some routines in the DLL have the @code{Stdcall} convention
28033 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28034 suffix then you'll have to edit @file{api.def} to add it, and specify
28035 @option{-k} to @command{gnatdll} when creating the import library.
28038 Here are some hints to find the right @code{@@}@var{nn} suffix.
28042 If you have the Microsoft import library (.lib), it is possible to get
28043 the right symbols by using Microsoft @code{dumpbin} tool (see the
28044 corresponding Microsoft documentation for further details).
28047 $ dumpbin /exports api.lib
28051 If you have a message about a missing symbol at link time the compiler
28052 tells you what symbol is expected. You just have to go back to the
28053 definition file and add the right suffix.
28057 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28058 (@pxref{Using gnatdll}) as follows:
28061 $ gnatdll -e API.def -d API.dll
28065 @code{gnatdll} takes as input a definition file @file{API.def} and the
28066 name of the DLL containing the services listed in the definition file
28067 @file{API.dll}. The name of the static import library generated is
28068 computed from the name of the definition file as follows: if the
28069 definition file name is @var{xyz}@code{.def}, the import library name will
28070 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
28071 @option{-e} could have been removed because the name of the definition
28072 file (before the ``@code{.def}'' suffix) is the same as the name of the
28073 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
28076 @node Microsoft-Style Import Library
28077 @subsubsection Microsoft-Style Import Library
28080 With GNAT you can either use a GNAT-style or Microsoft-style import
28081 library. A Microsoft import library is needed only if you plan to make an
28082 Ada DLL available to applications developed with Microsoft
28083 tools (@pxref{Mixed-Language Programming on Windows}).
28085 To create a Microsoft-style import library for @file{API.dll} you
28086 should proceed as follows:
28090 Create the definition file @file{API.def} from the DLL. For this use either
28091 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28092 tool (see the corresponding Microsoft documentation for further details).
28095 Build the actual import library using Microsoft's @code{lib} utility:
28098 $ lib -machine:IX86 -def:API.def -out:API.lib
28102 If you use the above command the definition file @file{API.def} must
28103 contain a line giving the name of the DLL:
28110 See the Microsoft documentation for further details about the usage of
28114 @node Building DLLs with GNAT Project files
28115 @section Building DLLs with GNAT Project files
28116 @cindex DLLs, building
28119 There is nothing specific to Windows in the build process.
28120 @pxref{Library Projects}.
28123 Due to a system limitation, it is not possible under Windows to create threads
28124 when inside the @code{DllMain} routine which is used for auto-initialization
28125 of shared libraries, so it is not possible to have library level tasks in SALs.
28127 @node Building DLLs with GNAT
28128 @section Building DLLs with GNAT
28129 @cindex DLLs, building
28132 This section explain how to build DLLs using the GNAT built-in DLL
28133 support. With the following procedure it is straight forward to build
28134 and use DLLs with GNAT.
28138 @item building object files
28140 The first step is to build all objects files that are to be included
28141 into the DLL. This is done by using the standard @command{gnatmake} tool.
28143 @item building the DLL
28145 To build the DLL you must use @command{gcc}'s @option{-shared} and
28146 @option{-shared-libgcc} options. It is quite simple to use this method:
28149 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28152 It is important to note that in this case all symbols found in the
28153 object files are automatically exported. It is possible to restrict
28154 the set of symbols to export by passing to @command{gcc} a definition
28155 file, @pxref{The Definition File}. For example:
28158 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28161 If you use a definition file you must export the elaboration procedures
28162 for every package that required one. Elaboration procedures are named
28163 using the package name followed by "_E".
28165 @item preparing DLL to be used
28167 For the DLL to be used by client programs the bodies must be hidden
28168 from it and the .ali set with read-only attribute. This is very important
28169 otherwise GNAT will recompile all packages and will not actually use
28170 the code in the DLL. For example:
28174 $ copy *.ads *.ali api.dll apilib
28175 $ attrib +R apilib\*.ali
28180 At this point it is possible to use the DLL by directly linking
28181 against it. Note that you must use the GNAT shared runtime when using
28182 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28186 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28189 @node Building DLLs with gnatdll
28190 @section Building DLLs with gnatdll
28191 @cindex DLLs, building
28194 * Limitations When Using Ada DLLs from Ada::
28195 * Exporting Ada Entities::
28196 * Ada DLLs and Elaboration::
28197 * Ada DLLs and Finalization::
28198 * Creating a Spec for Ada DLLs::
28199 * Creating the Definition File::
28204 Note that it is preferred to use GNAT Project files
28205 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28206 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28208 This section explains how to build DLLs containing Ada code using
28209 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28210 remainder of this section.
28212 The steps required to build an Ada DLL that is to be used by Ada as well as
28213 non-Ada applications are as follows:
28217 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28218 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28219 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28220 skip this step if you plan to use the Ada DLL only from Ada applications.
28223 Your Ada code must export an initialization routine which calls the routine
28224 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28225 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28226 routine exported by the Ada DLL must be invoked by the clients of the DLL
28227 to initialize the DLL.
28230 When useful, the DLL should also export a finalization routine which calls
28231 routine @code{adafinal} generated by @command{gnatbind} to perform the
28232 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28233 The finalization routine exported by the Ada DLL must be invoked by the
28234 clients of the DLL when the DLL services are no further needed.
28237 You must provide a spec for the services exported by the Ada DLL in each
28238 of the programming languages to which you plan to make the DLL available.
28241 You must provide a definition file listing the exported entities
28242 (@pxref{The Definition File}).
28245 Finally you must use @code{gnatdll} to produce the DLL and the import
28246 library (@pxref{Using gnatdll}).
28250 Note that a relocatable DLL stripped using the @code{strip}
28251 binutils tool will not be relocatable anymore. To build a DLL without
28252 debug information pass @code{-largs -s} to @code{gnatdll}. This
28253 restriction does not apply to a DLL built using a Library Project.
28254 @pxref{Library Projects}.
28256 @node Limitations When Using Ada DLLs from Ada
28257 @subsection Limitations When Using Ada DLLs from Ada
28260 When using Ada DLLs from Ada applications there is a limitation users
28261 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28262 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28263 each Ada DLL includes the services of the GNAT run time that are necessary
28264 to the Ada code inside the DLL. As a result, when an Ada program uses an
28265 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28266 one in the main program.
28268 It is therefore not possible to exchange GNAT run-time objects between the
28269 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28270 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28273 It is completely safe to exchange plain elementary, array or record types,
28274 Windows object handles, etc.
28276 @node Exporting Ada Entities
28277 @subsection Exporting Ada Entities
28278 @cindex Export table
28281 Building a DLL is a way to encapsulate a set of services usable from any
28282 application. As a result, the Ada entities exported by a DLL should be
28283 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28284 any Ada name mangling. As an example here is an Ada package
28285 @code{API}, spec and body, exporting two procedures, a function, and a
28288 @smallexample @c ada
28291 with Interfaces.C; use Interfaces;
28293 Count : C.int := 0;
28294 function Factorial (Val : C.int) return C.int;
28296 procedure Initialize_API;
28297 procedure Finalize_API;
28298 -- Initialization & Finalization routines. More in the next section.
28300 pragma Export (C, Initialize_API);
28301 pragma Export (C, Finalize_API);
28302 pragma Export (C, Count);
28303 pragma Export (C, Factorial);
28309 @smallexample @c ada
28312 package body API is
28313 function Factorial (Val : C.int) return C.int is
28316 Count := Count + 1;
28317 for K in 1 .. Val loop
28323 procedure Initialize_API is
28325 pragma Import (C, Adainit);
28328 end Initialize_API;
28330 procedure Finalize_API is
28331 procedure Adafinal;
28332 pragma Import (C, Adafinal);
28342 If the Ada DLL you are building will only be used by Ada applications
28343 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28344 convention. As an example, the previous package could be written as
28347 @smallexample @c ada
28351 Count : Integer := 0;
28352 function Factorial (Val : Integer) return Integer;
28354 procedure Initialize_API;
28355 procedure Finalize_API;
28356 -- Initialization and Finalization routines.
28362 @smallexample @c ada
28365 package body API is
28366 function Factorial (Val : Integer) return Integer is
28367 Fact : Integer := 1;
28369 Count := Count + 1;
28370 for K in 1 .. Val loop
28377 -- The remainder of this package body is unchanged.
28384 Note that if you do not export the Ada entities with a @code{C} or
28385 @code{Stdcall} convention you will have to provide the mangled Ada names
28386 in the definition file of the Ada DLL
28387 (@pxref{Creating the Definition File}).
28389 @node Ada DLLs and Elaboration
28390 @subsection Ada DLLs and Elaboration
28391 @cindex DLLs and elaboration
28394 The DLL that you are building contains your Ada code as well as all the
28395 routines in the Ada library that are needed by it. The first thing a
28396 user of your DLL must do is elaborate the Ada code
28397 (@pxref{Elaboration Order Handling in GNAT}).
28399 To achieve this you must export an initialization routine
28400 (@code{Initialize_API} in the previous example), which must be invoked
28401 before using any of the DLL services. This elaboration routine must call
28402 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28403 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28404 @code{Initialize_Api} for an example. Note that the GNAT binder is
28405 automatically invoked during the DLL build process by the @code{gnatdll}
28406 tool (@pxref{Using gnatdll}).
28408 When a DLL is loaded, Windows systematically invokes a routine called
28409 @code{DllMain}. It would therefore be possible to call @code{adainit}
28410 directly from @code{DllMain} without having to provide an explicit
28411 initialization routine. Unfortunately, it is not possible to call
28412 @code{adainit} from the @code{DllMain} if your program has library level
28413 tasks because access to the @code{DllMain} entry point is serialized by
28414 the system (that is, only a single thread can execute ``through'' it at a
28415 time), which means that the GNAT run time will deadlock waiting for the
28416 newly created task to complete its initialization.
28418 @node Ada DLLs and Finalization
28419 @subsection Ada DLLs and Finalization
28420 @cindex DLLs and finalization
28423 When the services of an Ada DLL are no longer needed, the client code should
28424 invoke the DLL finalization routine, if available. The DLL finalization
28425 routine is in charge of releasing all resources acquired by the DLL. In the
28426 case of the Ada code contained in the DLL, this is achieved by calling
28427 routine @code{adafinal} generated by the GNAT binder
28428 (@pxref{Binding with Non-Ada Main Programs}).
28429 See the body of @code{Finalize_Api} for an
28430 example. As already pointed out the GNAT binder is automatically invoked
28431 during the DLL build process by the @code{gnatdll} tool
28432 (@pxref{Using gnatdll}).
28434 @node Creating a Spec for Ada DLLs
28435 @subsection Creating a Spec for Ada DLLs
28438 To use the services exported by the Ada DLL from another programming
28439 language (e.g.@: C), you have to translate the specs of the exported Ada
28440 entities in that language. For instance in the case of @code{API.dll},
28441 the corresponding C header file could look like:
28446 extern int *_imp__count;
28447 #define count (*_imp__count)
28448 int factorial (int);
28454 It is important to understand that when building an Ada DLL to be used by
28455 other Ada applications, you need two different specs for the packages
28456 contained in the DLL: one for building the DLL and the other for using
28457 the DLL. This is because the @code{DLL} calling convention is needed to
28458 use a variable defined in a DLL, but when building the DLL, the variable
28459 must have either the @code{Ada} or @code{C} calling convention. As an
28460 example consider a DLL comprising the following package @code{API}:
28462 @smallexample @c ada
28466 Count : Integer := 0;
28468 -- Remainder of the package omitted.
28475 After producing a DLL containing package @code{API}, the spec that
28476 must be used to import @code{API.Count} from Ada code outside of the
28479 @smallexample @c ada
28484 pragma Import (DLL, Count);
28490 @node Creating the Definition File
28491 @subsection Creating the Definition File
28494 The definition file is the last file needed to build the DLL. It lists
28495 the exported symbols. As an example, the definition file for a DLL
28496 containing only package @code{API} (where all the entities are exported
28497 with a @code{C} calling convention) is:
28512 If the @code{C} calling convention is missing from package @code{API},
28513 then the definition file contains the mangled Ada names of the above
28514 entities, which in this case are:
28523 api__initialize_api
28528 @node Using gnatdll
28529 @subsection Using @code{gnatdll}
28533 * gnatdll Example::
28534 * gnatdll behind the Scenes::
28539 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28540 and non-Ada sources that make up your DLL have been compiled.
28541 @code{gnatdll} is actually in charge of two distinct tasks: build the
28542 static import library for the DLL and the actual DLL. The form of the
28543 @code{gnatdll} command is
28547 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28548 @c Expanding @ovar macro inline (explanation in macro def comments)
28549 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28554 where @var{list-of-files} is a list of ALI and object files. The object
28555 file list must be the exact list of objects corresponding to the non-Ada
28556 sources whose services are to be included in the DLL. The ALI file list
28557 must be the exact list of ALI files for the corresponding Ada sources
28558 whose services are to be included in the DLL. If @var{list-of-files} is
28559 missing, only the static import library is generated.
28562 You may specify any of the following switches to @code{gnatdll}:
28565 @c @item -a@ovar{address}
28566 @c Expanding @ovar macro inline (explanation in macro def comments)
28567 @item -a@r{[}@var{address}@r{]}
28568 @cindex @option{-a} (@code{gnatdll})
28569 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28570 specified the default address @var{0x11000000} will be used. By default,
28571 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28572 advise the reader to build relocatable DLL.
28574 @item -b @var{address}
28575 @cindex @option{-b} (@code{gnatdll})
28576 Set the relocatable DLL base address. By default the address is
28579 @item -bargs @var{opts}
28580 @cindex @option{-bargs} (@code{gnatdll})
28581 Binder options. Pass @var{opts} to the binder.
28583 @item -d @var{dllfile}
28584 @cindex @option{-d} (@code{gnatdll})
28585 @var{dllfile} is the name of the DLL. This switch must be present for
28586 @code{gnatdll} to do anything. The name of the generated import library is
28587 obtained algorithmically from @var{dllfile} as shown in the following
28588 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28589 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28590 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28591 as shown in the following example:
28592 if @var{dllfile} is @code{xyz.dll}, the definition
28593 file used is @code{xyz.def}.
28595 @item -e @var{deffile}
28596 @cindex @option{-e} (@code{gnatdll})
28597 @var{deffile} is the name of the definition file.
28600 @cindex @option{-g} (@code{gnatdll})
28601 Generate debugging information. This information is stored in the object
28602 file and copied from there to the final DLL file by the linker,
28603 where it can be read by the debugger. You must use the
28604 @option{-g} switch if you plan on using the debugger or the symbolic
28608 @cindex @option{-h} (@code{gnatdll})
28609 Help mode. Displays @code{gnatdll} switch usage information.
28612 @cindex @option{-I} (@code{gnatdll})
28613 Direct @code{gnatdll} to search the @var{dir} directory for source and
28614 object files needed to build the DLL.
28615 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28618 @cindex @option{-k} (@code{gnatdll})
28619 Removes the @code{@@}@var{nn} suffix from the import library's exported
28620 names, but keeps them for the link names. You must specify this
28621 option if you want to use a @code{Stdcall} function in a DLL for which
28622 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28623 of the Windows NT DLL for example. This option has no effect when
28624 @option{-n} option is specified.
28626 @item -l @var{file}
28627 @cindex @option{-l} (@code{gnatdll})
28628 The list of ALI and object files used to build the DLL are listed in
28629 @var{file}, instead of being given in the command line. Each line in
28630 @var{file} contains the name of an ALI or object file.
28633 @cindex @option{-n} (@code{gnatdll})
28634 No Import. Do not create the import library.
28637 @cindex @option{-q} (@code{gnatdll})
28638 Quiet mode. Do not display unnecessary messages.
28641 @cindex @option{-v} (@code{gnatdll})
28642 Verbose mode. Display extra information.
28644 @item -largs @var{opts}
28645 @cindex @option{-largs} (@code{gnatdll})
28646 Linker options. Pass @var{opts} to the linker.
28649 @node gnatdll Example
28650 @subsubsection @code{gnatdll} Example
28653 As an example the command to build a relocatable DLL from @file{api.adb}
28654 once @file{api.adb} has been compiled and @file{api.def} created is
28657 $ gnatdll -d api.dll api.ali
28661 The above command creates two files: @file{libapi.dll.a} (the import
28662 library) and @file{api.dll} (the actual DLL). If you want to create
28663 only the DLL, just type:
28666 $ gnatdll -d api.dll -n api.ali
28670 Alternatively if you want to create just the import library, type:
28673 $ gnatdll -d api.dll
28676 @node gnatdll behind the Scenes
28677 @subsubsection @code{gnatdll} behind the Scenes
28680 This section details the steps involved in creating a DLL. @code{gnatdll}
28681 does these steps for you. Unless you are interested in understanding what
28682 goes on behind the scenes, you should skip this section.
28684 We use the previous example of a DLL containing the Ada package @code{API},
28685 to illustrate the steps necessary to build a DLL. The starting point is a
28686 set of objects that will make up the DLL and the corresponding ALI
28687 files. In the case of this example this means that @file{api.o} and
28688 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28693 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28694 the information necessary to generate relocation information for the
28700 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28705 In addition to the base file, the @command{gnatlink} command generates an
28706 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28707 asks @command{gnatlink} to generate the routines @code{DllMain} and
28708 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28709 is loaded into memory.
28712 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28713 export table (@file{api.exp}). The export table contains the relocation
28714 information in a form which can be used during the final link to ensure
28715 that the Windows loader is able to place the DLL anywhere in memory.
28719 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28720 --output-exp api.exp
28725 @code{gnatdll} builds the base file using the new export table. Note that
28726 @command{gnatbind} must be called once again since the binder generated file
28727 has been deleted during the previous call to @command{gnatlink}.
28732 $ gnatlink api -o api.jnk api.exp -mdll
28733 -Wl,--base-file,api.base
28738 @code{gnatdll} builds the new export table using the new base file and
28739 generates the DLL import library @file{libAPI.dll.a}.
28743 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28744 --output-exp api.exp --output-lib libAPI.a
28749 Finally @code{gnatdll} builds the relocatable DLL using the final export
28755 $ gnatlink api api.exp -o api.dll -mdll
28760 @node Using dlltool
28761 @subsubsection Using @code{dlltool}
28764 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28765 DLLs and static import libraries. This section summarizes the most
28766 common @code{dlltool} switches. The form of the @code{dlltool} command
28770 @c $ dlltool @ovar{switches}
28771 @c Expanding @ovar macro inline (explanation in macro def comments)
28772 $ dlltool @r{[}@var{switches}@r{]}
28776 @code{dlltool} switches include:
28779 @item --base-file @var{basefile}
28780 @cindex @option{--base-file} (@command{dlltool})
28781 Read the base file @var{basefile} generated by the linker. This switch
28782 is used to create a relocatable DLL.
28784 @item --def @var{deffile}
28785 @cindex @option{--def} (@command{dlltool})
28786 Read the definition file.
28788 @item --dllname @var{name}
28789 @cindex @option{--dllname} (@command{dlltool})
28790 Gives the name of the DLL. This switch is used to embed the name of the
28791 DLL in the static import library generated by @code{dlltool} with switch
28792 @option{--output-lib}.
28795 @cindex @option{-k} (@command{dlltool})
28796 Kill @code{@@}@var{nn} from exported names
28797 (@pxref{Windows Calling Conventions}
28798 for a discussion about @code{Stdcall}-style symbols.
28801 @cindex @option{--help} (@command{dlltool})
28802 Prints the @code{dlltool} switches with a concise description.
28804 @item --output-exp @var{exportfile}
28805 @cindex @option{--output-exp} (@command{dlltool})
28806 Generate an export file @var{exportfile}. The export file contains the
28807 export table (list of symbols in the DLL) and is used to create the DLL.
28809 @item --output-lib @var{libfile}
28810 @cindex @option{--output-lib} (@command{dlltool})
28811 Generate a static import library @var{libfile}.
28814 @cindex @option{-v} (@command{dlltool})
28817 @item --as @var{assembler-name}
28818 @cindex @option{--as} (@command{dlltool})
28819 Use @var{assembler-name} as the assembler. The default is @code{as}.
28822 @node GNAT and Windows Resources
28823 @section GNAT and Windows Resources
28824 @cindex Resources, windows
28827 * Building Resources::
28828 * Compiling Resources::
28829 * Using Resources::
28833 Resources are an easy way to add Windows specific objects to your
28834 application. The objects that can be added as resources include:
28843 @item string tables
28853 @item version information
28856 For example, a version information resource can be defined as follow and
28857 embedded into an executable or DLL:
28859 A version information resource can be used to embed information into an
28860 executable or a DLL. These information can be viewed using the file properties
28861 from the Windows Explorer. Here is an example of a version information
28867 FILEVERSION 1,0,0,0
28868 PRODUCTVERSION 1,0,0,0
28870 BLOCK "StringFileInfo"
28874 VALUE "CompanyName", "My Company Name"
28875 VALUE "FileDescription", "My application"
28876 VALUE "FileVersion", "1.0"
28877 VALUE "InternalName", "my_app"
28878 VALUE "LegalCopyright", "My Name"
28879 VALUE "OriginalFilename", "my_app.exe"
28880 VALUE "ProductName", "My App"
28881 VALUE "ProductVersion", "1.0"
28885 BLOCK "VarFileInfo"
28887 VALUE "Translation", 0x809, 1252
28893 The value @code{0809} (langID) is for the U.K English language and
28894 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28898 This section explains how to build, compile and use resources. Note that this
28899 section does not cover all resource objects, for a complete description see
28900 the corresponding Microsoft documentation.
28902 @node Building Resources
28903 @subsection Building Resources
28904 @cindex Resources, building
28907 A resource file is an ASCII file. By convention resource files have an
28908 @file{.rc} extension.
28909 The easiest way to build a resource file is to use Microsoft tools
28910 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28911 @code{dlgedit.exe} to build dialogs.
28912 It is always possible to build an @file{.rc} file yourself by writing a
28915 It is not our objective to explain how to write a resource file. A
28916 complete description of the resource script language can be found in the
28917 Microsoft documentation.
28919 @node Compiling Resources
28920 @subsection Compiling Resources
28923 @cindex Resources, compiling
28926 This section describes how to build a GNAT-compatible (COFF) object file
28927 containing the resources. This is done using the Resource Compiler
28928 @code{windres} as follows:
28931 $ windres -i myres.rc -o myres.o
28935 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28936 file. You can specify an alternate preprocessor (usually named
28937 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28938 parameter. A list of all possible options may be obtained by entering
28939 the command @code{windres} @option{--help}.
28941 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28942 to produce a @file{.res} file (binary resource file). See the
28943 corresponding Microsoft documentation for further details. In this case
28944 you need to use @code{windres} to translate the @file{.res} file to a
28945 GNAT-compatible object file as follows:
28948 $ windres -i myres.res -o myres.o
28951 @node Using Resources
28952 @subsection Using Resources
28953 @cindex Resources, using
28956 To include the resource file in your program just add the
28957 GNAT-compatible object file for the resource(s) to the linker
28958 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28962 $ gnatmake myprog -largs myres.o
28965 @node Debugging a DLL
28966 @section Debugging a DLL
28967 @cindex DLL debugging
28970 * Program and DLL Both Built with GCC/GNAT::
28971 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28975 Debugging a DLL is similar to debugging a standard program. But
28976 we have to deal with two different executable parts: the DLL and the
28977 program that uses it. We have the following four possibilities:
28981 The program and the DLL are built with @code{GCC/GNAT}.
28983 The program is built with foreign tools and the DLL is built with
28986 The program is built with @code{GCC/GNAT} and the DLL is built with
28991 In this section we address only cases one and two above.
28992 There is no point in trying to debug
28993 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28994 information in it. To do so you must use a debugger compatible with the
28995 tools suite used to build the DLL.
28997 @node Program and DLL Both Built with GCC/GNAT
28998 @subsection Program and DLL Both Built with GCC/GNAT
29001 This is the simplest case. Both the DLL and the program have @code{GDB}
29002 compatible debugging information. It is then possible to break anywhere in
29003 the process. Let's suppose here that the main procedure is named
29004 @code{ada_main} and that in the DLL there is an entry point named
29008 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29009 program must have been built with the debugging information (see GNAT -g
29010 switch). Here are the step-by-step instructions for debugging it:
29013 @item Launch @code{GDB} on the main program.
29019 @item Start the program and stop at the beginning of the main procedure
29026 This step is required to be able to set a breakpoint inside the DLL. As long
29027 as the program is not run, the DLL is not loaded. This has the
29028 consequence that the DLL debugging information is also not loaded, so it is not
29029 possible to set a breakpoint in the DLL.
29031 @item Set a breakpoint inside the DLL
29034 (gdb) break ada_dll
29041 At this stage a breakpoint is set inside the DLL. From there on
29042 you can use the standard approach to debug the whole program
29043 (@pxref{Running and Debugging Ada Programs}).
29046 @c This used to work, probably because the DLLs were non-relocatable
29047 @c keep this section around until the problem is sorted out.
29049 To break on the @code{DllMain} routine it is not possible to follow
29050 the procedure above. At the time the program stop on @code{ada_main}
29051 the @code{DllMain} routine as already been called. Either you can use
29052 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29055 @item Launch @code{GDB} on the main program.
29061 @item Load DLL symbols
29064 (gdb) add-sym api.dll
29067 @item Set a breakpoint inside the DLL
29070 (gdb) break ada_dll.adb:45
29073 Note that at this point it is not possible to break using the routine symbol
29074 directly as the program is not yet running. The solution is to break
29075 on the proper line (break in @file{ada_dll.adb} line 45).
29077 @item Start the program
29086 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
29087 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
29090 * Debugging the DLL Directly::
29091 * Attaching to a Running Process::
29095 In this case things are slightly more complex because it is not possible to
29096 start the main program and then break at the beginning to load the DLL and the
29097 associated DLL debugging information. It is not possible to break at the
29098 beginning of the program because there is no @code{GDB} debugging information,
29099 and therefore there is no direct way of getting initial control. This
29100 section addresses this issue by describing some methods that can be used
29101 to break somewhere in the DLL to debug it.
29104 First suppose that the main procedure is named @code{main} (this is for
29105 example some C code built with Microsoft Visual C) and that there is a
29106 DLL named @code{test.dll} containing an Ada entry point named
29110 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29111 been built with debugging information (see GNAT -g option).
29113 @node Debugging the DLL Directly
29114 @subsubsection Debugging the DLL Directly
29118 Find out the executable starting address
29121 $ objdump --file-header main.exe
29124 The starting address is reported on the last line. For example:
29127 main.exe: file format pei-i386
29128 architecture: i386, flags 0x0000010a:
29129 EXEC_P, HAS_DEBUG, D_PAGED
29130 start address 0x00401010
29134 Launch the debugger on the executable.
29141 Set a breakpoint at the starting address, and launch the program.
29144 $ (gdb) break *0x00401010
29148 The program will stop at the given address.
29151 Set a breakpoint on a DLL subroutine.
29154 (gdb) break ada_dll.adb:45
29157 Or if you want to break using a symbol on the DLL, you need first to
29158 select the Ada language (language used by the DLL).
29161 (gdb) set language ada
29162 (gdb) break ada_dll
29166 Continue the program.
29173 This will run the program until it reaches the breakpoint that has been
29174 set. From that point you can use the standard way to debug a program
29175 as described in (@pxref{Running and Debugging Ada Programs}).
29180 It is also possible to debug the DLL by attaching to a running process.
29182 @node Attaching to a Running Process
29183 @subsubsection Attaching to a Running Process
29184 @cindex DLL debugging, attach to process
29187 With @code{GDB} it is always possible to debug a running process by
29188 attaching to it. It is possible to debug a DLL this way. The limitation
29189 of this approach is that the DLL must run long enough to perform the
29190 attach operation. It may be useful for instance to insert a time wasting
29191 loop in the code of the DLL to meet this criterion.
29195 @item Launch the main program @file{main.exe}.
29201 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29202 that the process PID for @file{main.exe} is 208.
29210 @item Attach to the running process to be debugged.
29216 @item Load the process debugging information.
29219 (gdb) symbol-file main.exe
29222 @item Break somewhere in the DLL.
29225 (gdb) break ada_dll
29228 @item Continue process execution.
29237 This last step will resume the process execution, and stop at
29238 the breakpoint we have set. From there you can use the standard
29239 approach to debug a program as described in
29240 (@pxref{Running and Debugging Ada Programs}).
29242 @node Setting Stack Size from gnatlink
29243 @section Setting Stack Size from @command{gnatlink}
29246 It is possible to specify the program stack size at link time. On modern
29247 versions of Windows, starting with XP, this is mostly useful to set the size of
29248 the main stack (environment task). The other task stacks are set with pragma
29249 Storage_Size or with the @command{gnatbind -d} command.
29251 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29252 reserve size of individual tasks, the link-time stack size applies to all
29253 tasks, and pragma Storage_Size has no effect.
29254 In particular, Stack Overflow checks are made against this
29255 link-time specified size.
29257 This setting can be done with
29258 @command{gnatlink} using either:
29262 @item using @option{-Xlinker} linker option
29265 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29268 This sets the stack reserve size to 0x10000 bytes and the stack commit
29269 size to 0x1000 bytes.
29271 @item using @option{-Wl} linker option
29274 $ gnatlink hello -Wl,--stack=0x1000000
29277 This sets the stack reserve size to 0x1000000 bytes. Note that with
29278 @option{-Wl} option it is not possible to set the stack commit size
29279 because the coma is a separator for this option.
29283 @node Setting Heap Size from gnatlink
29284 @section Setting Heap Size from @command{gnatlink}
29287 Under Windows systems, it is possible to specify the program heap size from
29288 @command{gnatlink} using either:
29292 @item using @option{-Xlinker} linker option
29295 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29298 This sets the heap reserve size to 0x10000 bytes and the heap commit
29299 size to 0x1000 bytes.
29301 @item using @option{-Wl} linker option
29304 $ gnatlink hello -Wl,--heap=0x1000000
29307 This sets the heap reserve size to 0x1000000 bytes. Note that with
29308 @option{-Wl} option it is not possible to set the heap commit size
29309 because the coma is a separator for this option.
29315 @c **********************************
29316 @c * GNU Free Documentation License *
29317 @c **********************************
29319 @c GNU Free Documentation License
29321 @node Index,,GNU Free Documentation License, Top
29327 @c Put table of contents at end, otherwise it precedes the "title page" in
29328 @c the .txt version
29329 @c Edit the pdf file to move the contents to the beginning, after the title