1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com). o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14 @setfilename gnat_ugn.info
17 Copyright @copyright{} 1995-2005, 2006, 2007, 2008 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.2 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
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
117 @include gcc-common.texi
119 @setchapternewpage odd
124 @title @value{EDITION} User's Guide
128 @titlefont{@i{@value{PLATFORM}}}
134 @subtitle GNAT, The GNU Ada Compiler
139 @vskip 0pt plus 1filll
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
150 @value{EDITION} User's Guide @value{PLATFORM}
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
178 * The GNAT Run-Time Library Builder gnatlbr::
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Other Utility Programs::
191 * Running and Debugging Ada Programs::
193 * Code Coverage and Profiling::
196 * Compatibility with HP Ada::
198 * Platform-Specific Information for the Run-Time Libraries::
199 * Example of Binder Output File::
200 * Elaboration Order Handling in GNAT::
201 * Conditional Compilation::
203 * Compatibility and Porting Guide::
205 * Microsoft Windows Topics::
207 * GNU Free Documentation License::
210 --- The Detailed Node Listing ---
214 * What This Guide Contains::
215 * What You Should Know before Reading This Guide::
216 * Related Information::
219 Getting Started with GNAT
222 * Running a Simple Ada Program::
223 * Running a Program with Multiple Units::
224 * Using the gnatmake Utility::
226 * Editing with Emacs::
229 * Introduction to GPS::
232 The GNAT Compilation Model
234 * Source Representation::
235 * Foreign Language Representation::
236 * File Naming Rules::
237 * Using Other File Names::
238 * Alternative File Naming Schemes::
239 * Generating Object Files::
240 * Source Dependencies::
241 * The Ada Library Information Files::
242 * Binding an Ada Program::
243 * Mixed Language Programming::
245 * Building Mixed Ada & C++ Programs::
246 * Comparison between GNAT and C/C++ Compilation Models::
248 * Comparison between GNAT and Conventional Ada Library Models::
250 * Placement of temporary files::
253 Foreign Language Representation
256 * Other 8-Bit Codes::
257 * Wide Character Encodings::
259 Compiling Ada Programs With gcc
261 * Compiling Programs::
263 * Search Paths and the Run-Time Library (RTL)::
264 * Order of Compilation Issues::
269 * Output and Error Message Control::
270 * Warning Message Control::
271 * Debugging and Assertion Control::
272 * Validity Checking::
275 * Using gcc for Syntax Checking::
276 * Using gcc for Semantic Checking::
277 * Compiling Different Versions of Ada::
278 * Character Set Control::
279 * File Naming Control::
280 * Subprogram Inlining Control::
281 * Auxiliary Output Control::
282 * Debugging Control::
283 * Exception Handling Control::
284 * Units to Sources Mapping Files::
285 * Integrated Preprocessing::
290 Binding Ada Programs With gnatbind
293 * Switches for gnatbind::
294 * Command-Line Access::
295 * Search Paths for gnatbind::
296 * Examples of gnatbind Usage::
298 Switches for gnatbind
300 * Consistency-Checking Modes::
301 * Binder Error Message Control::
302 * Elaboration Control::
304 * Binding with Non-Ada Main Programs::
305 * Binding Programs with No Main Subprogram::
307 Linking Using gnatlink
310 * Switches for gnatlink::
312 The GNAT Make Program gnatmake
315 * Switches for gnatmake::
316 * Mode Switches for gnatmake::
317 * Notes on the Command Line::
318 * How gnatmake Works::
319 * Examples of gnatmake Usage::
321 Improving Performance
322 * Performance Considerations::
323 * Text_IO Suggestions::
324 * Reducing Size of Ada Executables with gnatelim::
325 * Reducing Size of Executables with unused subprogram/data elimination::
327 Performance Considerations
328 * Controlling Run-Time Checks::
329 * Use of Restrictions::
330 * Optimization Levels::
331 * Debugging Optimized Code::
332 * Inlining of Subprograms::
333 * Other Optimization Switches::
334 * Optimization and Strict Aliasing::
336 * Coverage Analysis::
339 Reducing Size of Ada Executables with gnatelim
342 * Correcting the List of Eliminate Pragmas::
343 * Making Your Executables Smaller::
344 * Summary of the gnatelim Usage Cycle::
346 Reducing Size of Executables with unused subprogram/data elimination
347 * About unused subprogram/data elimination::
348 * Compilation options::
350 Renaming Files Using gnatchop
352 * Handling Files with Multiple Units::
353 * Operating gnatchop in Compilation Mode::
354 * Command Line for gnatchop::
355 * Switches for gnatchop::
356 * Examples of gnatchop Usage::
358 Configuration Pragmas
360 * Handling of Configuration Pragmas::
361 * The Configuration Pragmas Files::
363 Handling Arbitrary File Naming Conventions Using gnatname
365 * Arbitrary File Naming Conventions::
367 * Switches for gnatname::
368 * Examples of gnatname Usage::
373 * Examples of Project Files::
374 * Project File Syntax::
375 * Objects and Sources in Project Files::
376 * Importing Projects::
377 * Project Extension::
378 * Project Hierarchy Extension::
379 * External References in Project Files::
380 * Packages in Project Files::
381 * Variables from Imported Projects::
384 * Stand-alone Library Projects::
385 * Switches Related to Project Files::
386 * Tools Supporting Project Files::
387 * An Extended Example::
388 * Project File Complete Syntax::
390 The Cross-Referencing Tools gnatxref and gnatfind
392 * gnatxref Switches::
393 * gnatfind Switches::
394 * Project Files for gnatxref and gnatfind::
395 * Regular Expressions in gnatfind and gnatxref::
396 * Examples of gnatxref Usage::
397 * Examples of gnatfind Usage::
399 The GNAT Pretty-Printer gnatpp
401 * Switches for gnatpp::
404 The GNAT Metrics Tool gnatmetric
406 * Switches for gnatmetric::
408 File Name Krunching Using gnatkr
413 * Examples of gnatkr Usage::
415 Preprocessing Using gnatprep
416 * Preprocessing Symbols::
418 * Switches for gnatprep::
419 * Form of Definitions File::
420 * Form of Input Text for gnatprep::
423 The GNAT Run-Time Library Builder gnatlbr
426 * Switches for gnatlbr::
427 * Examples of gnatlbr Usage::
430 The GNAT Library Browser gnatls
433 * Switches for gnatls::
434 * Examples of gnatls Usage::
436 Cleaning Up Using gnatclean
438 * Running gnatclean::
439 * Switches for gnatclean::
440 @c * Examples of gnatclean Usage::
446 * Introduction to Libraries in GNAT::
447 * General Ada Libraries::
448 * Stand-alone Ada Libraries::
449 * Rebuilding the GNAT Run-Time Library::
451 Using the GNU make Utility
453 * Using gnatmake in a Makefile::
454 * Automatically Creating a List of Directories::
455 * Generating the Command Line Switches::
456 * Overcoming Command Line Length Limits::
459 Memory Management Issues
461 * Some Useful Memory Pools::
462 * The GNAT Debug Pool Facility::
467 Stack Related Facilities
469 * Stack Overflow Checking::
470 * Static Stack Usage Analysis::
471 * Dynamic Stack Usage Analysis::
473 Some Useful Memory Pools
475 The GNAT Debug Pool Facility
481 * Switches for gnatmem::
482 * Example of gnatmem Usage::
485 Verifying Properties Using gnatcheck
487 * Format of the Report File::
488 * General gnatcheck Switches::
489 * gnatcheck Rule Options::
490 * Adding the Results of Compiler Checks to gnatcheck Output::
491 * Project-Wide Checks::
494 Sample Bodies Using gnatstub
497 * Switches for gnatstub::
499 Other Utility Programs
501 * Using Other Utility Programs with GNAT::
502 * The External Symbol Naming Scheme of GNAT::
503 * Converting Ada Files to html with gnathtml::
506 Code Coverage and Profiling
508 * Code Coverage of Ada Programs using gcov::
509 * Profiling an Ada Program using gprof::
512 Running and Debugging Ada Programs
514 * The GNAT Debugger GDB::
516 * Introduction to GDB Commands::
517 * Using Ada Expressions::
518 * Calling User-Defined Subprograms::
519 * Using the Next Command in a Function::
522 * Debugging Generic Units::
523 * GNAT Abnormal Termination or Failure to Terminate::
524 * Naming Conventions for GNAT Source Files::
525 * Getting Internal Debugging Information::
533 Compatibility with HP Ada
535 * Ada Language Compatibility::
536 * Differences in the Definition of Package System::
537 * Language-Related Features::
538 * The Package STANDARD::
539 * The Package SYSTEM::
540 * Tasking and Task-Related Features::
541 * Pragmas and Pragma-Related Features::
542 * Library of Predefined Units::
544 * Main Program Definition::
545 * Implementation-Defined Attributes::
546 * Compiler and Run-Time Interfacing::
547 * Program Compilation and Library Management::
549 * Implementation Limits::
550 * Tools and Utilities::
552 Language-Related Features
554 * Integer Types and Representations::
555 * Floating-Point Types and Representations::
556 * Pragmas Float_Representation and Long_Float::
557 * Fixed-Point Types and Representations::
558 * Record and Array Component Alignment::
560 * Other Representation Clauses::
562 Tasking and Task-Related Features
564 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
565 * Assigning Task IDs::
566 * Task IDs and Delays::
567 * Task-Related Pragmas::
568 * Scheduling and Task Priority::
570 * External Interrupts::
572 Pragmas and Pragma-Related Features
574 * Restrictions on the Pragma INLINE::
575 * Restrictions on the Pragma INTERFACE::
576 * Restrictions on the Pragma SYSTEM_NAME::
578 Library of Predefined Units
580 * Changes to DECLIB::
584 * Shared Libraries and Options Files::
588 Platform-Specific Information for the Run-Time Libraries
590 * Summary of Run-Time Configurations::
591 * Specifying a Run-Time Library::
592 * Choosing the Scheduling Policy::
593 * Solaris-Specific Considerations::
594 * Linux-Specific Considerations::
595 * AIX-Specific Considerations::
596 * Irix-Specific Considerations::
598 Example of Binder Output File
600 Elaboration Order Handling in GNAT
603 * Checking the Elaboration Order::
604 * Controlling the Elaboration Order::
605 * Controlling Elaboration in GNAT - Internal Calls::
606 * Controlling Elaboration in GNAT - External Calls::
607 * Default Behavior in GNAT - Ensuring Safety::
608 * Treatment of Pragma Elaborate::
609 * Elaboration Issues for Library Tasks::
610 * Mixing Elaboration Models::
611 * What to Do If the Default Elaboration Behavior Fails::
612 * Elaboration for Access-to-Subprogram Values::
613 * Summary of Procedures for Elaboration Control::
614 * Other Elaboration Order Considerations::
616 Conditional Compilation
617 * Use of Boolean Constants::
618 * Debugging - A Special Case::
619 * Conditionalizing Declarations::
620 * Use of Alternative Implementations::
625 * Basic Assembler Syntax::
626 * A Simple Example of Inline Assembler::
627 * Output Variables in Inline Assembler::
628 * Input Variables in Inline Assembler::
629 * Inlining Inline Assembler Code::
630 * Other Asm Functionality::
632 Compatibility and Porting Guide
634 * Compatibility with Ada 83::
635 * Compatibility between Ada 95 and Ada 2005::
636 * Implementation-dependent characteristics::
638 @c This brief section is only in the non-VMS version
639 @c The complete chapter on HP Ada issues is in the VMS version
640 * Compatibility with HP Ada 83::
642 * Compatibility with Other Ada Systems::
643 * Representation Clauses::
645 * Transitioning to 64-Bit GNAT for OpenVMS::
649 Microsoft Windows Topics
651 * Using GNAT on Windows::
652 * CONSOLE and WINDOWS subsystems::
654 * Mixed-Language Programming on Windows::
655 * Windows Calling Conventions::
656 * Introduction to Dynamic Link Libraries (DLLs)::
657 * Using DLLs with GNAT::
658 * Building DLLs with GNAT::
659 * GNAT and Windows Resources::
661 * Setting Stack Size from gnatlink::
662 * Setting Heap Size from gnatlink::
669 @node About This Guide
670 @unnumbered About This Guide
674 This guide describes the use of @value{EDITION},
675 a compiler and software development toolset for the full Ada
676 programming language, implemented on OpenVMS for HP's Alpha and
677 Integrity server (I64) platforms.
680 This guide describes the use of @value{EDITION},
681 a compiler and software development
682 toolset for the full Ada programming language.
684 It documents the features of the compiler and tools, and explains
685 how to use them to build Ada applications.
687 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
688 Ada 83 compatibility mode.
689 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
690 but you can override with a compiler switch
691 (@pxref{Compiling Different Versions of Ada})
692 to explicitly specify the language version.
693 Throughout this manual, references to ``Ada'' without a year suffix
694 apply to both the Ada 95 and Ada 2005 versions of the language.
698 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
699 ``GNAT'' in the remainder of this document.
706 * What This Guide Contains::
707 * What You Should Know before Reading This Guide::
708 * Related Information::
712 @node What This Guide Contains
713 @unnumberedsec What This Guide Contains
716 This guide contains the following chapters:
720 @ref{Getting Started with GNAT}, describes how to get started compiling
721 and running Ada programs with the GNAT Ada programming environment.
723 @ref{The GNAT Compilation Model}, describes the compilation model used
727 @ref{Compiling Using gcc}, describes how to compile
728 Ada programs with @command{gcc}, the Ada compiler.
731 @ref{Binding Using gnatbind}, describes how to
732 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
736 @ref{Linking Using gnatlink},
737 describes @command{gnatlink}, a
738 program that provides for linking using the GNAT run-time library to
739 construct a program. @command{gnatlink} can also incorporate foreign language
740 object units into the executable.
743 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
744 utility that automatically determines the set of sources
745 needed by an Ada compilation unit, and executes the necessary compilations
749 @ref{Improving Performance}, shows various techniques for making your
750 Ada program run faster or take less space.
751 It discusses the effect of the compiler's optimization switch and
752 also describes the @command{gnatelim} tool and unused subprogram/data
756 @ref{Renaming Files Using gnatchop}, describes
757 @code{gnatchop}, a utility that allows you to preprocess a file that
758 contains Ada source code, and split it into one or more new files, one
759 for each compilation unit.
762 @ref{Configuration Pragmas}, describes the configuration pragmas
766 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
767 shows how to override the default GNAT file naming conventions,
768 either for an individual unit or globally.
771 @ref{GNAT Project Manager}, describes how to use project files
772 to organize large projects.
775 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
776 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
777 way to navigate through sources.
780 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
781 version of an Ada source file with control over casing, indentation,
782 comment placement, and other elements of program presentation style.
785 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
786 metrics for an Ada source file, such as the number of types and subprograms,
787 and assorted complexity measures.
790 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
791 file name krunching utility, used to handle shortened
792 file names on operating systems with a limit on the length of names.
795 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
796 preprocessor utility that allows a single source file to be used to
797 generate multiple or parameterized source files by means of macro
802 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
803 a tool for rebuilding the GNAT run time with user-supplied
804 configuration pragmas.
808 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
809 utility that displays information about compiled units, including dependences
810 on the corresponding sources files, and consistency of compilations.
813 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
814 to delete files that are produced by the compiler, binder and linker.
818 @ref{GNAT and Libraries}, describes the process of creating and using
819 Libraries with GNAT. It also describes how to recompile the GNAT run-time
823 @ref{Using the GNU make Utility}, describes some techniques for using
824 the GNAT toolset in Makefiles.
828 @ref{Memory Management Issues}, describes some useful predefined storage pools
829 and in particular the GNAT Debug Pool facility, which helps detect incorrect
832 It also describes @command{gnatmem}, a utility that monitors dynamic
833 allocation and deallocation and helps detect ``memory leaks''.
837 @ref{Stack Related Facilities}, describes some useful tools associated with
838 stack checking and analysis.
841 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
842 a utility that checks Ada code against a set of rules.
845 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
846 a utility that generates empty but compilable bodies for library units.
849 @ref{Other Utility Programs}, discusses several other GNAT utilities,
850 including @code{gnathtml}.
854 @ref{Code Coverage and Profiling}, describes how to perform a structural
855 coverage and profile the execution of Ada programs.
859 @ref{Running and Debugging Ada Programs}, describes how to run and debug
864 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
865 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
866 developed by Digital Equipment Corporation and currently supported by HP.}
867 for OpenVMS Alpha. This product was formerly known as DEC Ada,
870 historical compatibility reasons, the relevant libraries still use the
875 @ref{Platform-Specific Information for the Run-Time Libraries},
876 describes the various run-time
877 libraries supported by GNAT on various platforms and explains how to
878 choose a particular library.
881 @ref{Example of Binder Output File}, shows the source code for the binder
882 output file for a sample program.
885 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
886 you deal with elaboration order issues.
889 @ref{Conditional Compilation}, describes how to model conditional compilation,
890 both with Ada in general and with GNAT facilities in particular.
893 @ref{Inline Assembler}, shows how to use the inline assembly facility
897 @ref{Compatibility and Porting Guide}, contains sections on compatibility
898 of GNAT with other Ada development environments (including Ada 83 systems),
899 to assist in porting code from those environments.
903 @ref{Microsoft Windows Topics}, presents information relevant to the
904 Microsoft Windows platform.
908 @c *************************************************
909 @node What You Should Know before Reading This Guide
910 @c *************************************************
911 @unnumberedsec What You Should Know before Reading This Guide
913 @cindex Ada 95 Language Reference Manual
914 @cindex Ada 2005 Language Reference Manual
916 This guide assumes a basic familiarity with the Ada 95 language, as
917 described in the International Standard ANSI/ISO/IEC-8652:1995, January
919 It does not require knowledge of the new features introduced by Ada 2005,
920 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
922 Both reference manuals are included in the GNAT documentation
925 @node Related Information
926 @unnumberedsec Related Information
929 For further information about related tools, refer to the following
934 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
935 Reference Manual}, which contains all reference material for the GNAT
936 implementation of Ada.
940 @cite{Using the GNAT Programming Studio}, which describes the GPS
941 Integrated Development Environment.
944 @cite{GNAT Programming Studio Tutorial}, which introduces the
945 main GPS features through examples.
949 @cite{Ada 95 Reference Manual}, which contains reference
950 material for the Ada 95 programming language.
953 @cite{Ada 2005 Reference Manual}, which contains reference
954 material for the Ada 2005 programming language.
957 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
959 in the GNU:[DOCS] directory,
961 for all details on the use of the GNU source-level debugger.
964 @xref{Top,, The extensible self-documenting text editor, emacs,
967 located in the GNU:[DOCS] directory if the EMACS kit is installed,
969 for full information on the extensible editor and programming
976 @unnumberedsec Conventions
978 @cindex Typographical conventions
981 Following are examples of the typographical and graphic conventions used
986 @code{Functions}, @command{utility program names}, @code{standard names},
990 @option{Option flags}
993 @file{File names}, @samp{button names}, and @samp{field names}.
996 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1003 @r{[}optional information or parameters@r{]}
1006 Examples are described by text
1008 and then shown this way.
1013 Commands that are entered by the user are preceded in this manual by the
1014 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1015 uses this sequence as a prompt, then the commands will appear exactly as
1016 you see them in the manual. If your system uses some other prompt, then
1017 the command will appear with the @code{$} replaced by whatever prompt
1018 character you are using.
1021 Full file names are shown with the ``@code{/}'' character
1022 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1023 If you are using GNAT on a Windows platform, please note that
1024 the ``@code{\}'' character should be used instead.
1027 @c ****************************
1028 @node Getting Started with GNAT
1029 @chapter Getting Started with GNAT
1032 This chapter describes some simple ways of using GNAT to build
1033 executable Ada programs.
1035 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1036 show how to use the command line environment.
1037 @ref{Introduction to GPS}, provides a brief
1038 introduction to the GNAT Programming Studio, a visually-oriented
1039 Integrated Development Environment for GNAT.
1040 GPS offers a graphical ``look and feel'', support for development in
1041 other programming languages, comprehensive browsing features, and
1042 many other capabilities.
1043 For information on GPS please refer to
1044 @cite{Using the GNAT Programming Studio}.
1049 * Running a Simple Ada Program::
1050 * Running a Program with Multiple Units::
1051 * Using the gnatmake Utility::
1053 * Editing with Emacs::
1056 * Introduction to GPS::
1061 @section Running GNAT
1064 Three steps are needed to create an executable file from an Ada source
1069 The source file(s) must be compiled.
1071 The file(s) must be bound using the GNAT binder.
1073 All appropriate object files must be linked to produce an executable.
1077 All three steps are most commonly handled by using the @command{gnatmake}
1078 utility program that, given the name of the main program, automatically
1079 performs the necessary compilation, binding and linking steps.
1081 @node Running a Simple Ada Program
1082 @section Running a Simple Ada Program
1085 Any text editor may be used to prepare an Ada program.
1087 used, the optional Ada mode may be helpful in laying out the program.)
1089 program text is a normal text file. We will assume in our initial
1090 example that you have used your editor to prepare the following
1091 standard format text file:
1093 @smallexample @c ada
1095 with Ada.Text_IO; use Ada.Text_IO;
1098 Put_Line ("Hello WORLD!");
1104 This file should be named @file{hello.adb}.
1105 With the normal default file naming conventions, GNAT requires
1107 contain a single compilation unit whose file name is the
1109 with periods replaced by hyphens; the
1110 extension is @file{ads} for a
1111 spec and @file{adb} for a body.
1112 You can override this default file naming convention by use of the
1113 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1114 Alternatively, if you want to rename your files according to this default
1115 convention, which is probably more convenient if you will be using GNAT
1116 for all your compilations, then the @code{gnatchop} utility
1117 can be used to generate correctly-named source files
1118 (@pxref{Renaming Files Using gnatchop}).
1120 You can compile the program using the following command (@code{$} is used
1121 as the command prompt in the examples in this document):
1128 @command{gcc} is the command used to run the compiler. This compiler is
1129 capable of compiling programs in several languages, including Ada and
1130 C. It assumes that you have given it an Ada program if the file extension is
1131 either @file{.ads} or @file{.adb}, and it will then call
1132 the GNAT compiler to compile the specified file.
1135 The @option{-c} switch is required. It tells @command{gcc} to only do a
1136 compilation. (For C programs, @command{gcc} can also do linking, but this
1137 capability is not used directly for Ada programs, so the @option{-c}
1138 switch must always be present.)
1141 This compile command generates a file
1142 @file{hello.o}, which is the object
1143 file corresponding to your Ada program. It also generates
1144 an ``Ada Library Information'' file @file{hello.ali},
1145 which contains additional information used to check
1146 that an Ada program is consistent.
1147 To build an executable file,
1148 use @code{gnatbind} to bind the program
1149 and @command{gnatlink} to link it. The
1150 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1151 @file{ALI} file, but the default extension of @file{.ali} can
1152 be omitted. This means that in the most common case, the argument
1153 is simply the name of the main program:
1161 A simpler method of carrying out these steps is to use
1163 a master program that invokes all the required
1164 compilation, binding and linking tools in the correct order. In particular,
1165 @command{gnatmake} automatically recompiles any sources that have been
1166 modified since they were last compiled, or sources that depend
1167 on such modified sources, so that ``version skew'' is avoided.
1168 @cindex Version skew (avoided by @command{gnatmake})
1171 $ gnatmake hello.adb
1175 The result is an executable program called @file{hello}, which can be
1183 assuming that the current directory is on the search path
1184 for executable programs.
1187 and, if all has gone well, you will see
1194 appear in response to this command.
1196 @c ****************************************
1197 @node Running a Program with Multiple Units
1198 @section Running a Program with Multiple Units
1201 Consider a slightly more complicated example that has three files: a
1202 main program, and the spec and body of a package:
1204 @smallexample @c ada
1207 package Greetings is
1212 with Ada.Text_IO; use Ada.Text_IO;
1213 package body Greetings is
1216 Put_Line ("Hello WORLD!");
1219 procedure Goodbye is
1221 Put_Line ("Goodbye WORLD!");
1238 Following the one-unit-per-file rule, place this program in the
1239 following three separate files:
1243 spec of package @code{Greetings}
1246 body of package @code{Greetings}
1249 body of main program
1253 To build an executable version of
1254 this program, we could use four separate steps to compile, bind, and link
1255 the program, as follows:
1259 $ gcc -c greetings.adb
1265 Note that there is no required order of compilation when using GNAT.
1266 In particular it is perfectly fine to compile the main program first.
1267 Also, it is not necessary to compile package specs in the case where
1268 there is an accompanying body; you only need to compile the body. If you want
1269 to submit these files to the compiler for semantic checking and not code
1270 generation, then use the
1271 @option{-gnatc} switch:
1274 $ gcc -c greetings.ads -gnatc
1278 Although the compilation can be done in separate steps as in the
1279 above example, in practice it is almost always more convenient
1280 to use the @command{gnatmake} tool. All you need to know in this case
1281 is the name of the main program's source file. The effect of the above four
1282 commands can be achieved with a single one:
1285 $ gnatmake gmain.adb
1289 In the next section we discuss the advantages of using @command{gnatmake} in
1292 @c *****************************
1293 @node Using the gnatmake Utility
1294 @section Using the @command{gnatmake} Utility
1297 If you work on a program by compiling single components at a time using
1298 @command{gcc}, you typically keep track of the units you modify. In order to
1299 build a consistent system, you compile not only these units, but also any
1300 units that depend on the units you have modified.
1301 For example, in the preceding case,
1302 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1303 you edit @file{greetings.ads}, you must recompile both
1304 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1305 units that depend on @file{greetings.ads}.
1307 @code{gnatbind} will warn you if you forget one of these compilation
1308 steps, so that it is impossible to generate an inconsistent program as a
1309 result of forgetting to do a compilation. Nevertheless it is tedious and
1310 error-prone to keep track of dependencies among units.
1311 One approach to handle the dependency-bookkeeping is to use a
1312 makefile. However, makefiles present maintenance problems of their own:
1313 if the dependencies change as you change the program, you must make
1314 sure that the makefile is kept up-to-date manually, which is also an
1315 error-prone process.
1317 The @command{gnatmake} utility takes care of these details automatically.
1318 Invoke it using either one of the following forms:
1321 $ gnatmake gmain.adb
1322 $ gnatmake ^gmain^GMAIN^
1326 The argument is the name of the file containing the main program;
1327 you may omit the extension. @command{gnatmake}
1328 examines the environment, automatically recompiles any files that need
1329 recompiling, and binds and links the resulting set of object files,
1330 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1331 In a large program, it
1332 can be extremely helpful to use @command{gnatmake}, because working out by hand
1333 what needs to be recompiled can be difficult.
1335 Note that @command{gnatmake}
1336 takes into account all the Ada rules that
1337 establish dependencies among units. These include dependencies that result
1338 from inlining subprogram bodies, and from
1339 generic instantiation. Unlike some other
1340 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1341 found by the compiler on a previous compilation, which may possibly
1342 be wrong when sources change. @command{gnatmake} determines the exact set of
1343 dependencies from scratch each time it is run.
1346 @node Editing with Emacs
1347 @section Editing with Emacs
1351 Emacs is an extensible self-documenting text editor that is available in a
1352 separate VMSINSTAL kit.
1354 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1355 click on the Emacs Help menu and run the Emacs Tutorial.
1356 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1357 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1359 Documentation on Emacs and other tools is available in Emacs under the
1360 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1361 use the middle mouse button to select a topic (e.g.@: Emacs).
1363 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1364 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1365 get to the Emacs manual.
1366 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1369 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1370 which is sufficiently extensible to provide for a complete programming
1371 environment and shell for the sophisticated user.
1375 @node Introduction to GPS
1376 @section Introduction to GPS
1377 @cindex GPS (GNAT Programming Studio)
1378 @cindex GNAT Programming Studio (GPS)
1380 Although the command line interface (@command{gnatmake}, etc.) alone
1381 is sufficient, a graphical Interactive Development
1382 Environment can make it easier for you to compose, navigate, and debug
1383 programs. This section describes the main features of GPS
1384 (``GNAT Programming Studio''), the GNAT graphical IDE.
1385 You will see how to use GPS to build and debug an executable, and
1386 you will also learn some of the basics of the GNAT ``project'' facility.
1388 GPS enables you to do much more than is presented here;
1389 e.g., you can produce a call graph, interface to a third-party
1390 Version Control System, and inspect the generated assembly language
1392 Indeed, GPS also supports languages other than Ada.
1393 Such additional information, and an explanation of all of the GPS menu
1394 items. may be found in the on-line help, which includes
1395 a user's guide and a tutorial (these are also accessible from the GNAT
1399 * Building a New Program with GPS::
1400 * Simple Debugging with GPS::
1403 @node Building a New Program with GPS
1404 @subsection Building a New Program with GPS
1406 GPS invokes the GNAT compilation tools using information
1407 contained in a @emph{project} (also known as a @emph{project file}):
1408 a collection of properties such
1409 as source directories, identities of main subprograms, tool switches, etc.,
1410 and their associated values.
1411 See @ref{GNAT Project Manager} for details.
1412 In order to run GPS, you will need to either create a new project
1413 or else open an existing one.
1415 This section will explain how you can use GPS to create a project,
1416 to associate Ada source files with a project, and to build and run
1420 @item @emph{Creating a project}
1422 Invoke GPS, either from the command line or the platform's IDE.
1423 After it starts, GPS will display a ``Welcome'' screen with three
1428 @code{Start with default project in directory}
1431 @code{Create new project with wizard}
1434 @code{Open existing project}
1438 Select @code{Create new project with wizard} and press @code{OK}.
1439 A new window will appear. In the text box labeled with
1440 @code{Enter the name of the project to create}, type @file{sample}
1441 as the project name.
1442 In the next box, browse to choose the directory in which you
1443 would like to create the project file.
1444 After selecting an appropriate directory, press @code{Forward}.
1446 A window will appear with the title
1447 @code{Version Control System Configuration}.
1448 Simply press @code{Forward}.
1450 A window will appear with the title
1451 @code{Please select the source directories for this project}.
1452 The directory that you specified for the project file will be selected
1453 by default as the one to use for sources; simply press @code{Forward}.
1455 A window will appear with the title
1456 @code{Please select the build directory for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default for object files and executables;
1459 simply press @code{Forward}.
1461 A window will appear with the title
1462 @code{Please select the main units for this project}.
1463 You will supply this information later, after creating the source file.
1464 Simply press @code{Forward} for now.
1466 A window will appear with the title
1467 @code{Please select the switches to build the project}.
1468 Press @code{Apply}. This will create a project file named
1469 @file{sample.prj} in the directory that you had specified.
1471 @item @emph{Creating and saving the source file}
1473 After you create the new project, a GPS window will appear, which is
1474 partitioned into two main sections:
1478 A @emph{Workspace area}, initially greyed out, which you will use for
1479 creating and editing source files
1482 Directly below, a @emph{Messages area}, which initially displays a
1483 ``Welcome'' message.
1484 (If the Messages area is not visible, drag its border upward to expand it.)
1488 Select @code{File} on the menu bar, and then the @code{New} command.
1489 The Workspace area will become white, and you can now
1490 enter the source program explicitly.
1491 Type the following text
1493 @smallexample @c ada
1495 with Ada.Text_IO; use Ada.Text_IO;
1498 Put_Line("Hello from GPS!");
1504 Select @code{File}, then @code{Save As}, and enter the source file name
1506 The file will be saved in the same directory you specified as the
1507 location of the default project file.
1509 @item @emph{Updating the project file}
1511 You need to add the new source file to the project.
1513 the @code{Project} menu and then @code{Edit project properties}.
1514 Click the @code{Main files} tab on the left, and then the
1516 Choose @file{hello.adb} from the list, and press @code{Open}.
1517 The project settings window will reflect this action.
1520 @item @emph{Building and running the program}
1522 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1523 and select @file{hello.adb}.
1524 The Messages window will display the resulting invocations of @command{gcc},
1525 @command{gnatbind}, and @command{gnatlink}
1526 (reflecting the default switch settings from the
1527 project file that you created) and then a ``successful compilation/build''
1530 To run the program, choose the @code{Build} menu, then @code{Run}, and
1531 select @command{hello}.
1532 An @emph{Arguments Selection} window will appear.
1533 There are no command line arguments, so just click @code{OK}.
1535 The Messages window will now display the program's output (the string
1536 @code{Hello from GPS}), and at the bottom of the GPS window a status
1537 update is displayed (@code{Run: hello}).
1538 Close the GPS window (or select @code{File}, then @code{Exit}) to
1539 terminate this GPS session.
1542 @node Simple Debugging with GPS
1543 @subsection Simple Debugging with GPS
1545 This section illustrates basic debugging techniques (setting breakpoints,
1546 examining/modifying variables, single stepping).
1549 @item @emph{Opening a project}
1551 Start GPS and select @code{Open existing project}; browse to
1552 specify the project file @file{sample.prj} that you had created in the
1555 @item @emph{Creating a source file}
1557 Select @code{File}, then @code{New}, and type in the following program:
1559 @smallexample @c ada
1561 with Ada.Text_IO; use Ada.Text_IO;
1562 procedure Example is
1563 Line : String (1..80);
1566 Put_Line("Type a line of text at each prompt; an empty line to exit");
1570 Put_Line (Line (1..N) );
1578 Select @code{File}, then @code{Save as}, and enter the file name
1581 @item @emph{Updating the project file}
1583 Add @code{Example} as a new main unit for the project:
1586 Select @code{Project}, then @code{Edit Project Properties}.
1589 Select the @code{Main files} tab, click @code{Add}, then
1590 select the file @file{example.adb} from the list, and
1592 You will see the file name appear in the list of main units
1598 @item @emph{Building/running the executable}
1600 To build the executable
1601 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1603 Run the program to see its effect (in the Messages area).
1604 Each line that you enter is displayed; an empty line will
1605 cause the loop to exit and the program to terminate.
1607 @item @emph{Debugging the program}
1609 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1610 which are required for debugging, are on by default when you create
1612 Thus unless you intentionally remove these settings, you will be able
1613 to debug any program that you develop using GPS.
1616 @item @emph{Initializing}
1618 Select @code{Debug}, then @code{Initialize}, then @file{example}
1620 @item @emph{Setting a breakpoint}
1622 After performing the initialization step, you will observe a small
1623 icon to the right of each line number.
1624 This serves as a toggle for breakpoints; clicking the icon will
1625 set a breakpoint at the corresponding line (the icon will change to
1626 a red circle with an ``x''), and clicking it again
1627 will remove the breakpoint / reset the icon.
1629 For purposes of this example, set a breakpoint at line 10 (the
1630 statement @code{Put_Line@ (Line@ (1..N));}
1632 @item @emph{Starting program execution}
1634 Select @code{Debug}, then @code{Run}. When the
1635 @code{Program Arguments} window appears, click @code{OK}.
1636 A console window will appear; enter some line of text,
1637 e.g.@: @code{abcde}, at the prompt.
1638 The program will pause execution when it gets to the
1639 breakpoint, and the corresponding line is highlighted.
1641 @item @emph{Examining a variable}
1643 Move the mouse over one of the occurrences of the variable @code{N}.
1644 You will see the value (5) displayed, in ``tool tip'' fashion.
1645 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1646 You will see information about @code{N} appear in the @code{Debugger Data}
1647 pane, showing the value as 5.
1649 @item @emph{Assigning a new value to a variable}
1651 Right click on the @code{N} in the @code{Debugger Data} pane, and
1652 select @code{Set value of N}.
1653 When the input window appears, enter the value @code{4} and click
1655 This value does not automatically appear in the @code{Debugger Data}
1656 pane; to see it, right click again on the @code{N} in the
1657 @code{Debugger Data} pane and select @code{Update value}.
1658 The new value, 4, will appear in red.
1660 @item @emph{Single stepping}
1662 Select @code{Debug}, then @code{Next}.
1663 This will cause the next statement to be executed, in this case the
1664 call of @code{Put_Line} with the string slice.
1665 Notice in the console window that the displayed string is simply
1666 @code{abcd} and not @code{abcde} which you had entered.
1667 This is because the upper bound of the slice is now 4 rather than 5.
1669 @item @emph{Removing a breakpoint}
1671 Toggle the breakpoint icon at line 10.
1673 @item @emph{Resuming execution from a breakpoint}
1675 Select @code{Debug}, then @code{Continue}.
1676 The program will reach the next iteration of the loop, and
1677 wait for input after displaying the prompt.
1678 This time, just hit the @kbd{Enter} key.
1679 The value of @code{N} will be 0, and the program will terminate.
1680 The console window will disappear.
1685 @node The GNAT Compilation Model
1686 @chapter The GNAT Compilation Model
1687 @cindex GNAT compilation model
1688 @cindex Compilation model
1691 * Source Representation::
1692 * Foreign Language Representation::
1693 * File Naming Rules::
1694 * Using Other File Names::
1695 * Alternative File Naming Schemes::
1696 * Generating Object Files::
1697 * Source Dependencies::
1698 * The Ada Library Information Files::
1699 * Binding an Ada Program::
1700 * Mixed Language Programming::
1702 * Building Mixed Ada & C++ Programs::
1703 * Comparison between GNAT and C/C++ Compilation Models::
1705 * Comparison between GNAT and Conventional Ada Library Models::
1707 * Placement of temporary files::
1712 This chapter describes the compilation model used by GNAT. Although
1713 similar to that used by other languages, such as C and C++, this model
1714 is substantially different from the traditional Ada compilation models,
1715 which are based on a library. The model is initially described without
1716 reference to the library-based model. If you have not previously used an
1717 Ada compiler, you need only read the first part of this chapter. The
1718 last section describes and discusses the differences between the GNAT
1719 model and the traditional Ada compiler models. If you have used other
1720 Ada compilers, this section will help you to understand those
1721 differences, and the advantages of the GNAT model.
1723 @node Source Representation
1724 @section Source Representation
1728 Ada source programs are represented in standard text files, using
1729 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1730 7-bit ASCII set, plus additional characters used for
1731 representing foreign languages (@pxref{Foreign Language Representation}
1732 for support of non-USA character sets). The format effector characters
1733 are represented using their standard ASCII encodings, as follows:
1738 Vertical tab, @code{16#0B#}
1742 Horizontal tab, @code{16#09#}
1746 Carriage return, @code{16#0D#}
1750 Line feed, @code{16#0A#}
1754 Form feed, @code{16#0C#}
1758 Source files are in standard text file format. In addition, GNAT will
1759 recognize a wide variety of stream formats, in which the end of
1760 physical lines is marked by any of the following sequences:
1761 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1762 in accommodating files that are imported from other operating systems.
1764 @cindex End of source file
1765 @cindex Source file, end
1767 The end of a source file is normally represented by the physical end of
1768 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1769 recognized as signalling the end of the source file. Again, this is
1770 provided for compatibility with other operating systems where this
1771 code is used to represent the end of file.
1773 Each file contains a single Ada compilation unit, including any pragmas
1774 associated with the unit. For example, this means you must place a
1775 package declaration (a package @dfn{spec}) and the corresponding body in
1776 separate files. An Ada @dfn{compilation} (which is a sequence of
1777 compilation units) is represented using a sequence of files. Similarly,
1778 you will place each subunit or child unit in a separate file.
1780 @node Foreign Language Representation
1781 @section Foreign Language Representation
1784 GNAT supports the standard character sets defined in Ada as well as
1785 several other non-standard character sets for use in localized versions
1786 of the compiler (@pxref{Character Set Control}).
1789 * Other 8-Bit Codes::
1790 * Wide Character Encodings::
1798 The basic character set is Latin-1. This character set is defined by ISO
1799 standard 8859, part 1. The lower half (character codes @code{16#00#}
1800 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1801 is used to represent additional characters. These include extended letters
1802 used by European languages, such as French accents, the vowels with umlauts
1803 used in German, and the extra letter A-ring used in Swedish.
1805 @findex Ada.Characters.Latin_1
1806 For a complete list of Latin-1 codes and their encodings, see the source
1807 file of library unit @code{Ada.Characters.Latin_1} in file
1808 @file{a-chlat1.ads}.
1809 You may use any of these extended characters freely in character or
1810 string literals. In addition, the extended characters that represent
1811 letters can be used in identifiers.
1813 @node Other 8-Bit Codes
1814 @subsection Other 8-Bit Codes
1817 GNAT also supports several other 8-bit coding schemes:
1820 @item ISO 8859-2 (Latin-2)
1823 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1826 @item ISO 8859-3 (Latin-3)
1829 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1832 @item ISO 8859-4 (Latin-4)
1835 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1838 @item ISO 8859-5 (Cyrillic)
1841 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1842 lowercase equivalence.
1844 @item ISO 8859-15 (Latin-9)
1847 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1848 lowercase equivalence
1850 @item IBM PC (code page 437)
1851 @cindex code page 437
1852 This code page is the normal default for PCs in the U.S. It corresponds
1853 to the original IBM PC character set. This set has some, but not all, of
1854 the extended Latin-1 letters, but these letters do not have the same
1855 encoding as Latin-1. In this mode, these letters are allowed in
1856 identifiers with uppercase and lowercase equivalence.
1858 @item IBM PC (code page 850)
1859 @cindex code page 850
1860 This code page is a modification of 437 extended to include all the
1861 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1862 mode, all these letters are allowed in identifiers with uppercase and
1863 lowercase equivalence.
1865 @item Full Upper 8-bit
1866 Any character in the range 80-FF allowed in identifiers, and all are
1867 considered distinct. In other words, there are no uppercase and lowercase
1868 equivalences in this range. This is useful in conjunction with
1869 certain encoding schemes used for some foreign character sets (e.g.,
1870 the typical method of representing Chinese characters on the PC).
1873 No upper-half characters in the range 80-FF are allowed in identifiers.
1874 This gives Ada 83 compatibility for identifier names.
1878 For precise data on the encodings permitted, and the uppercase and lowercase
1879 equivalences that are recognized, see the file @file{csets.adb} in
1880 the GNAT compiler sources. You will need to obtain a full source release
1881 of GNAT to obtain this file.
1883 @node Wide Character Encodings
1884 @subsection Wide Character Encodings
1887 GNAT allows wide character codes to appear in character and string
1888 literals, and also optionally in identifiers, by means of the following
1889 possible encoding schemes:
1894 In this encoding, a wide character is represented by the following five
1902 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1903 characters (using uppercase letters) of the wide character code. For
1904 example, ESC A345 is used to represent the wide character with code
1906 This scheme is compatible with use of the full Wide_Character set.
1908 @item Upper-Half Coding
1909 @cindex Upper-Half Coding
1910 The wide character with encoding @code{16#abcd#} where the upper bit is on
1911 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1912 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1913 character, but is not required to be in the upper half. This method can
1914 be also used for shift-JIS or EUC, where the internal coding matches the
1917 @item Shift JIS Coding
1918 @cindex Shift JIS Coding
1919 A wide character is represented by a two-character sequence,
1921 @code{16#cd#}, with the restrictions described for upper-half encoding as
1922 described above. The internal character code is the corresponding JIS
1923 character according to the standard algorithm for Shift-JIS
1924 conversion. Only characters defined in the JIS code set table can be
1925 used with this encoding method.
1929 A wide character is represented by a two-character sequence
1931 @code{16#cd#}, with both characters being in the upper half. The internal
1932 character code is the corresponding JIS character according to the EUC
1933 encoding algorithm. Only characters defined in the JIS code set table
1934 can be used with this encoding method.
1937 A wide character is represented using
1938 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1939 10646-1/Am.2. Depending on the character value, the representation
1940 is a one, two, or three byte sequence:
1945 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1946 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1947 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1952 where the @var{xxx} bits correspond to the left-padded bits of the
1953 16-bit character value. Note that all lower half ASCII characters
1954 are represented as ASCII bytes and all upper half characters and
1955 other wide characters are represented as sequences of upper-half
1956 (The full UTF-8 scheme allows for encoding 31-bit characters as
1957 6-byte sequences, but in this implementation, all UTF-8 sequences
1958 of four or more bytes length will be treated as illegal).
1959 @item Brackets Coding
1960 In this encoding, a wide character is represented by the following eight
1968 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1969 characters (using uppercase letters) of the wide character code. For
1970 example, [``A345''] is used to represent the wide character with code
1971 @code{16#A345#}. It is also possible (though not required) to use the
1972 Brackets coding for upper half characters. For example, the code
1973 @code{16#A3#} can be represented as @code{[``A3'']}.
1975 This scheme is compatible with use of the full Wide_Character set,
1976 and is also the method used for wide character encoding in the standard
1977 ACVC (Ada Compiler Validation Capability) test suite distributions.
1982 Note: Some of these coding schemes do not permit the full use of the
1983 Ada character set. For example, neither Shift JIS, nor EUC allow the
1984 use of the upper half of the Latin-1 set.
1986 @node File Naming Rules
1987 @section File Naming Rules
1990 The default file name is determined by the name of the unit that the
1991 file contains. The name is formed by taking the full expanded name of
1992 the unit and replacing the separating dots with hyphens and using
1993 ^lowercase^uppercase^ for all letters.
1995 An exception arises if the file name generated by the above rules starts
1996 with one of the characters
1998 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2001 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2003 and the second character is a
2004 minus. In this case, the character ^tilde^dollar sign^ is used in place
2005 of the minus. The reason for this special rule is to avoid clashes with
2006 the standard names for child units of the packages System, Ada,
2007 Interfaces, and GNAT, which use the prefixes
2009 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2012 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2016 The file extension is @file{.ads} for a spec and
2017 @file{.adb} for a body. The following list shows some
2018 examples of these rules.
2025 @item arith_functions.ads
2026 Arith_Functions (package spec)
2027 @item arith_functions.adb
2028 Arith_Functions (package body)
2030 Func.Spec (child package spec)
2032 Func.Spec (child package body)
2034 Sub (subunit of Main)
2035 @item ^a~bad.adb^A$BAD.ADB^
2036 A.Bad (child package body)
2040 Following these rules can result in excessively long
2041 file names if corresponding
2042 unit names are long (for example, if child units or subunits are
2043 heavily nested). An option is available to shorten such long file names
2044 (called file name ``krunching''). This may be particularly useful when
2045 programs being developed with GNAT are to be used on operating systems
2046 with limited file name lengths. @xref{Using gnatkr}.
2048 Of course, no file shortening algorithm can guarantee uniqueness over
2049 all possible unit names; if file name krunching is used, it is your
2050 responsibility to ensure no name clashes occur. Alternatively you
2051 can specify the exact file names that you want used, as described
2052 in the next section. Finally, if your Ada programs are migrating from a
2053 compiler with a different naming convention, you can use the gnatchop
2054 utility to produce source files that follow the GNAT naming conventions.
2055 (For details @pxref{Renaming Files Using gnatchop}.)
2057 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2058 systems, case is not significant. So for example on @code{Windows XP}
2059 if the canonical name is @code{main-sub.adb}, you can use the file name
2060 @code{Main-Sub.adb} instead. However, case is significant for other
2061 operating systems, so for example, if you want to use other than
2062 canonically cased file names on a Unix system, you need to follow
2063 the procedures described in the next section.
2065 @node Using Other File Names
2066 @section Using Other File Names
2070 In the previous section, we have described the default rules used by
2071 GNAT to determine the file name in which a given unit resides. It is
2072 often convenient to follow these default rules, and if you follow them,
2073 the compiler knows without being explicitly told where to find all
2076 However, in some cases, particularly when a program is imported from
2077 another Ada compiler environment, it may be more convenient for the
2078 programmer to specify which file names contain which units. GNAT allows
2079 arbitrary file names to be used by means of the Source_File_Name pragma.
2080 The form of this pragma is as shown in the following examples:
2081 @cindex Source_File_Name pragma
2083 @smallexample @c ada
2085 pragma Source_File_Name (My_Utilities.Stacks,
2086 Spec_File_Name => "myutilst_a.ada");
2087 pragma Source_File_name (My_Utilities.Stacks,
2088 Body_File_Name => "myutilst.ada");
2093 As shown in this example, the first argument for the pragma is the unit
2094 name (in this example a child unit). The second argument has the form
2095 of a named association. The identifier
2096 indicates whether the file name is for a spec or a body;
2097 the file name itself is given by a string literal.
2099 The source file name pragma is a configuration pragma, which means that
2100 normally it will be placed in the @file{gnat.adc}
2101 file used to hold configuration
2102 pragmas that apply to a complete compilation environment.
2103 For more details on how the @file{gnat.adc} file is created and used
2104 see @ref{Handling of Configuration Pragmas}.
2105 @cindex @file{gnat.adc}
2108 GNAT allows completely arbitrary file names to be specified using the
2109 source file name pragma. However, if the file name specified has an
2110 extension other than @file{.ads} or @file{.adb} it is necessary to use
2111 a special syntax when compiling the file. The name in this case must be
2112 preceded by the special sequence @option{-x} followed by a space and the name
2113 of the language, here @code{ada}, as in:
2116 $ gcc -c -x ada peculiar_file_name.sim
2121 @command{gnatmake} handles non-standard file names in the usual manner (the
2122 non-standard file name for the main program is simply used as the
2123 argument to gnatmake). Note that if the extension is also non-standard,
2124 then it must be included in the @command{gnatmake} command, it may not
2127 @node Alternative File Naming Schemes
2128 @section Alternative File Naming Schemes
2129 @cindex File naming schemes, alternative
2132 In the previous section, we described the use of the @code{Source_File_Name}
2133 pragma to allow arbitrary names to be assigned to individual source files.
2134 However, this approach requires one pragma for each file, and especially in
2135 large systems can result in very long @file{gnat.adc} files, and also create
2136 a maintenance problem.
2138 GNAT also provides a facility for specifying systematic file naming schemes
2139 other than the standard default naming scheme previously described. An
2140 alternative scheme for naming is specified by the use of
2141 @code{Source_File_Name} pragmas having the following format:
2142 @cindex Source_File_Name pragma
2144 @smallexample @c ada
2145 pragma Source_File_Name (
2146 Spec_File_Name => FILE_NAME_PATTERN
2147 @r{[},Casing => CASING_SPEC@r{]}
2148 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2150 pragma Source_File_Name (
2151 Body_File_Name => FILE_NAME_PATTERN
2152 @r{[},Casing => CASING_SPEC@r{]}
2153 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2155 pragma Source_File_Name (
2156 Subunit_File_Name => FILE_NAME_PATTERN
2157 @r{[},Casing => CASING_SPEC@r{]}
2158 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2160 FILE_NAME_PATTERN ::= STRING_LITERAL
2161 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2165 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2166 It contains a single asterisk character, and the unit name is substituted
2167 systematically for this asterisk. The optional parameter
2168 @code{Casing} indicates
2169 whether the unit name is to be all upper-case letters, all lower-case letters,
2170 or mixed-case. If no
2171 @code{Casing} parameter is used, then the default is all
2172 ^lower-case^upper-case^.
2174 The optional @code{Dot_Replacement} string is used to replace any periods
2175 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2176 argument is used then separating dots appear unchanged in the resulting
2178 Although the above syntax indicates that the
2179 @code{Casing} argument must appear
2180 before the @code{Dot_Replacement} argument, but it
2181 is also permissible to write these arguments in the opposite order.
2183 As indicated, it is possible to specify different naming schemes for
2184 bodies, specs, and subunits. Quite often the rule for subunits is the
2185 same as the rule for bodies, in which case, there is no need to give
2186 a separate @code{Subunit_File_Name} rule, and in this case the
2187 @code{Body_File_name} rule is used for subunits as well.
2189 The separate rule for subunits can also be used to implement the rather
2190 unusual case of a compilation environment (e.g.@: a single directory) which
2191 contains a subunit and a child unit with the same unit name. Although
2192 both units cannot appear in the same partition, the Ada Reference Manual
2193 allows (but does not require) the possibility of the two units coexisting
2194 in the same environment.
2196 The file name translation works in the following steps:
2201 If there is a specific @code{Source_File_Name} pragma for the given unit,
2202 then this is always used, and any general pattern rules are ignored.
2205 If there is a pattern type @code{Source_File_Name} pragma that applies to
2206 the unit, then the resulting file name will be used if the file exists. If
2207 more than one pattern matches, the latest one will be tried first, and the
2208 first attempt resulting in a reference to a file that exists will be used.
2211 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2212 for which the corresponding file exists, then the standard GNAT default
2213 naming rules are used.
2218 As an example of the use of this mechanism, consider a commonly used scheme
2219 in which file names are all lower case, with separating periods copied
2220 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2221 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2224 @smallexample @c ada
2225 pragma Source_File_Name
2226 (Spec_File_Name => "*.1.ada");
2227 pragma Source_File_Name
2228 (Body_File_Name => "*.2.ada");
2232 The default GNAT scheme is actually implemented by providing the following
2233 default pragmas internally:
2235 @smallexample @c ada
2236 pragma Source_File_Name
2237 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2238 pragma Source_File_Name
2239 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2243 Our final example implements a scheme typically used with one of the
2244 Ada 83 compilers, where the separator character for subunits was ``__''
2245 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2246 by adding @file{.ADA}, and subunits by
2247 adding @file{.SEP}. All file names were
2248 upper case. Child units were not present of course since this was an
2249 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2250 the same double underscore separator for child units.
2252 @smallexample @c ada
2253 pragma Source_File_Name
2254 (Spec_File_Name => "*_.ADA",
2255 Dot_Replacement => "__",
2256 Casing = Uppercase);
2257 pragma Source_File_Name
2258 (Body_File_Name => "*.ADA",
2259 Dot_Replacement => "__",
2260 Casing = Uppercase);
2261 pragma Source_File_Name
2262 (Subunit_File_Name => "*.SEP",
2263 Dot_Replacement => "__",
2264 Casing = Uppercase);
2267 @node Generating Object Files
2268 @section Generating Object Files
2271 An Ada program consists of a set of source files, and the first step in
2272 compiling the program is to generate the corresponding object files.
2273 These are generated by compiling a subset of these source files.
2274 The files you need to compile are the following:
2278 If a package spec has no body, compile the package spec to produce the
2279 object file for the package.
2282 If a package has both a spec and a body, compile the body to produce the
2283 object file for the package. The source file for the package spec need
2284 not be compiled in this case because there is only one object file, which
2285 contains the code for both the spec and body of the package.
2288 For a subprogram, compile the subprogram body to produce the object file
2289 for the subprogram. The spec, if one is present, is as usual in a
2290 separate file, and need not be compiled.
2294 In the case of subunits, only compile the parent unit. A single object
2295 file is generated for the entire subunit tree, which includes all the
2299 Compile child units independently of their parent units
2300 (though, of course, the spec of all the ancestor unit must be present in order
2301 to compile a child unit).
2305 Compile generic units in the same manner as any other units. The object
2306 files in this case are small dummy files that contain at most the
2307 flag used for elaboration checking. This is because GNAT always handles generic
2308 instantiation by means of macro expansion. However, it is still necessary to
2309 compile generic units, for dependency checking and elaboration purposes.
2313 The preceding rules describe the set of files that must be compiled to
2314 generate the object files for a program. Each object file has the same
2315 name as the corresponding source file, except that the extension is
2318 You may wish to compile other files for the purpose of checking their
2319 syntactic and semantic correctness. For example, in the case where a
2320 package has a separate spec and body, you would not normally compile the
2321 spec. However, it is convenient in practice to compile the spec to make
2322 sure it is error-free before compiling clients of this spec, because such
2323 compilations will fail if there is an error in the spec.
2325 GNAT provides an option for compiling such files purely for the
2326 purposes of checking correctness; such compilations are not required as
2327 part of the process of building a program. To compile a file in this
2328 checking mode, use the @option{-gnatc} switch.
2330 @node Source Dependencies
2331 @section Source Dependencies
2334 A given object file clearly depends on the source file which is compiled
2335 to produce it. Here we are using @dfn{depends} in the sense of a typical
2336 @code{make} utility; in other words, an object file depends on a source
2337 file if changes to the source file require the object file to be
2339 In addition to this basic dependency, a given object may depend on
2340 additional source files as follows:
2344 If a file being compiled @code{with}'s a unit @var{X}, the object file
2345 depends on the file containing the spec of unit @var{X}. This includes
2346 files that are @code{with}'ed implicitly either because they are parents
2347 of @code{with}'ed child units or they are run-time units required by the
2348 language constructs used in a particular unit.
2351 If a file being compiled instantiates a library level generic unit, the
2352 object file depends on both the spec and body files for this generic
2356 If a file being compiled instantiates a generic unit defined within a
2357 package, the object file depends on the body file for the package as
2358 well as the spec file.
2362 @cindex @option{-gnatn} switch
2363 If a file being compiled contains a call to a subprogram for which
2364 pragma @code{Inline} applies and inlining is activated with the
2365 @option{-gnatn} switch, the object file depends on the file containing the
2366 body of this subprogram as well as on the file containing the spec. Note
2367 that for inlining to actually occur as a result of the use of this switch,
2368 it is necessary to compile in optimizing mode.
2370 @cindex @option{-gnatN} switch
2371 The use of @option{-gnatN} activates inlining optimization
2372 that is performed by the front end of the compiler. This inlining does
2373 not require that the code generation be optimized. Like @option{-gnatn},
2374 the use of this switch generates additional dependencies.
2376 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2377 to specify both options.
2379 When using a gcc-based back end (in practice this means using any version
2380 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2381 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2382 Historically front end inlining was more extensive than the gcc back end
2383 inlining, but that is no longer the case.
2386 If an object file @file{O} depends on the proper body of a subunit through
2387 inlining or instantiation, it depends on the parent unit of the subunit.
2388 This means that any modification of the parent unit or one of its subunits
2389 affects the compilation of @file{O}.
2392 The object file for a parent unit depends on all its subunit body files.
2395 The previous two rules meant that for purposes of computing dependencies and
2396 recompilation, a body and all its subunits are treated as an indivisible whole.
2399 These rules are applied transitively: if unit @code{A} @code{with}'s
2400 unit @code{B}, whose elaboration calls an inlined procedure in package
2401 @code{C}, the object file for unit @code{A} will depend on the body of
2402 @code{C}, in file @file{c.adb}.
2404 The set of dependent files described by these rules includes all the
2405 files on which the unit is semantically dependent, as dictated by the
2406 Ada language standard. However, it is a superset of what the
2407 standard describes, because it includes generic, inline, and subunit
2410 An object file must be recreated by recompiling the corresponding source
2411 file if any of the source files on which it depends are modified. For
2412 example, if the @code{make} utility is used to control compilation,
2413 the rule for an Ada object file must mention all the source files on
2414 which the object file depends, according to the above definition.
2415 The determination of the necessary
2416 recompilations is done automatically when one uses @command{gnatmake}.
2419 @node The Ada Library Information Files
2420 @section The Ada Library Information Files
2421 @cindex Ada Library Information files
2422 @cindex @file{ALI} files
2425 Each compilation actually generates two output files. The first of these
2426 is the normal object file that has a @file{.o} extension. The second is a
2427 text file containing full dependency information. It has the same
2428 name as the source file, but an @file{.ali} extension.
2429 This file is known as the Ada Library Information (@file{ALI}) file.
2430 The following information is contained in the @file{ALI} file.
2434 Version information (indicates which version of GNAT was used to compile
2435 the unit(s) in question)
2438 Main program information (including priority and time slice settings,
2439 as well as the wide character encoding used during compilation).
2442 List of arguments used in the @command{gcc} command for the compilation
2445 Attributes of the unit, including configuration pragmas used, an indication
2446 of whether the compilation was successful, exception model used etc.
2449 A list of relevant restrictions applying to the unit (used for consistency)
2453 Categorization information (e.g.@: use of pragma @code{Pure}).
2456 Information on all @code{with}'ed units, including presence of
2457 @code{Elaborate} or @code{Elaborate_All} pragmas.
2460 Information from any @code{Linker_Options} pragmas used in the unit
2463 Information on the use of @code{Body_Version} or @code{Version}
2464 attributes in the unit.
2467 Dependency information. This is a list of files, together with
2468 time stamp and checksum information. These are files on which
2469 the unit depends in the sense that recompilation is required
2470 if any of these units are modified.
2473 Cross-reference data. Contains information on all entities referenced
2474 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2475 provide cross-reference information.
2480 For a full detailed description of the format of the @file{ALI} file,
2481 see the source of the body of unit @code{Lib.Writ}, contained in file
2482 @file{lib-writ.adb} in the GNAT compiler sources.
2484 @node Binding an Ada Program
2485 @section Binding an Ada Program
2488 When using languages such as C and C++, once the source files have been
2489 compiled the only remaining step in building an executable program
2490 is linking the object modules together. This means that it is possible to
2491 link an inconsistent version of a program, in which two units have
2492 included different versions of the same header.
2494 The rules of Ada do not permit such an inconsistent program to be built.
2495 For example, if two clients have different versions of the same package,
2496 it is illegal to build a program containing these two clients.
2497 These rules are enforced by the GNAT binder, which also determines an
2498 elaboration order consistent with the Ada rules.
2500 The GNAT binder is run after all the object files for a program have
2501 been created. It is given the name of the main program unit, and from
2502 this it determines the set of units required by the program, by reading the
2503 corresponding ALI files. It generates error messages if the program is
2504 inconsistent or if no valid order of elaboration exists.
2506 If no errors are detected, the binder produces a main program, in Ada by
2507 default, that contains calls to the elaboration procedures of those
2508 compilation unit that require them, followed by
2509 a call to the main program. This Ada program is compiled to generate the
2510 object file for the main program. The name of
2511 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2512 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2515 Finally, the linker is used to build the resulting executable program,
2516 using the object from the main program from the bind step as well as the
2517 object files for the Ada units of the program.
2519 @node Mixed Language Programming
2520 @section Mixed Language Programming
2521 @cindex Mixed Language Programming
2524 This section describes how to develop a mixed-language program,
2525 specifically one that comprises units in both Ada and C.
2528 * Interfacing to C::
2529 * Calling Conventions::
2532 @node Interfacing to C
2533 @subsection Interfacing to C
2535 Interfacing Ada with a foreign language such as C involves using
2536 compiler directives to import and/or export entity definitions in each
2537 language---using @code{extern} statements in C, for instance, and the
2538 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2539 A full treatment of these topics is provided in Appendix B, section 1
2540 of the Ada Reference Manual.
2542 There are two ways to build a program using GNAT that contains some Ada
2543 sources and some foreign language sources, depending on whether or not
2544 the main subprogram is written in Ada. Here is a source example with
2545 the main subprogram in Ada:
2551 void print_num (int num)
2553 printf ("num is %d.\n", num);
2559 /* num_from_Ada is declared in my_main.adb */
2560 extern int num_from_Ada;
2564 return num_from_Ada;
2568 @smallexample @c ada
2570 procedure My_Main is
2572 -- Declare then export an Integer entity called num_from_Ada
2573 My_Num : Integer := 10;
2574 pragma Export (C, My_Num, "num_from_Ada");
2576 -- Declare an Ada function spec for Get_Num, then use
2577 -- C function get_num for the implementation.
2578 function Get_Num return Integer;
2579 pragma Import (C, Get_Num, "get_num");
2581 -- Declare an Ada procedure spec for Print_Num, then use
2582 -- C function print_num for the implementation.
2583 procedure Print_Num (Num : Integer);
2584 pragma Import (C, Print_Num, "print_num");
2587 Print_Num (Get_Num);
2593 To build this example, first compile the foreign language files to
2594 generate object files:
2596 ^gcc -c file1.c^gcc -c FILE1.C^
2597 ^gcc -c file2.c^gcc -c FILE2.C^
2601 Then, compile the Ada units to produce a set of object files and ALI
2604 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2608 Run the Ada binder on the Ada main program:
2610 gnatbind my_main.ali
2614 Link the Ada main program, the Ada objects and the other language
2617 gnatlink my_main.ali file1.o file2.o
2621 The last three steps can be grouped in a single command:
2623 gnatmake my_main.adb -largs file1.o file2.o
2626 @cindex Binder output file
2628 If the main program is in a language other than Ada, then you may have
2629 more than one entry point into the Ada subsystem. You must use a special
2630 binder option to generate callable routines that initialize and
2631 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2632 Calls to the initialization and finalization routines must be inserted
2633 in the main program, or some other appropriate point in the code. The
2634 call to initialize the Ada units must occur before the first Ada
2635 subprogram is called, and the call to finalize the Ada units must occur
2636 after the last Ada subprogram returns. The binder will place the
2637 initialization and finalization subprograms into the
2638 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2639 sources. To illustrate, we have the following example:
2643 extern void adainit (void);
2644 extern void adafinal (void);
2645 extern int add (int, int);
2646 extern int sub (int, int);
2648 int main (int argc, char *argv[])
2654 /* Should print "21 + 7 = 28" */
2655 printf ("%d + %d = %d\n", a, b, add (a, b));
2656 /* Should print "21 - 7 = 14" */
2657 printf ("%d - %d = %d\n", a, b, sub (a, b));
2663 @smallexample @c ada
2666 function Add (A, B : Integer) return Integer;
2667 pragma Export (C, Add, "add");
2671 package body Unit1 is
2672 function Add (A, B : Integer) return Integer is
2680 function Sub (A, B : Integer) return Integer;
2681 pragma Export (C, Sub, "sub");
2685 package body Unit2 is
2686 function Sub (A, B : Integer) return Integer is
2695 The build procedure for this application is similar to the last
2696 example's. First, compile the foreign language files to generate object
2699 ^gcc -c main.c^gcc -c main.c^
2703 Next, compile the Ada units to produce a set of object files and ALI
2706 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2707 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2711 Run the Ada binder on every generated ALI file. Make sure to use the
2712 @option{-n} option to specify a foreign main program:
2714 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2718 Link the Ada main program, the Ada objects and the foreign language
2719 objects. You need only list the last ALI file here:
2721 gnatlink unit2.ali main.o -o exec_file
2724 This procedure yields a binary executable called @file{exec_file}.
2728 Depending on the circumstances (for example when your non-Ada main object
2729 does not provide symbol @code{main}), you may also need to instruct the
2730 GNAT linker not to include the standard startup objects by passing the
2731 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2733 @node Calling Conventions
2734 @subsection Calling Conventions
2735 @cindex Foreign Languages
2736 @cindex Calling Conventions
2737 GNAT follows standard calling sequence conventions and will thus interface
2738 to any other language that also follows these conventions. The following
2739 Convention identifiers are recognized by GNAT:
2742 @cindex Interfacing to Ada
2743 @cindex Other Ada compilers
2744 @cindex Convention Ada
2746 This indicates that the standard Ada calling sequence will be
2747 used and all Ada data items may be passed without any limitations in the
2748 case where GNAT is used to generate both the caller and callee. It is also
2749 possible to mix GNAT generated code and code generated by another Ada
2750 compiler. In this case, the data types should be restricted to simple
2751 cases, including primitive types. Whether complex data types can be passed
2752 depends on the situation. Probably it is safe to pass simple arrays, such
2753 as arrays of integers or floats. Records may or may not work, depending
2754 on whether both compilers lay them out identically. Complex structures
2755 involving variant records, access parameters, tasks, or protected types,
2756 are unlikely to be able to be passed.
2758 Note that in the case of GNAT running
2759 on a platform that supports HP Ada 83, a higher degree of compatibility
2760 can be guaranteed, and in particular records are layed out in an identical
2761 manner in the two compilers. Note also that if output from two different
2762 compilers is mixed, the program is responsible for dealing with elaboration
2763 issues. Probably the safest approach is to write the main program in the
2764 version of Ada other than GNAT, so that it takes care of its own elaboration
2765 requirements, and then call the GNAT-generated adainit procedure to ensure
2766 elaboration of the GNAT components. Consult the documentation of the other
2767 Ada compiler for further details on elaboration.
2769 However, it is not possible to mix the tasking run time of GNAT and
2770 HP Ada 83, All the tasking operations must either be entirely within
2771 GNAT compiled sections of the program, or entirely within HP Ada 83
2772 compiled sections of the program.
2774 @cindex Interfacing to Assembly
2775 @cindex Convention Assembler
2777 Specifies assembler as the convention. In practice this has the
2778 same effect as convention Ada (but is not equivalent in the sense of being
2779 considered the same convention).
2781 @cindex Convention Asm
2784 Equivalent to Assembler.
2786 @cindex Interfacing to COBOL
2787 @cindex Convention COBOL
2790 Data will be passed according to the conventions described
2791 in section B.4 of the Ada Reference Manual.
2794 @cindex Interfacing to C
2795 @cindex Convention C
2797 Data will be passed according to the conventions described
2798 in section B.3 of the Ada Reference Manual.
2800 A note on interfacing to a C ``varargs'' function:
2801 @findex C varargs function
2802 @cindex Interfacing to C varargs function
2803 @cindex varargs function interfaces
2807 In C, @code{varargs} allows a function to take a variable number of
2808 arguments. There is no direct equivalent in this to Ada. One
2809 approach that can be used is to create a C wrapper for each
2810 different profile and then interface to this C wrapper. For
2811 example, to print an @code{int} value using @code{printf},
2812 create a C function @code{printfi} that takes two arguments, a
2813 pointer to a string and an int, and calls @code{printf}.
2814 Then in the Ada program, use pragma @code{Import} to
2815 interface to @code{printfi}.
2818 It may work on some platforms to directly interface to
2819 a @code{varargs} function by providing a specific Ada profile
2820 for a particular call. However, this does not work on
2821 all platforms, since there is no guarantee that the
2822 calling sequence for a two argument normal C function
2823 is the same as for calling a @code{varargs} C function with
2824 the same two arguments.
2827 @cindex Convention Default
2832 @cindex Convention External
2839 @cindex Interfacing to C++
2840 @cindex Convention C++
2841 @item C_Plus_Plus (or CPP)
2842 This stands for C++. For most purposes this is identical to C.
2843 See the separate description of the specialized GNAT pragmas relating to
2844 C++ interfacing for further details.
2848 @cindex Interfacing to Fortran
2849 @cindex Convention Fortran
2851 Data will be passed according to the conventions described
2852 in section B.5 of the Ada Reference Manual.
2855 This applies to an intrinsic operation, as defined in the Ada
2856 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2857 this means that the body of the subprogram is provided by the compiler itself,
2858 usually by means of an efficient code sequence, and that the user does not
2859 supply an explicit body for it. In an application program, the pragma may
2860 be applied to the following sets of names:
2864 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2865 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2866 two formal parameters. The
2867 first one must be a signed integer type or a modular type with a binary
2868 modulus, and the second parameter must be of type Natural.
2869 The return type must be the same as the type of the first argument. The size
2870 of this type can only be 8, 16, 32, or 64.
2873 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2874 The corresponding operator declaration must have parameters and result type
2875 that have the same root numeric type (for example, all three are long_float
2876 types). This simplifies the definition of operations that use type checking
2877 to perform dimensional checks:
2879 @smallexample @c ada
2880 type Distance is new Long_Float;
2881 type Time is new Long_Float;
2882 type Velocity is new Long_Float;
2883 function "/" (D : Distance; T : Time)
2885 pragma Import (Intrinsic, "/");
2889 This common idiom is often programmed with a generic definition and an
2890 explicit body. The pragma makes it simpler to introduce such declarations.
2891 It incurs no overhead in compilation time or code size, because it is
2892 implemented as a single machine instruction.
2895 General subprogram entities, to bind an Ada subprogram declaration to
2896 a compiler builtin by name with back-ends where such interfaces are
2897 available. A typical example is the set of ``__builtin'' functions
2898 exposed by the GCC back-end, as in the following example:
2900 @smallexample @c ada
2901 function builtin_sqrt (F : Float) return Float;
2902 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2905 Most of the GCC builtins are accessible this way, and as for other
2906 import conventions (e.g. C), it is the user's responsibility to ensure
2907 that the Ada subprogram profile matches the underlying builtin
2915 @cindex Convention Stdcall
2917 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2918 and specifies that the @code{Stdcall} calling sequence will be used,
2919 as defined by the NT API. Nevertheless, to ease building
2920 cross-platform bindings this convention will be handled as a @code{C} calling
2921 convention on non-Windows platforms.
2924 @cindex Convention DLL
2926 This is equivalent to @code{Stdcall}.
2929 @cindex Convention Win32
2931 This is equivalent to @code{Stdcall}.
2935 @cindex Convention Stubbed
2937 This is a special convention that indicates that the compiler
2938 should provide a stub body that raises @code{Program_Error}.
2942 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2943 that can be used to parametrize conventions and allow additional synonyms
2944 to be specified. For example if you have legacy code in which the convention
2945 identifier Fortran77 was used for Fortran, you can use the configuration
2948 @smallexample @c ada
2949 pragma Convention_Identifier (Fortran77, Fortran);
2953 And from now on the identifier Fortran77 may be used as a convention
2954 identifier (for example in an @code{Import} pragma) with the same
2958 @node Building Mixed Ada & C++ Programs
2959 @section Building Mixed Ada and C++ Programs
2962 A programmer inexperienced with mixed-language development may find that
2963 building an application containing both Ada and C++ code can be a
2964 challenge. This section gives a few
2965 hints that should make this task easier. The first section addresses
2966 the differences between interfacing with C and interfacing with C++.
2968 looks into the delicate problem of linking the complete application from
2969 its Ada and C++ parts. The last section gives some hints on how the GNAT
2970 run-time library can be adapted in order to allow inter-language dispatching
2971 with a new C++ compiler.
2974 * Interfacing to C++::
2975 * Linking a Mixed C++ & Ada Program::
2976 * A Simple Example::
2977 * Interfacing with C++ at the Class Level::
2980 @node Interfacing to C++
2981 @subsection Interfacing to C++
2984 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2985 generating code that is compatible with the G++ Application Binary
2986 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2989 Interfacing can be done at 3 levels: simple data, subprograms, and
2990 classes. In the first two cases, GNAT offers a specific @code{Convention
2991 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2992 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2993 not provide any help to solve the demangling problem. This problem can be
2994 addressed in two ways:
2997 by modifying the C++ code in order to force a C convention using
2998 the @code{extern "C"} syntax.
3001 by figuring out the mangled name and use it as the Link_Name argument of
3006 Interfacing at the class level can be achieved by using the GNAT specific
3007 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
3008 gnat_rm, GNAT Reference Manual}, for additional information.
3010 @node Linking a Mixed C++ & Ada Program
3011 @subsection Linking a Mixed C++ & Ada Program
3014 Usually the linker of the C++ development system must be used to link
3015 mixed applications because most C++ systems will resolve elaboration
3016 issues (such as calling constructors on global class instances)
3017 transparently during the link phase. GNAT has been adapted to ease the
3018 use of a foreign linker for the last phase. Three cases can be
3023 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3024 The C++ linker can simply be called by using the C++ specific driver
3025 called @code{c++}. Note that this setup is not very common because it
3026 may involve recompiling the whole GCC tree from sources, which makes it
3027 harder to upgrade the compilation system for one language without
3028 destabilizing the other.
3033 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3037 Using GNAT and G++ from two different GCC installations: If both
3038 compilers are on the @env{PATH}, the previous method may be used. It is
3039 important to note that environment variables such as
3040 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3041 @env{GCC_ROOT} will affect both compilers
3042 at the same time and may make one of the two compilers operate
3043 improperly if set during invocation of the wrong compiler. It is also
3044 very important that the linker uses the proper @file{libgcc.a} GCC
3045 library -- that is, the one from the C++ compiler installation. The
3046 implicit link command as suggested in the @command{gnatmake} command
3047 from the former example can be replaced by an explicit link command with
3048 the full-verbosity option in order to verify which library is used:
3051 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3053 If there is a problem due to interfering environment variables, it can
3054 be worked around by using an intermediate script. The following example
3055 shows the proper script to use when GNAT has not been installed at its
3056 default location and g++ has been installed at its default location:
3064 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3068 Using a non-GNU C++ compiler: The commands previously described can be
3069 used to insure that the C++ linker is used. Nonetheless, you need to add
3070 a few more parameters to the link command line, depending on the exception
3073 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3074 to the libgcc libraries are required:
3079 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3080 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3083 Where CC is the name of the non-GNU C++ compiler.
3085 If the @code{zero cost} exception mechanism is used, and the platform
3086 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3087 paths to more objects are required:
3092 CC `gcc -print-file-name=crtbegin.o` $* \
3093 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3094 `gcc -print-file-name=crtend.o`
3095 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3098 If the @code{zero cost} exception mechanism is used, and the platform
3099 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3100 Tru64 or AIX), the simple approach described above will not work and
3101 a pre-linking phase using GNAT will be necessary.
3105 @node A Simple Example
3106 @subsection A Simple Example
3108 The following example, provided as part of the GNAT examples, shows how
3109 to achieve procedural interfacing between Ada and C++ in both
3110 directions. The C++ class A has two methods. The first method is exported
3111 to Ada by the means of an extern C wrapper function. The second method
3112 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3113 a limited record with a layout comparable to the C++ class. The Ada
3114 subprogram, in turn, calls the C++ method. So, starting from the C++
3115 main program, the process passes back and forth between the two
3119 Here are the compilation commands:
3121 $ gnatmake -c simple_cpp_interface
3124 $ gnatbind -n simple_cpp_interface
3125 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3126 -lstdc++ ex7.o cpp_main.o
3130 Here are the corresponding sources:
3138 void adainit (void);
3139 void adafinal (void);
3140 void method1 (A *t);
3162 class A : public Origin @{
3164 void method1 (void);
3165 void method2 (int v);
3175 extern "C" @{ void ada_method2 (A *t, int v);@}
3177 void A::method1 (void)
3180 printf ("in A::method1, a_value = %d \n",a_value);
3184 void A::method2 (int v)
3186 ada_method2 (this, v);
3187 printf ("in A::method2, a_value = %d \n",a_value);
3194 printf ("in A::A, a_value = %d \n",a_value);
3198 @smallexample @c ada
3200 package body Simple_Cpp_Interface is
3202 procedure Ada_Method2 (This : in out A; V : Integer) is
3208 end Simple_Cpp_Interface;
3211 package Simple_Cpp_Interface is
3214 Vptr : System.Address;
3218 pragma Convention (C, A);
3220 procedure Method1 (This : in out A);
3221 pragma Import (C, Method1);
3223 procedure Ada_Method2 (This : in out A; V : Integer);
3224 pragma Export (C, Ada_Method2);
3226 end Simple_Cpp_Interface;
3229 @node Interfacing with C++ at the Class Level
3230 @subsection Interfacing with C++ at the Class Level
3232 In this section we demonstrate the GNAT features for interfacing with
3233 C++ by means of an example making use of Ada 2005 abstract interface
3234 types. This example consists of a classification of animals; classes
3235 have been used to model our main classification of animals, and
3236 interfaces provide support for the management of secondary
3237 classifications. We first demonstrate a case in which the types and
3238 constructors are defined on the C++ side and imported from the Ada
3239 side, and latter the reverse case.
3241 The root of our derivation will be the @code{Animal} class, with a
3242 single private attribute (the @code{Age} of the animal) and two public
3243 primitives to set and get the value of this attribute.
3248 @b{virtual} void Set_Age (int New_Age);
3249 @b{virtual} int Age ();
3255 Abstract interface types are defined in C++ by means of classes with pure
3256 virtual functions and no data members. In our example we will use two
3257 interfaces that provide support for the common management of @code{Carnivore}
3258 and @code{Domestic} animals:
3261 @b{class} Carnivore @{
3263 @b{virtual} int Number_Of_Teeth () = 0;
3266 @b{class} Domestic @{
3268 @b{virtual void} Set_Owner (char* Name) = 0;
3272 Using these declarations, we can now say that a @code{Dog} is an animal that is
3273 both Carnivore and Domestic, that is:
3276 @b{class} Dog : Animal, Carnivore, Domestic @{
3278 @b{virtual} int Number_Of_Teeth ();
3279 @b{virtual} void Set_Owner (char* Name);
3281 Dog(); // Constructor
3288 In the following examples we will assume that the previous declarations are
3289 located in a file named @code{animals.h}. The following package demonstrates
3290 how to import these C++ declarations from the Ada side:
3292 @smallexample @c ada
3293 with Interfaces.C.Strings; use Interfaces.C.Strings;
3295 type Carnivore is interface;
3296 pragma Convention (C_Plus_Plus, Carnivore);
3297 function Number_Of_Teeth (X : Carnivore)
3298 return Natural is abstract;
3300 type Domestic is interface;
3301 pragma Convention (C_Plus_Plus, Set_Owner);
3303 (X : in out Domestic;
3304 Name : Chars_Ptr) is abstract;
3306 type Animal is tagged record
3309 pragma Import (C_Plus_Plus, Animal);
3311 procedure Set_Age (X : in out Animal; Age : Integer);
3312 pragma Import (C_Plus_Plus, Set_Age);
3314 function Age (X : Animal) return Integer;
3315 pragma Import (C_Plus_Plus, Age);
3317 type Dog is new Animal and Carnivore and Domestic with record
3318 Tooth_Count : Natural;
3319 Owner : String (1 .. 30);
3321 pragma Import (C_Plus_Plus, Dog);
3323 function Number_Of_Teeth (A : Dog) return Integer;
3324 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3326 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3327 pragma Import (C_Plus_Plus, Set_Owner);
3329 function New_Dog return Dog'Class;
3330 pragma CPP_Constructor (New_Dog);
3331 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3335 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3336 interfacing with these C++ classes is easy. The only requirement is that all
3337 the primitives and components must be declared exactly in the same order in
3340 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3341 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3342 the arguments to the called primitives will be the same as for C++. For the
3343 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3344 to indicate that they have been defined on the C++ side; this is required
3345 because the dispatch table associated with these tagged types will be built
3346 in the C++ side and therefore will not contain the predefined Ada primitives
3347 which Ada would otherwise expect.
3349 As the reader can see there is no need to indicate the C++ mangled names
3350 associated with each subprogram because it is assumed that all the calls to
3351 these primitives will be dispatching calls. The only exception is the
3352 constructor, which must be registered with the compiler by means of
3353 @code{pragma CPP_Constructor} and needs to provide its associated C++
3354 mangled name because the Ada compiler generates direct calls to it.
3356 With the above packages we can now declare objects of type Dog on the Ada side
3357 and dispatch calls to the corresponding subprograms on the C++ side. We can
3358 also extend the tagged type Dog with further fields and primitives, and
3359 override some of its C++ primitives on the Ada side. For example, here we have
3360 a type derivation defined on the Ada side that inherits all the dispatching
3361 primitives of the ancestor from the C++ side.
3364 @b{with} Animals; @b{use} Animals;
3365 @b{package} Vaccinated_Animals @b{is}
3366 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3367 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3368 @b{end} Vaccinated_Animals;
3371 It is important to note that, because of the ABI compatibility, the programmer
3372 does not need to add any further information to indicate either the object
3373 layout or the dispatch table entry associated with each dispatching operation.
3375 Now let us define all the types and constructors on the Ada side and export
3376 them to C++, using the same hierarchy of our previous example:
3378 @smallexample @c ada
3379 with Interfaces.C.Strings;
3380 use Interfaces.C.Strings;
3382 type Carnivore is interface;
3383 pragma Convention (C_Plus_Plus, Carnivore);
3384 function Number_Of_Teeth (X : Carnivore)
3385 return Natural is abstract;
3387 type Domestic is interface;
3388 pragma Convention (C_Plus_Plus, Set_Owner);
3390 (X : in out Domestic;
3391 Name : Chars_Ptr) is abstract;
3393 type Animal is tagged record
3396 pragma Convention (C_Plus_Plus, Animal);
3398 procedure Set_Age (X : in out Animal; Age : Integer);
3399 pragma Export (C_Plus_Plus, Set_Age);
3401 function Age (X : Animal) return Integer;
3402 pragma Export (C_Plus_Plus, Age);
3404 type Dog is new Animal and Carnivore and Domestic with record
3405 Tooth_Count : Natural;
3406 Owner : String (1 .. 30);
3408 pragma Convention (C_Plus_Plus, Dog);
3410 function Number_Of_Teeth (A : Dog) return Integer;
3411 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3413 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3414 pragma Export (C_Plus_Plus, Set_Owner);
3416 function New_Dog return Dog'Class;
3417 pragma Export (C_Plus_Plus, New_Dog);
3421 Compared with our previous example the only difference is the use of
3422 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3423 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3424 nothing else to be done; as explained above, the only requirement is that all
3425 the primitives and components are declared in exactly the same order.
3427 For completeness, let us see a brief C++ main program that uses the
3428 declarations available in @code{animals.h} (presented in our first example) to
3429 import and use the declarations from the Ada side, properly initializing and
3430 finalizing the Ada run-time system along the way:
3433 @b{#include} "animals.h"
3434 @b{#include} <iostream>
3435 @b{using namespace} std;
3437 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3438 void Check_Domestic (Domestic *obj) @{@dots{}@}
3439 void Check_Animal (Animal *obj) @{@dots{}@}
3440 void Check_Dog (Dog *obj) @{@dots{}@}
3443 void adainit (void);
3444 void adafinal (void);
3450 Dog *obj = new_dog(); // Ada constructor
3451 Check_Carnivore (obj); // Check secondary DT
3452 Check_Domestic (obj); // Check secondary DT
3453 Check_Animal (obj); // Check primary DT
3454 Check_Dog (obj); // Check primary DT
3459 adainit (); test(); adafinal ();
3464 @node Comparison between GNAT and C/C++ Compilation Models
3465 @section Comparison between GNAT and C/C++ Compilation Models
3468 The GNAT model of compilation is close to the C and C++ models. You can
3469 think of Ada specs as corresponding to header files in C. As in C, you
3470 don't need to compile specs; they are compiled when they are used. The
3471 Ada @code{with} is similar in effect to the @code{#include} of a C
3474 One notable difference is that, in Ada, you may compile specs separately
3475 to check them for semantic and syntactic accuracy. This is not always
3476 possible with C headers because they are fragments of programs that have
3477 less specific syntactic or semantic rules.
3479 The other major difference is the requirement for running the binder,
3480 which performs two important functions. First, it checks for
3481 consistency. In C or C++, the only defense against assembling
3482 inconsistent programs lies outside the compiler, in a makefile, for
3483 example. The binder satisfies the Ada requirement that it be impossible
3484 to construct an inconsistent program when the compiler is used in normal
3487 @cindex Elaboration order control
3488 The other important function of the binder is to deal with elaboration
3489 issues. There are also elaboration issues in C++ that are handled
3490 automatically. This automatic handling has the advantage of being
3491 simpler to use, but the C++ programmer has no control over elaboration.
3492 Where @code{gnatbind} might complain there was no valid order of
3493 elaboration, a C++ compiler would simply construct a program that
3494 malfunctioned at run time.
3497 @node Comparison between GNAT and Conventional Ada Library Models
3498 @section Comparison between GNAT and Conventional Ada Library Models
3501 This section is intended for Ada programmers who have
3502 used an Ada compiler implementing the traditional Ada library
3503 model, as described in the Ada Reference Manual.
3505 @cindex GNAT library
3506 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3507 source files themselves acts as the library. Compiling Ada programs does
3508 not generate any centralized information, but rather an object file and
3509 a ALI file, which are of interest only to the binder and linker.
3510 In a traditional system, the compiler reads information not only from
3511 the source file being compiled, but also from the centralized library.
3512 This means that the effect of a compilation depends on what has been
3513 previously compiled. In particular:
3517 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3518 to the version of the unit most recently compiled into the library.
3521 Inlining is effective only if the necessary body has already been
3522 compiled into the library.
3525 Compiling a unit may obsolete other units in the library.
3529 In GNAT, compiling one unit never affects the compilation of any other
3530 units because the compiler reads only source files. Only changes to source
3531 files can affect the results of a compilation. In particular:
3535 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3536 to the source version of the unit that is currently accessible to the
3541 Inlining requires the appropriate source files for the package or
3542 subprogram bodies to be available to the compiler. Inlining is always
3543 effective, independent of the order in which units are complied.
3546 Compiling a unit never affects any other compilations. The editing of
3547 sources may cause previous compilations to be out of date if they
3548 depended on the source file being modified.
3552 The most important result of these differences is that order of compilation
3553 is never significant in GNAT. There is no situation in which one is
3554 required to do one compilation before another. What shows up as order of
3555 compilation requirements in the traditional Ada library becomes, in
3556 GNAT, simple source dependencies; in other words, there is only a set
3557 of rules saying what source files must be present when a file is
3561 @node Placement of temporary files
3562 @section Placement of temporary files
3563 @cindex Temporary files (user control over placement)
3566 GNAT creates temporary files in the directory designated by the environment
3567 variable @env{TMPDIR}.
3568 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3569 for detailed information on how environment variables are resolved.
3570 For most users the easiest way to make use of this feature is to simply
3571 define @env{TMPDIR} as a job level logical name).
3572 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3573 for compiler temporary files, then you can include something like the
3574 following command in your @file{LOGIN.COM} file:
3577 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3581 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3582 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3583 designated by @env{TEMP}.
3584 If none of these environment variables are defined then GNAT uses the
3585 directory designated by the logical name @code{SYS$SCRATCH:}
3586 (by default the user's home directory). If all else fails
3587 GNAT uses the current directory for temporary files.
3590 @c *************************
3591 @node Compiling Using gcc
3592 @chapter Compiling Using @command{gcc}
3595 This chapter discusses how to compile Ada programs using the @command{gcc}
3596 command. It also describes the set of switches
3597 that can be used to control the behavior of the compiler.
3599 * Compiling Programs::
3600 * Switches for gcc::
3601 * Search Paths and the Run-Time Library (RTL)::
3602 * Order of Compilation Issues::
3606 @node Compiling Programs
3607 @section Compiling Programs
3610 The first step in creating an executable program is to compile the units
3611 of the program using the @command{gcc} command. You must compile the
3616 the body file (@file{.adb}) for a library level subprogram or generic
3620 the spec file (@file{.ads}) for a library level package or generic
3621 package that has no body
3624 the body file (@file{.adb}) for a library level package
3625 or generic package that has a body
3630 You need @emph{not} compile the following files
3635 the spec of a library unit which has a body
3642 because they are compiled as part of compiling related units. GNAT
3644 when the corresponding body is compiled, and subunits when the parent is
3647 @cindex cannot generate code
3648 If you attempt to compile any of these files, you will get one of the
3649 following error messages (where @var{fff} is the name of the file you compiled):
3652 cannot generate code for file @var{fff} (package spec)
3653 to check package spec, use -gnatc
3655 cannot generate code for file @var{fff} (missing subunits)
3656 to check parent unit, use -gnatc
3658 cannot generate code for file @var{fff} (subprogram spec)
3659 to check subprogram spec, use -gnatc
3661 cannot generate code for file @var{fff} (subunit)
3662 to check subunit, use -gnatc
3666 As indicated by the above error messages, if you want to submit
3667 one of these files to the compiler to check for correct semantics
3668 without generating code, then use the @option{-gnatc} switch.
3670 The basic command for compiling a file containing an Ada unit is
3673 $ gcc -c @ovar{switches} @file{file name}
3677 where @var{file name} is the name of the Ada file (usually
3679 @file{.ads} for a spec or @file{.adb} for a body).
3682 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3684 The result of a successful compilation is an object file, which has the
3685 same name as the source file but an extension of @file{.o} and an Ada
3686 Library Information (ALI) file, which also has the same name as the
3687 source file, but with @file{.ali} as the extension. GNAT creates these
3688 two output files in the current directory, but you may specify a source
3689 file in any directory using an absolute or relative path specification
3690 containing the directory information.
3693 @command{gcc} is actually a driver program that looks at the extensions of
3694 the file arguments and loads the appropriate compiler. For example, the
3695 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3696 These programs are in directories known to the driver program (in some
3697 configurations via environment variables you set), but need not be in
3698 your path. The @command{gcc} driver also calls the assembler and any other
3699 utilities needed to complete the generation of the required object
3702 It is possible to supply several file names on the same @command{gcc}
3703 command. This causes @command{gcc} to call the appropriate compiler for
3704 each file. For example, the following command lists three separate
3705 files to be compiled:
3708 $ gcc -c x.adb y.adb z.c
3712 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3713 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3714 The compiler generates three object files @file{x.o}, @file{y.o} and
3715 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3716 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3719 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3722 @node Switches for gcc
3723 @section Switches for @command{gcc}
3726 The @command{gcc} command accepts switches that control the
3727 compilation process. These switches are fully described in this section.
3728 First we briefly list all the switches, in alphabetical order, then we
3729 describe the switches in more detail in functionally grouped sections.
3731 More switches exist for GCC than those documented here, especially
3732 for specific targets. However, their use is not recommended as
3733 they may change code generation in ways that are incompatible with
3734 the Ada run-time library, or can cause inconsistencies between
3738 * Output and Error Message Control::
3739 * Warning Message Control::
3740 * Debugging and Assertion Control::
3741 * Validity Checking::
3744 * Using gcc for Syntax Checking::
3745 * Using gcc for Semantic Checking::
3746 * Compiling Different Versions of Ada::
3747 * Character Set Control::
3748 * File Naming Control::
3749 * Subprogram Inlining Control::
3750 * Auxiliary Output Control::
3751 * Debugging Control::
3752 * Exception Handling Control::
3753 * Units to Sources Mapping Files::
3754 * Integrated Preprocessing::
3755 * Code Generation Control::
3764 @cindex @option{-b} (@command{gcc})
3765 @item -b @var{target}
3766 Compile your program to run on @var{target}, which is the name of a
3767 system configuration. You must have a GNAT cross-compiler built if
3768 @var{target} is not the same as your host system.
3771 @cindex @option{-B} (@command{gcc})
3772 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3773 from @var{dir} instead of the default location. Only use this switch
3774 when multiple versions of the GNAT compiler are available.
3775 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3776 GNU Compiler Collection (GCC)}, for further details. You would normally
3777 use the @option{-b} or @option{-V} switch instead.
3780 @cindex @option{-c} (@command{gcc})
3781 Compile. Always use this switch when compiling Ada programs.
3783 Note: for some other languages when using @command{gcc}, notably in
3784 the case of C and C++, it is possible to use
3785 use @command{gcc} without a @option{-c} switch to
3786 compile and link in one step. In the case of GNAT, you
3787 cannot use this approach, because the binder must be run
3788 and @command{gcc} cannot be used to run the GNAT binder.
3792 @cindex @option{-fno-inline} (@command{gcc})
3793 Suppresses all back-end inlining, even if other optimization or inlining
3795 This includes suppression of inlining that results
3796 from the use of the pragma @code{Inline_Always}.
3797 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3798 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3799 effect if this switch is present.
3801 @item -fno-inline-functions
3802 @cindex @option{-fno-inline-functions} (@command{gcc})
3803 Suppresses automatic inlining of small subprograms, which is enabled
3804 if @option{-O3} is used.
3806 @item -fno-inline-functions-called-once
3807 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3808 Suppresses inlining of subprograms local to the unit and called once
3809 from within it, which is enabled if @option{-O1} is used.
3811 @item -fno-strict-aliasing
3812 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3813 Causes the compiler to avoid assumptions regarding non-aliasing
3814 of objects of different types. See
3815 @ref{Optimization and Strict Aliasing} for details.
3818 @cindex @option{-fstack-check} (@command{gcc})
3819 Activates stack checking.
3820 See @ref{Stack Overflow Checking} for details.
3823 @cindex @option{-fstack-usage} (@command{gcc})
3824 Makes the compiler output stack usage information for the program, on a
3825 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3827 @item -fcallgraph-info@r{[}=su@r{]}
3828 @cindex @option{-fcallgraph-info} (@command{gcc})
3829 Makes the compiler output callgraph information for the program, on a
3830 per-file basis. The information is generated in the VCG format. It can
3831 be decorated with stack-usage per-node information.
3834 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3835 Generate debugging information. This information is stored in the object
3836 file and copied from there to the final executable file by the linker,
3837 where it can be read by the debugger. You must use the
3838 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3841 @cindex @option{-gnat83} (@command{gcc})
3842 Enforce Ada 83 restrictions.
3845 @cindex @option{-gnat95} (@command{gcc})
3846 Enforce Ada 95 restrictions.
3849 @cindex @option{-gnat05} (@command{gcc})
3850 Allow full Ada 2005 features.
3853 @cindex @option{-gnata} (@command{gcc})
3854 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3855 activated. Note that these pragmas can also be controlled using the
3856 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3857 It also activates pragmas @code{Check}, @code{Precondition}, and
3858 @code{Postcondition}. Note that these pragmas can also be controlled
3859 using the configuration pragma @code{Check_Policy}.
3862 @cindex @option{-gnatA} (@command{gcc})
3863 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3867 @cindex @option{-gnatb} (@command{gcc})
3868 Generate brief messages to @file{stderr} even if verbose mode set.
3871 @cindex @option{-gnatB} (@command{gcc})
3872 Assume no invalid (bad) values except for 'Valid attribute use.
3875 @cindex @option{-gnatc} (@command{gcc})
3876 Check syntax and semantics only (no code generation attempted).
3879 @cindex @option{-gnatd} (@command{gcc})
3880 Specify debug options for the compiler. The string of characters after
3881 the @option{-gnatd} specify the specific debug options. The possible
3882 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3883 compiler source file @file{debug.adb} for details of the implemented
3884 debug options. Certain debug options are relevant to applications
3885 programmers, and these are documented at appropriate points in this
3889 @cindex @option{-gnatD[nn]} (@command{gcc})
3890 Create expanded source files for source level debugging. This switch
3891 also suppress generation of cross-reference information
3892 (see @option{-gnatx}).
3894 @item -gnatec=@var{path}
3895 @cindex @option{-gnatec} (@command{gcc})
3896 Specify a configuration pragma file
3898 (the equal sign is optional)
3900 (@pxref{The Configuration Pragmas Files}).
3902 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3903 @cindex @option{-gnateD} (@command{gcc})
3904 Defines a symbol, associated with @var{value}, for preprocessing.
3905 (@pxref{Integrated Preprocessing}).
3908 @cindex @option{-gnatef} (@command{gcc})
3909 Display full source path name in brief error messages.
3912 @cindex @option{-gnateG} (@command{gcc})
3913 Save result of preprocessing in a text file.
3915 @item -gnatem=@var{path}
3916 @cindex @option{-gnatem} (@command{gcc})
3917 Specify a mapping file
3919 (the equal sign is optional)
3921 (@pxref{Units to Sources Mapping Files}).
3923 @item -gnatep=@var{file}
3924 @cindex @option{-gnatep} (@command{gcc})
3925 Specify a preprocessing data file
3927 (the equal sign is optional)
3929 (@pxref{Integrated Preprocessing}).
3932 @cindex @option{-gnatE} (@command{gcc})
3933 Full dynamic elaboration checks.
3936 @cindex @option{-gnatf} (@command{gcc})
3937 Full errors. Multiple errors per line, all undefined references, do not
3938 attempt to suppress cascaded errors.
3941 @cindex @option{-gnatF} (@command{gcc})
3942 Externals names are folded to all uppercase.
3944 @item ^-gnatg^/GNAT_INTERNAL^
3945 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3946 Internal GNAT implementation mode. This should not be used for
3947 applications programs, it is intended only for use by the compiler
3948 and its run-time library. For documentation, see the GNAT sources.
3949 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3950 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3951 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3952 so that all standard warnings and all standard style options are turned on.
3953 All warnings and style error messages are treated as errors.
3956 @cindex @option{-gnatG[nn]} (@command{gcc})
3957 List generated expanded code in source form.
3959 @item ^-gnath^/HELP^
3960 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3961 Output usage information. The output is written to @file{stdout}.
3963 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3964 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3965 Identifier character set
3967 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3969 For details of the possible selections for @var{c},
3970 see @ref{Character Set Control}.
3972 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3973 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3974 Ignore representation clauses. When this switch is used, all
3975 representation clauses are treated as comments. This is useful
3976 when initially porting code where you want to ignore rep clause
3977 problems, and also for compiling foreign code (particularly
3981 @cindex @option{-gnatjnn} (@command{gcc})
3982 Reformat error messages to fit on nn character lines
3984 @item -gnatk=@var{n}
3985 @cindex @option{-gnatk} (@command{gcc})
3986 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3989 @cindex @option{-gnatl} (@command{gcc})
3990 Output full source listing with embedded error messages.
3993 @cindex @option{-gnatL} (@command{gcc})
3994 Used in conjunction with -gnatG or -gnatD to intersperse original
3995 source lines (as comment lines with line numbers) in the expanded
3998 @item -gnatm=@var{n}
3999 @cindex @option{-gnatm} (@command{gcc})
4000 Limit number of detected error or warning messages to @var{n}
4001 where @var{n} is in the range 1..999_999. The default setting if
4002 no switch is given is 9999. Compilation is terminated if this
4003 limit is exceeded. The equal sign here is optional.
4006 @cindex @option{-gnatn} (@command{gcc})
4007 Activate inlining for subprograms for which
4008 pragma @code{inline} is specified. This inlining is performed
4009 by the GCC back-end.
4012 @cindex @option{-gnatN} (@command{gcc})
4013 Activate front end inlining for subprograms for which
4014 pragma @code{Inline} is specified. This inlining is performed
4015 by the front end and will be visible in the
4016 @option{-gnatG} output.
4017 In some cases, this has proved more effective than the back end
4018 inlining resulting from the use of
4021 @option{-gnatN} automatically implies
4022 @option{-gnatn} so it is not necessary
4023 to specify both options. There are a few cases that the back-end inlining
4024 catches that cannot be dealt with in the front-end.
4027 @cindex @option{-gnato} (@command{gcc})
4028 Enable numeric overflow checking (which is not normally enabled by
4029 default). Note that division by zero is a separate check that is not
4030 controlled by this switch (division by zero checking is on by default).
4033 @cindex @option{-gnatp} (@command{gcc})
4034 Suppress all checks. See @ref{Run-Time Checks} for details.
4037 @cindex @option{-gnatP} (@command{gcc})
4038 Enable polling. This is required on some systems (notably Windows NT) to
4039 obtain asynchronous abort and asynchronous transfer of control capability.
4040 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4044 @cindex @option{-gnatq} (@command{gcc})
4045 Don't quit. Try semantics, even if parse errors.
4048 @cindex @option{-gnatQ} (@command{gcc})
4049 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4052 @cindex @option{-gnatr} (@command{gcc})
4053 Treat pragma Restrictions as Restriction_Warnings.
4055 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4056 @cindex @option{-gnatR} (@command{gcc})
4057 Output representation information for declared types and objects.
4060 @cindex @option{-gnats} (@command{gcc})
4064 @cindex @option{-gnatS} (@command{gcc})
4065 Print package Standard.
4068 @cindex @option{-gnatt} (@command{gcc})
4069 Generate tree output file.
4071 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4072 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4073 All compiler tables start at @var{nnn} times usual starting size.
4076 @cindex @option{-gnatu} (@command{gcc})
4077 List units for this compilation.
4080 @cindex @option{-gnatU} (@command{gcc})
4081 Tag all error messages with the unique string ``error:''
4084 @cindex @option{-gnatv} (@command{gcc})
4085 Verbose mode. Full error output with source lines to @file{stdout}.
4088 @cindex @option{-gnatV} (@command{gcc})
4089 Control level of validity checking. See separate section describing
4092 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4093 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4095 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4096 the exact warnings that
4097 are enabled or disabled (@pxref{Warning Message Control}).
4099 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4100 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4101 Wide character encoding method
4103 (@var{e}=n/h/u/s/e/8).
4106 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4110 @cindex @option{-gnatx} (@command{gcc})
4111 Suppress generation of cross-reference information.
4113 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4114 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4115 Enable built-in style checks (@pxref{Style Checking}).
4117 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4118 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4119 Distribution stub generation and compilation
4121 (@var{m}=r/c for receiver/caller stubs).
4124 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4125 to be generated and compiled).
4128 @item ^-I^/SEARCH=^@var{dir}
4129 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4131 Direct GNAT to search the @var{dir} directory for source files needed by
4132 the current compilation
4133 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4135 @item ^-I-^/NOCURRENT_DIRECTORY^
4136 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4138 Except for the source file named in the command line, do not look for source
4139 files in the directory containing the source file named in the command line
4140 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4144 @cindex @option{-mbig-switch} (@command{gcc})
4145 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4146 This standard gcc switch causes the compiler to use larger offsets in its
4147 jump table representation for @code{case} statements.
4148 This may result in less efficient code, but is sometimes necessary
4149 (for example on HP-UX targets)
4150 @cindex HP-UX and @option{-mbig-switch} option
4151 in order to compile large and/or nested @code{case} statements.
4154 @cindex @option{-o} (@command{gcc})
4155 This switch is used in @command{gcc} to redirect the generated object file
4156 and its associated ALI file. Beware of this switch with GNAT, because it may
4157 cause the object file and ALI file to have different names which in turn
4158 may confuse the binder and the linker.
4162 @cindex @option{-nostdinc} (@command{gcc})
4163 Inhibit the search of the default location for the GNAT Run Time
4164 Library (RTL) source files.
4167 @cindex @option{-nostdlib} (@command{gcc})
4168 Inhibit the search of the default location for the GNAT Run Time
4169 Library (RTL) ALI files.
4173 @cindex @option{-O} (@command{gcc})
4174 @var{n} controls the optimization level.
4178 No optimization, the default setting if no @option{-O} appears
4181 Normal optimization, the default if you specify @option{-O} without
4182 an operand. A good compromise between code quality and compilation
4186 Extensive optimization, may improve execution time, possibly at the cost of
4187 substantially increased compilation time.
4190 Same as @option{-O2}, and also includes inline expansion for small subprograms
4194 Optimize space usage
4198 See also @ref{Optimization Levels}.
4203 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4204 Equivalent to @option{/OPTIMIZE=NONE}.
4205 This is the default behavior in the absence of an @option{/OPTIMIZE}
4208 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4209 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4210 Selects the level of optimization for your program. The supported
4211 keywords are as follows:
4214 Perform most optimizations, including those that
4216 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4217 without keyword options.
4220 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4223 Perform some optimizations, but omit ones that are costly.
4226 Same as @code{SOME}.
4229 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4230 automatic inlining of small subprograms within a unit
4233 Try to unroll loops. This keyword may be specified together with
4234 any keyword above other than @code{NONE}. Loop unrolling
4235 usually, but not always, improves the performance of programs.
4238 Optimize space usage
4242 See also @ref{Optimization Levels}.
4246 @item -pass-exit-codes
4247 @cindex @option{-pass-exit-codes} (@command{gcc})
4248 Catch exit codes from the compiler and use the most meaningful as
4252 @item --RTS=@var{rts-path}
4253 @cindex @option{--RTS} (@command{gcc})
4254 Specifies the default location of the runtime library. Same meaning as the
4255 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4258 @cindex @option{^-S^/ASM^} (@command{gcc})
4259 ^Used in place of @option{-c} to^Used to^
4260 cause the assembler source file to be
4261 generated, using @file{^.s^.S^} as the extension,
4262 instead of the object file.
4263 This may be useful if you need to examine the generated assembly code.
4265 @item ^-fverbose-asm^/VERBOSE_ASM^
4266 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4267 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4268 to cause the generated assembly code file to be annotated with variable
4269 names, making it significantly easier to follow.
4272 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4273 Show commands generated by the @command{gcc} driver. Normally used only for
4274 debugging purposes or if you need to be sure what version of the
4275 compiler you are executing.
4279 @cindex @option{-V} (@command{gcc})
4280 Execute @var{ver} version of the compiler. This is the @command{gcc}
4281 version, not the GNAT version.
4284 @item ^-w^/NO_BACK_END_WARNINGS^
4285 @cindex @option{-w} (@command{gcc})
4286 Turn off warnings generated by the back end of the compiler. Use of
4287 this switch also causes the default for front end warnings to be set
4288 to suppress (as though @option{-gnatws} had appeared at the start of
4294 @c Combining qualifiers does not work on VMS
4295 You may combine a sequence of GNAT switches into a single switch. For
4296 example, the combined switch
4298 @cindex Combining GNAT switches
4304 is equivalent to specifying the following sequence of switches:
4307 -gnato -gnatf -gnati3
4312 The following restrictions apply to the combination of switches
4317 The switch @option{-gnatc} if combined with other switches must come
4318 first in the string.
4321 The switch @option{-gnats} if combined with other switches must come
4322 first in the string.
4326 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4327 may not be combined with any other switches.
4331 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4332 switch), then all further characters in the switch are interpreted
4333 as style modifiers (see description of @option{-gnaty}).
4336 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4337 switch), then all further characters in the switch are interpreted
4338 as debug flags (see description of @option{-gnatd}).
4341 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4342 switch), then all further characters in the switch are interpreted
4343 as warning mode modifiers (see description of @option{-gnatw}).
4346 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4347 switch), then all further characters in the switch are interpreted
4348 as validity checking options (see description of @option{-gnatV}).
4352 @node Output and Error Message Control
4353 @subsection Output and Error Message Control
4357 The standard default format for error messages is called ``brief format''.
4358 Brief format messages are written to @file{stderr} (the standard error
4359 file) and have the following form:
4362 e.adb:3:04: Incorrect spelling of keyword "function"
4363 e.adb:4:20: ";" should be "is"
4367 The first integer after the file name is the line number in the file,
4368 and the second integer is the column number within the line.
4370 @code{GPS} can parse the error messages
4371 and point to the referenced character.
4373 The following switches provide control over the error message
4379 @cindex @option{-gnatv} (@command{gcc})
4382 The v stands for verbose.
4384 The effect of this setting is to write long-format error
4385 messages to @file{stdout} (the standard output file.
4386 The same program compiled with the
4387 @option{-gnatv} switch would generate:
4391 3. funcion X (Q : Integer)
4393 >>> Incorrect spelling of keyword "function"
4396 >>> ";" should be "is"
4401 The vertical bar indicates the location of the error, and the @samp{>>>}
4402 prefix can be used to search for error messages. When this switch is
4403 used the only source lines output are those with errors.
4406 @cindex @option{-gnatl} (@command{gcc})
4408 The @code{l} stands for list.
4410 This switch causes a full listing of
4411 the file to be generated. In the case where a body is
4412 compiled, the corresponding spec is also listed, along
4413 with any subunits. Typical output from compiling a package
4414 body @file{p.adb} might look like:
4416 @smallexample @c ada
4420 1. package body p is
4422 3. procedure a is separate;
4433 2. pragma Elaborate_Body
4457 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4458 standard output is redirected, a brief summary is written to
4459 @file{stderr} (standard error) giving the number of error messages and
4460 warning messages generated.
4462 @item -^gnatl^OUTPUT_FILE^=file
4463 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4464 This has the same effect as @option{-gnatl} except that the output is
4465 written to a file instead of to standard output. If the given name
4466 @file{fname} does not start with a period, then it is the full name
4467 of the file to be written. If @file{fname} is an extension, it is
4468 appended to the name of the file being compiled. For example, if
4469 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4470 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4473 @cindex @option{-gnatU} (@command{gcc})
4474 This switch forces all error messages to be preceded by the unique
4475 string ``error:''. This means that error messages take a few more
4476 characters in space, but allows easy searching for and identification
4480 @cindex @option{-gnatb} (@command{gcc})
4482 The @code{b} stands for brief.
4484 This switch causes GNAT to generate the
4485 brief format error messages to @file{stderr} (the standard error
4486 file) as well as the verbose
4487 format message or full listing (which as usual is written to
4488 @file{stdout} (the standard output file).
4490 @item -gnatm=@var{n}
4491 @cindex @option{-gnatm} (@command{gcc})
4493 The @code{m} stands for maximum.
4495 @var{n} is a decimal integer in the
4496 range of 1 to 999 and limits the number of error messages to be
4497 generated. For example, using @option{-gnatm2} might yield
4500 e.adb:3:04: Incorrect spelling of keyword "function"
4501 e.adb:5:35: missing ".."
4502 fatal error: maximum errors reached
4503 compilation abandoned
4507 Note that the equal sign is optional, so the switches
4508 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4511 @cindex @option{-gnatf} (@command{gcc})
4512 @cindex Error messages, suppressing
4514 The @code{f} stands for full.
4516 Normally, the compiler suppresses error messages that are likely to be
4517 redundant. This switch causes all error
4518 messages to be generated. In particular, in the case of
4519 references to undefined variables. If a given variable is referenced
4520 several times, the normal format of messages is
4522 e.adb:7:07: "V" is undefined (more references follow)
4526 where the parenthetical comment warns that there are additional
4527 references to the variable @code{V}. Compiling the same program with the
4528 @option{-gnatf} switch yields
4531 e.adb:7:07: "V" is undefined
4532 e.adb:8:07: "V" is undefined
4533 e.adb:8:12: "V" is undefined
4534 e.adb:8:16: "V" is undefined
4535 e.adb:9:07: "V" is undefined
4536 e.adb:9:12: "V" is undefined
4540 The @option{-gnatf} switch also generates additional information for
4541 some error messages. Some examples are:
4545 Full details on entities not available in high integrity mode
4547 Details on possibly non-portable unchecked conversion
4549 List possible interpretations for ambiguous calls
4551 Additional details on incorrect parameters
4555 @cindex @option{-gnatjnn} (@command{gcc})
4556 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4557 with continuation lines are treated as though the continuation lines were
4558 separate messages (and so a warning with two continuation lines counts as
4559 three warnings, and is listed as three separate messages).
4561 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4562 messages are output in a different manner. A message and all its continuation
4563 lines are treated as a unit, and count as only one warning or message in the
4564 statistics totals. Furthermore, the message is reformatted so that no line
4565 is longer than nn characters.
4568 @cindex @option{-gnatq} (@command{gcc})
4570 The @code{q} stands for quit (really ``don't quit'').
4572 In normal operation mode, the compiler first parses the program and
4573 determines if there are any syntax errors. If there are, appropriate
4574 error messages are generated and compilation is immediately terminated.
4576 GNAT to continue with semantic analysis even if syntax errors have been
4577 found. This may enable the detection of more errors in a single run. On
4578 the other hand, the semantic analyzer is more likely to encounter some
4579 internal fatal error when given a syntactically invalid tree.
4582 @cindex @option{-gnatQ} (@command{gcc})
4583 In normal operation mode, the @file{ALI} file is not generated if any
4584 illegalities are detected in the program. The use of @option{-gnatQ} forces
4585 generation of the @file{ALI} file. This file is marked as being in
4586 error, so it cannot be used for binding purposes, but it does contain
4587 reasonably complete cross-reference information, and thus may be useful
4588 for use by tools (e.g., semantic browsing tools or integrated development
4589 environments) that are driven from the @file{ALI} file. This switch
4590 implies @option{-gnatq}, since the semantic phase must be run to get a
4591 meaningful ALI file.
4593 In addition, if @option{-gnatt} is also specified, then the tree file is
4594 generated even if there are illegalities. It may be useful in this case
4595 to also specify @option{-gnatq} to ensure that full semantic processing
4596 occurs. The resulting tree file can be processed by ASIS, for the purpose
4597 of providing partial information about illegal units, but if the error
4598 causes the tree to be badly malformed, then ASIS may crash during the
4601 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4602 being in error, @command{gnatmake} will attempt to recompile the source when it
4603 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4605 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4606 since ALI files are never generated if @option{-gnats} is set.
4610 @node Warning Message Control
4611 @subsection Warning Message Control
4612 @cindex Warning messages
4614 In addition to error messages, which correspond to illegalities as defined
4615 in the Ada Reference Manual, the compiler detects two kinds of warning
4618 First, the compiler considers some constructs suspicious and generates a
4619 warning message to alert you to a possible error. Second, if the
4620 compiler detects a situation that is sure to raise an exception at
4621 run time, it generates a warning message. The following shows an example
4622 of warning messages:
4624 e.adb:4:24: warning: creation of object may raise Storage_Error
4625 e.adb:10:17: warning: static value out of range
4626 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4630 GNAT considers a large number of situations as appropriate
4631 for the generation of warning messages. As always, warnings are not
4632 definite indications of errors. For example, if you do an out-of-range
4633 assignment with the deliberate intention of raising a
4634 @code{Constraint_Error} exception, then the warning that may be
4635 issued does not indicate an error. Some of the situations for which GNAT
4636 issues warnings (at least some of the time) are given in the following
4637 list. This list is not complete, and new warnings are often added to
4638 subsequent versions of GNAT. The list is intended to give a general idea
4639 of the kinds of warnings that are generated.
4643 Possible infinitely recursive calls
4646 Out-of-range values being assigned
4649 Possible order of elaboration problems
4652 Assertions (pragma Assert) that are sure to fail
4658 Address clauses with possibly unaligned values, or where an attempt is
4659 made to overlay a smaller variable with a larger one.
4662 Fixed-point type declarations with a null range
4665 Direct_IO or Sequential_IO instantiated with a type that has access values
4668 Variables that are never assigned a value
4671 Variables that are referenced before being initialized
4674 Task entries with no corresponding @code{accept} statement
4677 Duplicate accepts for the same task entry in a @code{select}
4680 Objects that take too much storage
4683 Unchecked conversion between types of differing sizes
4686 Missing @code{return} statement along some execution path in a function
4689 Incorrect (unrecognized) pragmas
4692 Incorrect external names
4695 Allocation from empty storage pool
4698 Potentially blocking operation in protected type
4701 Suspicious parenthesization of expressions
4704 Mismatching bounds in an aggregate
4707 Attempt to return local value by reference
4710 Premature instantiation of a generic body
4713 Attempt to pack aliased components
4716 Out of bounds array subscripts
4719 Wrong length on string assignment
4722 Violations of style rules if style checking is enabled
4725 Unused @code{with} clauses
4728 @code{Bit_Order} usage that does not have any effect
4731 @code{Standard.Duration} used to resolve universal fixed expression
4734 Dereference of possibly null value
4737 Declaration that is likely to cause storage error
4740 Internal GNAT unit @code{with}'ed by application unit
4743 Values known to be out of range at compile time
4746 Unreferenced labels and variables
4749 Address overlays that could clobber memory
4752 Unexpected initialization when address clause present
4755 Bad alignment for address clause
4758 Useless type conversions
4761 Redundant assignment statements and other redundant constructs
4764 Useless exception handlers
4767 Accidental hiding of name by child unit
4770 Access before elaboration detected at compile time
4773 A range in a @code{for} loop that is known to be null or might be null
4778 The following section lists compiler switches that are available
4779 to control the handling of warning messages. It is also possible
4780 to exercise much finer control over what warnings are issued and
4781 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4782 gnat_rm, GNAT Reference manual}.
4787 @emph{Activate all optional errors.}
4788 @cindex @option{-gnatwa} (@command{gcc})
4789 This switch activates most optional warning messages, see remaining list
4790 in this section for details on optional warning messages that can be
4791 individually controlled. The warnings that are not turned on by this
4793 @option{-gnatwd} (implicit dereferencing),
4794 @option{-gnatwh} (hiding),
4795 @option{-gnatwl} (elaboration warnings),
4796 @option{-gnatw.o} (warn on values set by out parameters ignored)
4797 and @option{-gnatwt} (tracking of deleted conditional code).
4798 All other optional warnings are turned on.
4801 @emph{Suppress all optional errors.}
4802 @cindex @option{-gnatwA} (@command{gcc})
4803 This switch suppresses all optional warning messages, see remaining list
4804 in this section for details on optional warning messages that can be
4805 individually controlled.
4808 @emph{Activate warnings on failing assertions.}
4809 @cindex @option{-gnatw.a} (@command{gcc})
4810 @cindex Assert failures
4811 This switch activates warnings for assertions where the compiler can tell at
4812 compile time that the assertion will fail. Note that this warning is given
4813 even if assertions are disabled. The default is that such warnings are
4817 @emph{Suppress warnings on failing assertions.}
4818 @cindex @option{-gnatw.A} (@command{gcc})
4819 @cindex Assert failures
4820 This switch suppresses warnings for assertions where the compiler can tell at
4821 compile time that the assertion will fail.
4824 @emph{Activate warnings on bad fixed values.}
4825 @cindex @option{-gnatwb} (@command{gcc})
4826 @cindex Bad fixed values
4827 @cindex Fixed-point Small value
4829 This switch activates warnings for static fixed-point expressions whose
4830 value is not an exact multiple of Small. Such values are implementation
4831 dependent, since an implementation is free to choose either of the multiples
4832 that surround the value. GNAT always chooses the closer one, but this is not
4833 required behavior, and it is better to specify a value that is an exact
4834 multiple, ensuring predictable execution. The default is that such warnings
4838 @emph{Suppress warnings on bad fixed values.}
4839 @cindex @option{-gnatwB} (@command{gcc})
4840 This switch suppresses warnings for static fixed-point expressions whose
4841 value is not an exact multiple of Small.
4844 @emph{Activate warnings on biased representation.}
4845 @cindex @option{-gnatw.b} (@command{gcc})
4846 @cindex Biased representation
4847 This switch activates warnings when a size clause, value size clause, component
4848 clause, or component size clause forces the use of biased representation for an
4849 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4850 to represent 10/11). The default is that such warnings are generated.
4853 @emph{Suppress warnings on biased representation.}
4854 @cindex @option{-gnatwB} (@command{gcc})
4855 This switch suppresses warnings for representation clauses that force the use
4856 of biased representation.
4859 @emph{Activate warnings on conditionals.}
4860 @cindex @option{-gnatwc} (@command{gcc})
4861 @cindex Conditionals, constant
4862 This switch activates warnings for conditional expressions used in
4863 tests that are known to be True or False at compile time. The default
4864 is that such warnings are not generated.
4865 Note that this warning does
4866 not get issued for the use of boolean variables or constants whose
4867 values are known at compile time, since this is a standard technique
4868 for conditional compilation in Ada, and this would generate too many
4869 false positive warnings.
4871 This warning option also activates a special test for comparisons using
4872 the operators ``>='' and`` <=''.
4873 If the compiler can tell that only the equality condition is possible,
4874 then it will warn that the ``>'' or ``<'' part of the test
4875 is useless and that the operator could be replaced by ``=''.
4876 An example would be comparing a @code{Natural} variable <= 0.
4878 This warning option also generates warnings if
4879 one or both tests is optimized away in a membership test for integer
4880 values if the result can be determined at compile time. Range tests on
4881 enumeration types are not included, since it is common for such tests
4882 to include an end point.
4884 This warning can also be turned on using @option{-gnatwa}.
4887 @emph{Suppress warnings on conditionals.}
4888 @cindex @option{-gnatwC} (@command{gcc})
4889 This switch suppresses warnings for conditional expressions used in
4890 tests that are known to be True or False at compile time.
4893 @emph{Activate warnings on missing component clauses.}
4894 @cindex @option{-gnatw.c} (@command{gcc})
4895 @cindex Component clause, missing
4896 This switch activates warnings for record components where a record
4897 representation clause is present and has component clauses for the
4898 majority, but not all, of the components. A warning is given for each
4899 component for which no component clause is present.
4901 This warning can also be turned on using @option{-gnatwa}.
4904 @emph{Suppress warnings on missing component clauses.}
4905 @cindex @option{-gnatwC} (@command{gcc})
4906 This switch suppresses warnings for record components that are
4907 missing a component clause in the situation described above.
4910 @emph{Activate warnings on implicit dereferencing.}
4911 @cindex @option{-gnatwd} (@command{gcc})
4912 If this switch is set, then the use of a prefix of an access type
4913 in an indexed component, slice, or selected component without an
4914 explicit @code{.all} will generate a warning. With this warning
4915 enabled, access checks occur only at points where an explicit
4916 @code{.all} appears in the source code (assuming no warnings are
4917 generated as a result of this switch). The default is that such
4918 warnings are not generated.
4919 Note that @option{-gnatwa} does not affect the setting of
4920 this warning option.
4923 @emph{Suppress warnings on implicit dereferencing.}
4924 @cindex @option{-gnatwD} (@command{gcc})
4925 @cindex Implicit dereferencing
4926 @cindex Dereferencing, implicit
4927 This switch suppresses warnings for implicit dereferences in
4928 indexed components, slices, and selected components.
4931 @emph{Treat warnings as errors.}
4932 @cindex @option{-gnatwe} (@command{gcc})
4933 @cindex Warnings, treat as error
4934 This switch causes warning messages to be treated as errors.
4935 The warning string still appears, but the warning messages are counted
4936 as errors, and prevent the generation of an object file.
4939 @emph{Activate every optional warning}
4940 @cindex @option{-gnatw.e} (@command{gcc})
4941 @cindex Warnings, activate every optional warning
4942 This switch activates all optional warnings, including those which
4943 are not activated by @code{-gnatwa}.
4946 @emph{Activate warnings on unreferenced formals.}
4947 @cindex @option{-gnatwf} (@command{gcc})
4948 @cindex Formals, unreferenced
4949 This switch causes a warning to be generated if a formal parameter
4950 is not referenced in the body of the subprogram. This warning can
4951 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4952 default is that these warnings are not generated.
4955 @emph{Suppress warnings on unreferenced formals.}
4956 @cindex @option{-gnatwF} (@command{gcc})
4957 This switch suppresses warnings for unreferenced formal
4958 parameters. Note that the
4959 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4960 effect of warning on unreferenced entities other than subprogram
4964 @emph{Activate warnings on unrecognized pragmas.}
4965 @cindex @option{-gnatwg} (@command{gcc})
4966 @cindex Pragmas, unrecognized
4967 This switch causes a warning to be generated if an unrecognized
4968 pragma is encountered. Apart from issuing this warning, the
4969 pragma is ignored and has no effect. This warning can
4970 also be turned on using @option{-gnatwa}. The default
4971 is that such warnings are issued (satisfying the Ada Reference
4972 Manual requirement that such warnings appear).
4975 @emph{Suppress warnings on unrecognized pragmas.}
4976 @cindex @option{-gnatwG} (@command{gcc})
4977 This switch suppresses warnings for unrecognized pragmas.
4980 @emph{Activate warnings on hiding.}
4981 @cindex @option{-gnatwh} (@command{gcc})
4982 @cindex Hiding of Declarations
4983 This switch activates warnings on hiding declarations.
4984 A declaration is considered hiding
4985 if it is for a non-overloadable entity, and it declares an entity with the
4986 same name as some other entity that is directly or use-visible. The default
4987 is that such warnings are not generated.
4988 Note that @option{-gnatwa} does not affect the setting of this warning option.
4991 @emph{Suppress warnings on hiding.}
4992 @cindex @option{-gnatwH} (@command{gcc})
4993 This switch suppresses warnings on hiding declarations.
4996 @emph{Activate warnings on implementation units.}
4997 @cindex @option{-gnatwi} (@command{gcc})
4998 This switch activates warnings for a @code{with} of an internal GNAT
4999 implementation unit, defined as any unit from the @code{Ada},
5000 @code{Interfaces}, @code{GNAT},
5001 ^^@code{DEC},^ or @code{System}
5002 hierarchies that is not
5003 documented in either the Ada Reference Manual or the GNAT
5004 Programmer's Reference Manual. Such units are intended only
5005 for internal implementation purposes and should not be @code{with}'ed
5006 by user programs. The default is that such warnings are generated
5007 This warning can also be turned on using @option{-gnatwa}.
5010 @emph{Disable warnings on implementation units.}
5011 @cindex @option{-gnatwI} (@command{gcc})
5012 This switch disables warnings for a @code{with} of an internal GNAT
5013 implementation unit.
5016 @emph{Activate warnings on obsolescent features (Annex J).}
5017 @cindex @option{-gnatwj} (@command{gcc})
5018 @cindex Features, obsolescent
5019 @cindex Obsolescent features
5020 If this warning option is activated, then warnings are generated for
5021 calls to subprograms marked with @code{pragma Obsolescent} and
5022 for use of features in Annex J of the Ada Reference Manual. In the
5023 case of Annex J, not all features are flagged. In particular use
5024 of the renamed packages (like @code{Text_IO}) and use of package
5025 @code{ASCII} are not flagged, since these are very common and
5026 would generate many annoying positive warnings. The default is that
5027 such warnings are not generated. This warning is also turned on by
5028 the use of @option{-gnatwa}.
5030 In addition to the above cases, warnings are also generated for
5031 GNAT features that have been provided in past versions but which
5032 have been superseded (typically by features in the new Ada standard).
5033 For example, @code{pragma Ravenscar} will be flagged since its
5034 function is replaced by @code{pragma Profile(Ravenscar)}.
5036 Note that this warning option functions differently from the
5037 restriction @code{No_Obsolescent_Features} in two respects.
5038 First, the restriction applies only to annex J features.
5039 Second, the restriction does flag uses of package @code{ASCII}.
5042 @emph{Suppress warnings on obsolescent features (Annex J).}
5043 @cindex @option{-gnatwJ} (@command{gcc})
5044 This switch disables warnings on use of obsolescent features.
5047 @emph{Activate warnings on variables that could be constants.}
5048 @cindex @option{-gnatwk} (@command{gcc})
5049 This switch activates warnings for variables that are initialized but
5050 never modified, and then could be declared constants. The default is that
5051 such warnings are not given.
5052 This warning can also be turned on using @option{-gnatwa}.
5055 @emph{Suppress warnings on variables that could be constants.}
5056 @cindex @option{-gnatwK} (@command{gcc})
5057 This switch disables warnings on variables that could be declared constants.
5060 @emph{Activate warnings for elaboration pragmas.}
5061 @cindex @option{-gnatwl} (@command{gcc})
5062 @cindex Elaboration, warnings
5063 This switch activates warnings on missing
5064 @code{Elaborate_All} and @code{Elaborate} pragmas.
5065 See the section in this guide on elaboration checking for details on
5066 when such pragmas should be used. In dynamic elaboration mode, this switch
5067 generations warnings about the need to add elaboration pragmas. Note however,
5068 that if you blindly follow these warnings, and add @code{Elaborate_All}
5069 warnings wherever they are recommended, you basically end up with the
5070 equivalent of the static elaboration model, which may not be what you want for
5071 legacy code for which the static model does not work.
5073 For the static model, the messages generated are labeled "info:" (for
5074 information messages). They are not warnings to add elaboration pragmas,
5075 merely informational messages showing what implicit elaboration pragmas
5076 have been added, for use in analyzing elaboration circularity problems.
5078 Warnings are also generated if you
5079 are using the static mode of elaboration, and a @code{pragma Elaborate}
5080 is encountered. The default is that such warnings
5082 This warning is not automatically turned on by the use of @option{-gnatwa}.
5085 @emph{Suppress warnings for elaboration pragmas.}
5086 @cindex @option{-gnatwL} (@command{gcc})
5087 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5088 See the section in this guide on elaboration checking for details on
5089 when such pragmas should be used.
5092 @emph{Activate warnings on modified but unreferenced variables.}
5093 @cindex @option{-gnatwm} (@command{gcc})
5094 This switch activates warnings for variables that are assigned (using
5095 an initialization value or with one or more assignment statements) but
5096 whose value is never read. The warning is suppressed for volatile
5097 variables and also for variables that are renamings of other variables
5098 or for which an address clause is given.
5099 This warning can also be turned on using @option{-gnatwa}.
5100 The default is that these warnings are not given.
5103 @emph{Disable warnings on modified but unreferenced variables.}
5104 @cindex @option{-gnatwM} (@command{gcc})
5105 This switch disables warnings for variables that are assigned or
5106 initialized, but never read.
5109 @emph{Set normal warnings mode.}
5110 @cindex @option{-gnatwn} (@command{gcc})
5111 This switch sets normal warning mode, in which enabled warnings are
5112 issued and treated as warnings rather than errors. This is the default
5113 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5114 an explicit @option{-gnatws} or
5115 @option{-gnatwe}. It also cancels the effect of the
5116 implicit @option{-gnatwe} that is activated by the
5117 use of @option{-gnatg}.
5120 @emph{Activate warnings on address clause overlays.}
5121 @cindex @option{-gnatwo} (@command{gcc})
5122 @cindex Address Clauses, warnings
5123 This switch activates warnings for possibly unintended initialization
5124 effects of defining address clauses that cause one variable to overlap
5125 another. The default is that such warnings are generated.
5126 This warning can also be turned on using @option{-gnatwa}.
5129 @emph{Suppress warnings on address clause overlays.}
5130 @cindex @option{-gnatwO} (@command{gcc})
5131 This switch suppresses warnings on possibly unintended initialization
5132 effects of defining address clauses that cause one variable to overlap
5136 @emph{Activate warnings on modified but unreferenced out parameters.}
5137 @cindex @option{-gnatw.o} (@command{gcc})
5138 This switch activates warnings for variables that are modified by using
5139 them as actuals for a call to a procedure with an out mode formal, where
5140 the resulting assigned value is never read. It is applicable in the case
5141 where there is more than one out mode formal. If there is only one out
5142 mode formal, the warning is issued by default (controlled by -gnatwu).
5143 The warning is suppressed for volatile
5144 variables and also for variables that are renamings of other variables
5145 or for which an address clause is given.
5146 The default is that these warnings are not given. Note that this warning
5147 is not included in -gnatwa, it must be activated explicitly.
5150 @emph{Disable warnings on modified but unreferenced out parameters.}
5151 @cindex @option{-gnatw.O} (@command{gcc})
5152 This switch suppresses warnings for variables that are modified by using
5153 them as actuals for a call to a procedure with an out mode formal, where
5154 the resulting assigned value is never read.
5157 @emph{Activate warnings on ineffective pragma Inlines.}
5158 @cindex @option{-gnatwp} (@command{gcc})
5159 @cindex Inlining, warnings
5160 This switch activates warnings for failure of front end inlining
5161 (activated by @option{-gnatN}) to inline a particular call. There are
5162 many reasons for not being able to inline a call, including most
5163 commonly that the call is too complex to inline. The default is
5164 that such warnings are not given.
5165 This warning can also be turned on using @option{-gnatwa}.
5166 Warnings on ineffective inlining by the gcc back-end can be activated
5167 separately, using the gcc switch -Winline.
5170 @emph{Suppress warnings on ineffective pragma Inlines.}
5171 @cindex @option{-gnatwP} (@command{gcc})
5172 This switch suppresses warnings on ineffective pragma Inlines. If the
5173 inlining mechanism cannot inline a call, it will simply ignore the
5177 @emph{Activate warnings on parameter ordering.}
5178 @cindex @option{-gnatw.p} (@command{gcc})
5179 @cindex Parameter order, warnings
5180 This switch activates warnings for cases of suspicious parameter
5181 ordering when the list of arguments are all simple identifiers that
5182 match the names of the formals, but are in a different order. The
5183 warning is suppressed if any use of named parameter notation is used,
5184 so this is the appropriate way to suppress a false positive (and
5185 serves to emphasize that the "misordering" is deliberate). The
5187 that such warnings are not given.
5188 This warning can also be turned on using @option{-gnatwa}.
5191 @emph{Suppress warnings on parameter ordering.}
5192 @cindex @option{-gnatw.P} (@command{gcc})
5193 This switch suppresses warnings on cases of suspicious parameter
5197 @emph{Activate warnings on questionable missing parentheses.}
5198 @cindex @option{-gnatwq} (@command{gcc})
5199 @cindex Parentheses, warnings
5200 This switch activates warnings for cases where parentheses are not used and
5201 the result is potential ambiguity from a readers point of view. For example
5202 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5203 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5204 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5205 follow the rule of always parenthesizing to make the association clear, and
5206 this warning switch warns if such parentheses are not present. The default
5207 is that these warnings are given.
5208 This warning can also be turned on using @option{-gnatwa}.
5211 @emph{Suppress warnings on questionable missing parentheses.}
5212 @cindex @option{-gnatwQ} (@command{gcc})
5213 This switch suppresses warnings for cases where the association is not
5214 clear and the use of parentheses is preferred.
5217 @emph{Activate warnings on redundant constructs.}
5218 @cindex @option{-gnatwr} (@command{gcc})
5219 This switch activates warnings for redundant constructs. The following
5220 is the current list of constructs regarded as redundant:
5224 Assignment of an item to itself.
5226 Type conversion that converts an expression to its own type.
5228 Use of the attribute @code{Base} where @code{typ'Base} is the same
5231 Use of pragma @code{Pack} when all components are placed by a record
5232 representation clause.
5234 Exception handler containing only a reraise statement (raise with no
5235 operand) which has no effect.
5237 Use of the operator abs on an operand that is known at compile time
5240 Comparison of boolean expressions to an explicit True value.
5243 This warning can also be turned on using @option{-gnatwa}.
5244 The default is that warnings for redundant constructs are not given.
5247 @emph{Suppress warnings on redundant constructs.}
5248 @cindex @option{-gnatwR} (@command{gcc})
5249 This switch suppresses warnings for redundant constructs.
5252 @emph{Suppress all warnings.}
5253 @cindex @option{-gnatws} (@command{gcc})
5254 This switch completely suppresses the
5255 output of all warning messages from the GNAT front end.
5256 Note that it does not suppress warnings from the @command{gcc} back end.
5257 To suppress these back end warnings as well, use the switch @option{-w}
5258 in addition to @option{-gnatws}.
5261 @emph{Activate warnings for tracking of deleted conditional code.}
5262 @cindex @option{-gnatwt} (@command{gcc})
5263 @cindex Deactivated code, warnings
5264 @cindex Deleted code, warnings
5265 This switch activates warnings for tracking of code in conditionals (IF and
5266 CASE statements) that is detected to be dead code which cannot be executed, and
5267 which is removed by the front end. This warning is off by default, and is not
5268 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5269 useful for detecting deactivated code in certified applications.
5272 @emph{Suppress warnings for tracking of deleted conditional code.}
5273 @cindex @option{-gnatwT} (@command{gcc})
5274 This switch suppresses warnings for tracking of deleted conditional code.
5277 @emph{Activate warnings on unused entities.}
5278 @cindex @option{-gnatwu} (@command{gcc})
5279 This switch activates warnings to be generated for entities that
5280 are declared but not referenced, and for units that are @code{with}'ed
5282 referenced. In the case of packages, a warning is also generated if
5283 no entities in the package are referenced. This means that if the package
5284 is referenced but the only references are in @code{use}
5285 clauses or @code{renames}
5286 declarations, a warning is still generated. A warning is also generated
5287 for a generic package that is @code{with}'ed but never instantiated.
5288 In the case where a package or subprogram body is compiled, and there
5289 is a @code{with} on the corresponding spec
5290 that is only referenced in the body,
5291 a warning is also generated, noting that the
5292 @code{with} can be moved to the body. The default is that
5293 such warnings are not generated.
5294 This switch also activates warnings on unreferenced formals
5295 (it includes the effect of @option{-gnatwf}).
5296 This warning can also be turned on using @option{-gnatwa}.
5299 @emph{Suppress warnings on unused entities.}
5300 @cindex @option{-gnatwU} (@command{gcc})
5301 This switch suppresses warnings for unused entities and packages.
5302 It also turns off warnings on unreferenced formals (and thus includes
5303 the effect of @option{-gnatwF}).
5306 @emph{Activate warnings on unassigned variables.}
5307 @cindex @option{-gnatwv} (@command{gcc})
5308 @cindex Unassigned variable warnings
5309 This switch activates warnings for access to variables which
5310 may not be properly initialized. The default is that
5311 such warnings are generated.
5312 This warning can also be turned on using @option{-gnatwa}.
5315 @emph{Suppress warnings on unassigned variables.}
5316 @cindex @option{-gnatwV} (@command{gcc})
5317 This switch suppresses warnings for access to variables which
5318 may not be properly initialized.
5319 For variables of a composite type, the warning can also be suppressed in
5320 Ada 2005 by using a default initialization with a box. For example, if
5321 Table is an array of records whose components are only partially uninitialized,
5322 then the following code:
5324 @smallexample @c ada
5325 Tab : Table := (others => <>);
5328 will suppress warnings on subsequent statements that access components
5332 @emph{Activate warnings on wrong low bound assumption.}
5333 @cindex @option{-gnatww} (@command{gcc})
5334 @cindex String indexing warnings
5335 This switch activates warnings for indexing an unconstrained string parameter
5336 with a literal or S'Length. This is a case where the code is assuming that the
5337 low bound is one, which is in general not true (for example when a slice is
5338 passed). The default is that such warnings are generated.
5339 This warning can also be turned on using @option{-gnatwa}.
5342 @emph{Suppress warnings on wrong low bound assumption.}
5343 @cindex @option{-gnatwW} (@command{gcc})
5344 This switch suppresses warnings for indexing an unconstrained string parameter
5345 with a literal or S'Length. Note that this warning can also be suppressed
5346 in a particular case by adding an
5347 assertion that the lower bound is 1,
5348 as shown in the following example.
5350 @smallexample @c ada
5351 procedure K (S : String) is
5352 pragma Assert (S'First = 1);
5357 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5358 @cindex @option{-gnatw.w} (@command{gcc})
5359 @cindex Warnings Off control
5360 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5361 where either the pragma is entirely useless (because it suppresses no
5362 warnings), or it could be replaced by @code{pragma Unreferenced} or
5363 @code{pragma Unmodified}.The default is that these warnings are not given.
5364 Note that this warning is not included in -gnatwa, it must be
5365 activated explicitly.
5368 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5369 @cindex @option{-gnatw.W} (@command{gcc})
5370 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5373 @emph{Activate warnings on Export/Import pragmas.}
5374 @cindex @option{-gnatwx} (@command{gcc})
5375 @cindex Export/Import pragma warnings
5376 This switch activates warnings on Export/Import pragmas when
5377 the compiler detects a possible conflict between the Ada and
5378 foreign language calling sequences. For example, the use of
5379 default parameters in a convention C procedure is dubious
5380 because the C compiler cannot supply the proper default, so
5381 a warning is issued. The default is that such warnings are
5383 This warning can also be turned on using @option{-gnatwa}.
5386 @emph{Suppress warnings on Export/Import pragmas.}
5387 @cindex @option{-gnatwX} (@command{gcc})
5388 This switch suppresses warnings on Export/Import pragmas.
5389 The sense of this is that you are telling the compiler that
5390 you know what you are doing in writing the pragma, and it
5391 should not complain at you.
5394 @emph{Activate warnings for No_Exception_Propagation mode.}
5395 @cindex @option{-gnatwm} (@command{gcc})
5396 This switch activates warnings for exception usage when pragma Restrictions
5397 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5398 explicit exception raises which are not covered by a local handler, and for
5399 exception handlers which do not cover a local raise. The default is that these
5400 warnings are not given.
5403 @emph{Disable warnings for No_Exception_Propagation mode.}
5404 This switch disables warnings for exception usage when pragma Restrictions
5405 (No_Exception_Propagation) is in effect.
5408 @emph{Activate warnings for Ada 2005 compatibility issues.}
5409 @cindex @option{-gnatwy} (@command{gcc})
5410 @cindex Ada 2005 compatibility issues warnings
5411 For the most part Ada 2005 is upwards compatible with Ada 95,
5412 but there are some exceptions (for example the fact that
5413 @code{interface} is now a reserved word in Ada 2005). This
5414 switch activates several warnings to help in identifying
5415 and correcting such incompatibilities. The default is that
5416 these warnings are generated. Note that at one point Ada 2005
5417 was called Ada 0Y, hence the choice of character.
5418 This warning can also be turned on using @option{-gnatwa}.
5421 @emph{Disable warnings for Ada 2005 compatibility issues.}
5422 @cindex @option{-gnatwY} (@command{gcc})
5423 @cindex Ada 2005 compatibility issues warnings
5424 This switch suppresses several warnings intended to help in identifying
5425 incompatibilities between Ada 95 and Ada 2005.
5428 @emph{Activate warnings on unchecked conversions.}
5429 @cindex @option{-gnatwz} (@command{gcc})
5430 @cindex Unchecked_Conversion warnings
5431 This switch activates warnings for unchecked conversions
5432 where the types are known at compile time to have different
5434 is that such warnings are generated. Warnings are also
5435 generated for subprogram pointers with different conventions,
5436 and, on VMS only, for data pointers with different conventions.
5437 This warning can also be turned on using @option{-gnatwa}.
5440 @emph{Suppress warnings on unchecked conversions.}
5441 @cindex @option{-gnatwZ} (@command{gcc})
5442 This switch suppresses warnings for unchecked conversions
5443 where the types are known at compile time to have different
5444 sizes or conventions.
5446 @item ^-Wunused^WARNINGS=UNUSED^
5447 @cindex @option{-Wunused}
5448 The warnings controlled by the @option{-gnatw} switch are generated by
5449 the front end of the compiler. The @option{GCC} back end can provide
5450 additional warnings and they are controlled by the @option{-W} switch.
5451 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5452 warnings for entities that are declared but not referenced.
5454 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5455 @cindex @option{-Wuninitialized}
5456 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5457 the back end warning for uninitialized variables. This switch must be
5458 used in conjunction with an optimization level greater than zero.
5460 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5461 @cindex @option{-Wall}
5462 This switch enables all the above warnings from the @option{GCC} back end.
5463 The code generator detects a number of warning situations that are missed
5464 by the @option{GNAT} front end, and this switch can be used to activate them.
5465 The use of this switch also sets the default front end warning mode to
5466 @option{-gnatwa}, that is, most front end warnings activated as well.
5468 @item ^-w^/NO_BACK_END_WARNINGS^
5470 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5471 The use of this switch also sets the default front end warning mode to
5472 @option{-gnatws}, that is, front end warnings suppressed as well.
5478 A string of warning parameters can be used in the same parameter. For example:
5485 will turn on all optional warnings except for elaboration pragma warnings,
5486 and also specify that warnings should be treated as errors.
5488 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5513 @node Debugging and Assertion Control
5514 @subsection Debugging and Assertion Control
5518 @cindex @option{-gnata} (@command{gcc})
5524 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5525 are ignored. This switch, where @samp{a} stands for assert, causes
5526 @code{Assert} and @code{Debug} pragmas to be activated.
5528 The pragmas have the form:
5532 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5533 @var{static-string-expression}@r{]})
5534 @b{pragma} Debug (@var{procedure call})
5539 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5540 If the result is @code{True}, the pragma has no effect (other than
5541 possible side effects from evaluating the expression). If the result is
5542 @code{False}, the exception @code{Assert_Failure} declared in the package
5543 @code{System.Assertions} is
5544 raised (passing @var{static-string-expression}, if present, as the
5545 message associated with the exception). If no string expression is
5546 given the default is a string giving the file name and line number
5549 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5550 @code{pragma Debug} may appear within a declaration sequence, allowing
5551 debugging procedures to be called between declarations.
5554 @item /DEBUG@r{[}=debug-level@r{]}
5556 Specifies how much debugging information is to be included in
5557 the resulting object file where 'debug-level' is one of the following:
5560 Include both debugger symbol records and traceback
5562 This is the default setting.
5564 Include both debugger symbol records and traceback in
5567 Excludes both debugger symbol records and traceback
5568 the object file. Same as /NODEBUG.
5570 Includes only debugger symbol records in the object
5571 file. Note that this doesn't include traceback information.
5576 @node Validity Checking
5577 @subsection Validity Checking
5578 @findex Validity Checking
5581 The Ada Reference Manual has specific requirements for checking
5582 for invalid values. In particular, RM 13.9.1 requires that the
5583 evaluation of invalid values (for example from unchecked conversions),
5584 not result in erroneous execution. In GNAT, the result of such an
5585 evaluation in normal default mode is to either use the value
5586 unmodified, or to raise Constraint_Error in those cases where use
5587 of the unmodified value would cause erroneous execution. The cases
5588 where unmodified values might lead to erroneous execution are case
5589 statements (where a wild jump might result from an invalid value),
5590 and subscripts on the left hand side (where memory corruption could
5591 occur as a result of an invalid value).
5593 The @option{-gnatB} switch tells the compiler to assume that all
5594 values are valid (that is, within their declared subtype range)
5595 except in the context of a use of the Valid attribute. This means
5596 the compiler can generate more efficient code, since the range
5597 of values is better known at compile time.
5599 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5602 The @code{x} argument is a string of letters that
5603 indicate validity checks that are performed or not performed in addition
5604 to the default checks described above.
5607 The options allowed for this qualifier
5608 indicate validity checks that are performed or not performed in addition
5609 to the default checks described above.
5615 @emph{All validity checks.}
5616 @cindex @option{-gnatVa} (@command{gcc})
5617 All validity checks are turned on.
5619 That is, @option{-gnatVa} is
5620 equivalent to @option{gnatVcdfimorst}.
5624 @emph{Validity checks for copies.}
5625 @cindex @option{-gnatVc} (@command{gcc})
5626 The right hand side of assignments, and the initializing values of
5627 object declarations are validity checked.
5630 @emph{Default (RM) validity checks.}
5631 @cindex @option{-gnatVd} (@command{gcc})
5632 Some validity checks are done by default following normal Ada semantics
5634 A check is done in case statements that the expression is within the range
5635 of the subtype. If it is not, Constraint_Error is raised.
5636 For assignments to array components, a check is done that the expression used
5637 as index is within the range. If it is not, Constraint_Error is raised.
5638 Both these validity checks may be turned off using switch @option{-gnatVD}.
5639 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5640 switch @option{-gnatVd} will leave the checks turned on.
5641 Switch @option{-gnatVD} should be used only if you are sure that all such
5642 expressions have valid values. If you use this switch and invalid values
5643 are present, then the program is erroneous, and wild jumps or memory
5644 overwriting may occur.
5647 @emph{Validity checks for elementary components.}
5648 @cindex @option{-gnatVe} (@command{gcc})
5649 In the absence of this switch, assignments to record or array components are
5650 not validity checked, even if validity checks for assignments generally
5651 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5652 require valid data, but assignment of individual components does. So for
5653 example, there is a difference between copying the elements of an array with a
5654 slice assignment, compared to assigning element by element in a loop. This
5655 switch allows you to turn off validity checking for components, even when they
5656 are assigned component by component.
5659 @emph{Validity checks for floating-point values.}
5660 @cindex @option{-gnatVf} (@command{gcc})
5661 In the absence of this switch, validity checking occurs only for discrete
5662 values. If @option{-gnatVf} is specified, then validity checking also applies
5663 for floating-point values, and NaNs and infinities are considered invalid,
5664 as well as out of range values for constrained types. Note that this means
5665 that standard IEEE infinity mode is not allowed. The exact contexts
5666 in which floating-point values are checked depends on the setting of other
5667 options. For example,
5668 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5669 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5670 (the order does not matter) specifies that floating-point parameters of mode
5671 @code{in} should be validity checked.
5674 @emph{Validity checks for @code{in} mode parameters}
5675 @cindex @option{-gnatVi} (@command{gcc})
5676 Arguments for parameters of mode @code{in} are validity checked in function
5677 and procedure calls at the point of call.
5680 @emph{Validity checks for @code{in out} mode parameters.}
5681 @cindex @option{-gnatVm} (@command{gcc})
5682 Arguments for parameters of mode @code{in out} are validity checked in
5683 procedure calls at the point of call. The @code{'m'} here stands for
5684 modify, since this concerns parameters that can be modified by the call.
5685 Note that there is no specific option to test @code{out} parameters,
5686 but any reference within the subprogram will be tested in the usual
5687 manner, and if an invalid value is copied back, any reference to it
5688 will be subject to validity checking.
5691 @emph{No validity checks.}
5692 @cindex @option{-gnatVn} (@command{gcc})
5693 This switch turns off all validity checking, including the default checking
5694 for case statements and left hand side subscripts. Note that the use of
5695 the switch @option{-gnatp} suppresses all run-time checks, including
5696 validity checks, and thus implies @option{-gnatVn}. When this switch
5697 is used, it cancels any other @option{-gnatV} previously issued.
5700 @emph{Validity checks for operator and attribute operands.}
5701 @cindex @option{-gnatVo} (@command{gcc})
5702 Arguments for predefined operators and attributes are validity checked.
5703 This includes all operators in package @code{Standard},
5704 the shift operators defined as intrinsic in package @code{Interfaces}
5705 and operands for attributes such as @code{Pos}. Checks are also made
5706 on individual component values for composite comparisons, and on the
5707 expressions in type conversions and qualified expressions. Checks are
5708 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5711 @emph{Validity checks for parameters.}
5712 @cindex @option{-gnatVp} (@command{gcc})
5713 This controls the treatment of parameters within a subprogram (as opposed
5714 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5715 of parameters on a call. If either of these call options is used, then
5716 normally an assumption is made within a subprogram that the input arguments
5717 have been validity checking at the point of call, and do not need checking
5718 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5719 is not made, and parameters are not assumed to be valid, so their validity
5720 will be checked (or rechecked) within the subprogram.
5723 @emph{Validity checks for function returns.}
5724 @cindex @option{-gnatVr} (@command{gcc})
5725 The expression in @code{return} statements in functions is validity
5729 @emph{Validity checks for subscripts.}
5730 @cindex @option{-gnatVs} (@command{gcc})
5731 All subscripts expressions are checked for validity, whether they appear
5732 on the right side or left side (in default mode only left side subscripts
5733 are validity checked).
5736 @emph{Validity checks for tests.}
5737 @cindex @option{-gnatVt} (@command{gcc})
5738 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5739 statements are checked, as well as guard expressions in entry calls.
5744 The @option{-gnatV} switch may be followed by
5745 ^a string of letters^a list of options^
5746 to turn on a series of validity checking options.
5748 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5749 specifies that in addition to the default validity checking, copies and
5750 function return expressions are to be validity checked.
5751 In order to make it easier
5752 to specify the desired combination of effects,
5754 the upper case letters @code{CDFIMORST} may
5755 be used to turn off the corresponding lower case option.
5758 the prefix @code{NO} on an option turns off the corresponding validity
5761 @item @code{NOCOPIES}
5762 @item @code{NODEFAULT}
5763 @item @code{NOFLOATS}
5764 @item @code{NOIN_PARAMS}
5765 @item @code{NOMOD_PARAMS}
5766 @item @code{NOOPERANDS}
5767 @item @code{NORETURNS}
5768 @item @code{NOSUBSCRIPTS}
5769 @item @code{NOTESTS}
5773 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5774 turns on all validity checking options except for
5775 checking of @code{@b{in out}} procedure arguments.
5777 The specification of additional validity checking generates extra code (and
5778 in the case of @option{-gnatVa} the code expansion can be substantial).
5779 However, these additional checks can be very useful in detecting
5780 uninitialized variables, incorrect use of unchecked conversion, and other
5781 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5782 is useful in conjunction with the extra validity checking, since this
5783 ensures that wherever possible uninitialized variables have invalid values.
5785 See also the pragma @code{Validity_Checks} which allows modification of
5786 the validity checking mode at the program source level, and also allows for
5787 temporary disabling of validity checks.
5789 @node Style Checking
5790 @subsection Style Checking
5791 @findex Style checking
5794 The @option{-gnaty^x^(option,option,@dots{})^} switch
5795 @cindex @option{-gnaty} (@command{gcc})
5796 causes the compiler to
5797 enforce specified style rules. A limited set of style rules has been used
5798 in writing the GNAT sources themselves. This switch allows user programs
5799 to activate all or some of these checks. If the source program fails a
5800 specified style check, an appropriate warning message is given, preceded by
5801 the character sequence ``(style)''.
5803 @code{(option,option,@dots{})} is a sequence of keywords
5806 The string @var{x} is a sequence of letters or digits
5808 indicating the particular style
5809 checks to be performed. The following checks are defined:
5814 @emph{Specify indentation level.}
5815 If a digit from 1-9 appears
5816 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5817 then proper indentation is checked, with the digit indicating the
5818 indentation level required. A value of zero turns off this style check.
5819 The general style of required indentation is as specified by
5820 the examples in the Ada Reference Manual. Full line comments must be
5821 aligned with the @code{--} starting on a column that is a multiple of
5822 the alignment level, or they may be aligned the same way as the following
5823 non-blank line (this is useful when full line comments appear in the middle
5827 @emph{Check attribute casing.}
5828 Attribute names, including the case of keywords such as @code{digits}
5829 used as attributes names, must be written in mixed case, that is, the
5830 initial letter and any letter following an underscore must be uppercase.
5831 All other letters must be lowercase.
5833 @item ^A^ARRAY_INDEXES^
5834 @emph{Use of array index numbers in array attributes.}
5835 When using the array attributes First, Last, Range,
5836 or Length, the index number must be omitted for one-dimensional arrays
5837 and is required for multi-dimensional arrays.
5840 @emph{Blanks not allowed at statement end.}
5841 Trailing blanks are not allowed at the end of statements. The purpose of this
5842 rule, together with h (no horizontal tabs), is to enforce a canonical format
5843 for the use of blanks to separate source tokens.
5846 @emph{Check comments.}
5847 Comments must meet the following set of rules:
5852 The ``@code{--}'' that starts the column must either start in column one,
5853 or else at least one blank must precede this sequence.
5856 Comments that follow other tokens on a line must have at least one blank
5857 following the ``@code{--}'' at the start of the comment.
5860 Full line comments must have two blanks following the ``@code{--}'' that
5861 starts the comment, with the following exceptions.
5864 A line consisting only of the ``@code{--}'' characters, possibly preceded
5865 by blanks is permitted.
5868 A comment starting with ``@code{--x}'' where @code{x} is a special character
5870 This allows proper processing of the output generated by specialized tools
5871 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5873 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5874 special character is defined as being in one of the ASCII ranges
5875 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
5876 Note that this usage is not permitted
5877 in GNAT implementation units (i.e., when @option{-gnatg} is used).
5880 A line consisting entirely of minus signs, possibly preceded by blanks, is
5881 permitted. This allows the construction of box comments where lines of minus
5882 signs are used to form the top and bottom of the box.
5885 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5886 least one blank follows the initial ``@code{--}''. Together with the preceding
5887 rule, this allows the construction of box comments, as shown in the following
5890 ---------------------------
5891 -- This is a box comment --
5892 -- with two text lines. --
5893 ---------------------------
5897 @item ^d^DOS_LINE_ENDINGS^
5898 @emph{Check no DOS line terminators present.}
5899 All lines must be terminated by a single ASCII.LF
5900 character (in particular the DOS line terminator sequence CR/LF is not
5904 @emph{Check end/exit labels.}
5905 Optional labels on @code{end} statements ending subprograms and on
5906 @code{exit} statements exiting named loops, are required to be present.
5909 @emph{No form feeds or vertical tabs.}
5910 Neither form feeds nor vertical tab characters are permitted
5914 @emph{GNAT style mode}
5915 The set of style check switches is set to match that used by the GNAT sources.
5916 This may be useful when developing code that is eventually intended to be
5917 incorporated into GNAT. For further details, see GNAT sources.
5920 @emph{No horizontal tabs.}
5921 Horizontal tab characters are not permitted in the source text.
5922 Together with the b (no blanks at end of line) check, this
5923 enforces a canonical form for the use of blanks to separate
5927 @emph{Check if-then layout.}
5928 The keyword @code{then} must appear either on the same
5929 line as corresponding @code{if}, or on a line on its own, lined
5930 up under the @code{if} with at least one non-blank line in between
5931 containing all or part of the condition to be tested.
5934 @emph{check mode IN keywords}
5935 Mode @code{in} (the default mode) is not
5936 allowed to be given explicitly. @code{in out} is fine,
5937 but not @code{in} on its own.
5940 @emph{Check keyword casing.}
5941 All keywords must be in lower case (with the exception of keywords
5942 such as @code{digits} used as attribute names to which this check
5946 @emph{Check layout.}
5947 Layout of statement and declaration constructs must follow the
5948 recommendations in the Ada Reference Manual, as indicated by the
5949 form of the syntax rules. For example an @code{else} keyword must
5950 be lined up with the corresponding @code{if} keyword.
5952 There are two respects in which the style rule enforced by this check
5953 option are more liberal than those in the Ada Reference Manual. First
5954 in the case of record declarations, it is permissible to put the
5955 @code{record} keyword on the same line as the @code{type} keyword, and
5956 then the @code{end} in @code{end record} must line up under @code{type}.
5957 This is also permitted when the type declaration is split on two lines.
5958 For example, any of the following three layouts is acceptable:
5960 @smallexample @c ada
5983 Second, in the case of a block statement, a permitted alternative
5984 is to put the block label on the same line as the @code{declare} or
5985 @code{begin} keyword, and then line the @code{end} keyword up under
5986 the block label. For example both the following are permitted:
5988 @smallexample @c ada
6006 The same alternative format is allowed for loops. For example, both of
6007 the following are permitted:
6009 @smallexample @c ada
6011 Clear : while J < 10 loop
6022 @item ^Lnnn^MAX_NESTING=nnn^
6023 @emph{Set maximum nesting level}
6024 The maximum level of nesting of constructs (including subprograms, loops,
6025 blocks, packages, and conditionals) may not exceed the given value
6026 @option{nnn}. A value of zero disconnects this style check.
6028 @item ^m^LINE_LENGTH^
6029 @emph{Check maximum line length.}
6030 The length of source lines must not exceed 79 characters, including
6031 any trailing blanks. The value of 79 allows convenient display on an
6032 80 character wide device or window, allowing for possible special
6033 treatment of 80 character lines. Note that this count is of
6034 characters in the source text. This means that a tab character counts
6035 as one character in this count but a wide character sequence counts as
6036 a single character (however many bytes are needed in the encoding).
6038 @item ^Mnnn^MAX_LENGTH=nnn^
6039 @emph{Set maximum line length.}
6040 The length of lines must not exceed the
6041 given value @option{nnn}. The maximum value that can be specified is 32767.
6043 @item ^n^STANDARD_CASING^
6044 @emph{Check casing of entities in Standard.}
6045 Any identifier from Standard must be cased
6046 to match the presentation in the Ada Reference Manual (for example,
6047 @code{Integer} and @code{ASCII.NUL}).
6050 @emph{Turn off all style checks}
6051 All style check options are turned off.
6053 @item ^o^ORDERED_SUBPROGRAMS^
6054 @emph{Check order of subprogram bodies.}
6055 All subprogram bodies in a given scope
6056 (e.g.@: a package body) must be in alphabetical order. The ordering
6057 rule uses normal Ada rules for comparing strings, ignoring casing
6058 of letters, except that if there is a trailing numeric suffix, then
6059 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6062 @item ^O^OVERRIDING_INDICATORS^
6063 @emph{Check that overriding subprograms are explicitly marked as such.}
6064 The declaration of a primitive operation of a type extension that overrides
6065 an inherited operation must carry an overriding indicator.
6068 @emph{Check pragma casing.}
6069 Pragma names must be written in mixed case, that is, the
6070 initial letter and any letter following an underscore must be uppercase.
6071 All other letters must be lowercase.
6073 @item ^r^REFERENCES^
6074 @emph{Check references.}
6075 All identifier references must be cased in the same way as the
6076 corresponding declaration. No specific casing style is imposed on
6077 identifiers. The only requirement is for consistency of references
6080 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6081 @emph{Check no statements after THEN/ELSE.}
6082 No statements are allowed
6083 on the same line as a THEN or ELSE keyword following the
6084 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6085 and a special exception allows a pragma to appear after ELSE.
6088 @emph{Check separate specs.}
6089 Separate declarations (``specs'') are required for subprograms (a
6090 body is not allowed to serve as its own declaration). The only
6091 exception is that parameterless library level procedures are
6092 not required to have a separate declaration. This exception covers
6093 the most frequent form of main program procedures.
6096 @emph{Check token spacing.}
6097 The following token spacing rules are enforced:
6102 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6105 The token @code{=>} must be surrounded by spaces.
6108 The token @code{<>} must be preceded by a space or a left parenthesis.
6111 Binary operators other than @code{**} must be surrounded by spaces.
6112 There is no restriction on the layout of the @code{**} binary operator.
6115 Colon must be surrounded by spaces.
6118 Colon-equal (assignment, initialization) must be surrounded by spaces.
6121 Comma must be the first non-blank character on the line, or be
6122 immediately preceded by a non-blank character, and must be followed
6126 If the token preceding a left parenthesis ends with a letter or digit, then
6127 a space must separate the two tokens.
6130 A right parenthesis must either be the first non-blank character on
6131 a line, or it must be preceded by a non-blank character.
6134 A semicolon must not be preceded by a space, and must not be followed by
6135 a non-blank character.
6138 A unary plus or minus may not be followed by a space.
6141 A vertical bar must be surrounded by spaces.
6144 @item ^u^UNNECESSARY_BLANK_LINES^
6145 @emph{Check unnecessary blank lines.}
6146 Unnecessary blank lines are not allowed. A blank line is considered
6147 unnecessary if it appears at the end of the file, or if more than
6148 one blank line occurs in sequence.
6150 @item ^x^XTRA_PARENS^
6151 @emph{Check extra parentheses.}
6152 Unnecessary extra level of parentheses (C-style) are not allowed
6153 around conditions in @code{if} statements, @code{while} statements and
6154 @code{exit} statements.
6156 @item ^y^ALL_BUILTIN^
6157 @emph{Set all standard style check options}
6158 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6159 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6160 @option{-gnatyS}, @option{-gnatyLnnn},
6161 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6165 @emph{Remove style check options}
6166 This causes any subsequent options in the string to act as canceling the
6167 corresponding style check option. To cancel maximum nesting level control,
6168 use @option{L} parameter witout any integer value after that, because any
6169 digit following @option{-} in the parameter string of the @option{-gnaty}
6170 option will be threated as canceling indentation check. The same is true
6171 for @option{M} parameter. @option{y} and @option{N} parameters are not
6172 allowed after @option{-}.
6175 This causes any subsequent options in the string to enable the corresponding
6176 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6182 @emph{Removing style check options}
6183 If the name of a style check is preceded by @option{NO} then the corresponding
6184 style check is turned off. For example @option{NOCOMMENTS} turns off style
6185 checking for comments.
6190 In the above rules, appearing in column one is always permitted, that is,
6191 counts as meeting either a requirement for a required preceding space,
6192 or as meeting a requirement for no preceding space.
6194 Appearing at the end of a line is also always permitted, that is, counts
6195 as meeting either a requirement for a following space, or as meeting
6196 a requirement for no following space.
6199 If any of these style rules is violated, a message is generated giving
6200 details on the violation. The initial characters of such messages are
6201 always ``@code{(style)}''. Note that these messages are treated as warning
6202 messages, so they normally do not prevent the generation of an object
6203 file. The @option{-gnatwe} switch can be used to treat warning messages,
6204 including style messages, as fatal errors.
6208 @option{-gnaty} on its own (that is not
6209 followed by any letters or digits), then the effect is equivalent
6210 to the use of @option{-gnatyy}, as described above, that is all
6211 built-in standard style check options are enabled.
6215 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6216 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6217 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6229 clears any previously set style checks.
6231 @node Run-Time Checks
6232 @subsection Run-Time Checks
6233 @cindex Division by zero
6234 @cindex Access before elaboration
6235 @cindex Checks, division by zero
6236 @cindex Checks, access before elaboration
6237 @cindex Checks, stack overflow checking
6240 By default, the following checks are suppressed: integer overflow
6241 checks, stack overflow checks, and checks for access before
6242 elaboration on subprogram calls. All other checks, including range
6243 checks and array bounds checks, are turned on by default. The
6244 following @command{gcc} switches refine this default behavior.
6249 @cindex @option{-gnatp} (@command{gcc})
6250 @cindex Suppressing checks
6251 @cindex Checks, suppressing
6253 Suppress all run-time checks as though @code{pragma Suppress (All_checks)}
6254 had been present in the source. Validity checks are also suppressed (in
6255 other words @option{-gnatp} also implies @option{-gnatVn}.
6256 Use this switch to improve the performance
6257 of the code at the expense of safety in the presence of invalid data or
6260 Note that when checks are suppressed, the compiler is allowed, but not
6261 required, to omit the checking code. If the run-time cost of the
6262 checking code is zero or near-zero, the compiler will generate it even
6263 if checks are suppressed. In particular, if the compiler can prove
6264 that a certain check will necessarily fail, it will generate code to
6265 do an unconditional ``raise'', even if checks are suppressed. The
6266 compiler warns in this case.
6268 Of course, run-time checks are omitted whenever the compiler can prove
6269 that they will not fail, whether or not checks are suppressed.
6271 Note that if you suppress a check that would have failed, program
6272 execution is erroneous, which means the behavior is totally
6273 unpredictable. The program might crash, or print wrong answers, or
6274 do anything else. It might even do exactly what you wanted it to do
6275 (and then it might start failing mysteriously next week or next
6276 year). The compiler will generate code based on the assumption that
6277 the condition being checked is true, which can result in disaster if
6278 that assumption is wrong.
6281 @cindex @option{-gnato} (@command{gcc})
6282 @cindex Overflow checks
6283 @cindex Check, overflow
6284 Enables overflow checking for integer operations.
6285 This causes GNAT to generate slower and larger executable
6286 programs by adding code to check for overflow (resulting in raising
6287 @code{Constraint_Error} as required by standard Ada
6288 semantics). These overflow checks correspond to situations in which
6289 the true value of the result of an operation may be outside the base
6290 range of the result type. The following example shows the distinction:
6292 @smallexample @c ada
6293 X1 : Integer := "Integer'Last";
6294 X2 : Integer range 1 .. 5 := "5";
6295 X3 : Integer := "Integer'Last";
6296 X4 : Integer range 1 .. 5 := "5";
6297 F : Float := "2.0E+20";
6306 Note that if explicit values are assigned at compile time, the
6307 compiler may be able to detect overflow at compile time, in which case
6308 no actual run-time checking code is required, and Constraint_Error
6309 will be raised unconditionally, with or without
6310 @option{-gnato}. That's why the assigned values in the above fragment
6311 are in quotes, the meaning is "assign a value not known to the
6312 compiler that happens to be equal to ...". The remaining discussion
6313 assumes that the compiler cannot detect the values at compile time.
6315 Here the first addition results in a value that is outside the base range
6316 of Integer, and hence requires an overflow check for detection of the
6317 constraint error. Thus the first assignment to @code{X1} raises a
6318 @code{Constraint_Error} exception only if @option{-gnato} is set.
6320 The second increment operation results in a violation of the explicit
6321 range constraint; such range checks are performed by default, and are
6322 unaffected by @option{-gnato}.
6324 The two conversions of @code{F} both result in values that are outside
6325 the base range of type @code{Integer} and thus will raise
6326 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6327 The fact that the result of the second conversion is assigned to
6328 variable @code{X4} with a restricted range is irrelevant, since the problem
6329 is in the conversion, not the assignment.
6331 Basically the rule is that in the default mode (@option{-gnato} not
6332 used), the generated code assures that all integer variables stay
6333 within their declared ranges, or within the base range if there is
6334 no declared range. This prevents any serious problems like indexes
6335 out of range for array operations.
6337 What is not checked in default mode is an overflow that results in
6338 an in-range, but incorrect value. In the above example, the assignments
6339 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6340 range of the target variable, but the result is wrong in the sense that
6341 it is too large to be represented correctly. Typically the assignment
6342 to @code{X1} will result in wrap around to the largest negative number.
6343 The conversions of @code{F} will result in some @code{Integer} value
6344 and if that integer value is out of the @code{X4} range then the
6345 subsequent assignment would generate an exception.
6347 @findex Machine_Overflows
6348 Note that the @option{-gnato} switch does not affect the code generated
6349 for any floating-point operations; it applies only to integer
6351 For floating-point, GNAT has the @code{Machine_Overflows}
6352 attribute set to @code{False} and the normal mode of operation is to
6353 generate IEEE NaN and infinite values on overflow or invalid operations
6354 (such as dividing 0.0 by 0.0).
6356 The reason that we distinguish overflow checking from other kinds of
6357 range constraint checking is that a failure of an overflow check, unlike
6358 for example the failure of a range check, can result in an incorrect
6359 value, but cannot cause random memory destruction (like an out of range
6360 subscript), or a wild jump (from an out of range case value). Overflow
6361 checking is also quite expensive in time and space, since in general it
6362 requires the use of double length arithmetic.
6364 Note again that @option{-gnato} is off by default, so overflow checking is
6365 not performed in default mode. This means that out of the box, with the
6366 default settings, GNAT does not do all the checks expected from the
6367 language description in the Ada Reference Manual. If you want all constraint
6368 checks to be performed, as described in this Manual, then you must
6369 explicitly use the -gnato switch either on the @command{gnatmake} or
6370 @command{gcc} command.
6373 @cindex @option{-gnatE} (@command{gcc})
6374 @cindex Elaboration checks
6375 @cindex Check, elaboration
6376 Enables dynamic checks for access-before-elaboration
6377 on subprogram calls and generic instantiations.
6378 Note that @option{-gnatE} is not necessary for safety, because in the
6379 default mode, GNAT ensures statically that the checks would not fail.
6380 For full details of the effect and use of this switch,
6381 @xref{Compiling Using gcc}.
6384 @cindex @option{-fstack-check} (@command{gcc})
6385 @cindex Stack Overflow Checking
6386 @cindex Checks, stack overflow checking
6387 Activates stack overflow checking. For full details of the effect and use of
6388 this switch see @ref{Stack Overflow Checking}.
6393 The setting of these switches only controls the default setting of the
6394 checks. You may modify them using either @code{Suppress} (to remove
6395 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6398 @node Using gcc for Syntax Checking
6399 @subsection Using @command{gcc} for Syntax Checking
6402 @cindex @option{-gnats} (@command{gcc})
6406 The @code{s} stands for ``syntax''.
6409 Run GNAT in syntax checking only mode. For
6410 example, the command
6413 $ gcc -c -gnats x.adb
6417 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6418 series of files in a single command
6420 , and can use wild cards to specify such a group of files.
6421 Note that you must specify the @option{-c} (compile
6422 only) flag in addition to the @option{-gnats} flag.
6425 You may use other switches in conjunction with @option{-gnats}. In
6426 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6427 format of any generated error messages.
6429 When the source file is empty or contains only empty lines and/or comments,
6430 the output is a warning:
6433 $ gcc -c -gnats -x ada toto.txt
6434 toto.txt:1:01: warning: empty file, contains no compilation units
6438 Otherwise, the output is simply the error messages, if any. No object file or
6439 ALI file is generated by a syntax-only compilation. Also, no units other
6440 than the one specified are accessed. For example, if a unit @code{X}
6441 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6442 check only mode does not access the source file containing unit
6445 @cindex Multiple units, syntax checking
6446 Normally, GNAT allows only a single unit in a source file. However, this
6447 restriction does not apply in syntax-check-only mode, and it is possible
6448 to check a file containing multiple compilation units concatenated
6449 together. This is primarily used by the @code{gnatchop} utility
6450 (@pxref{Renaming Files Using gnatchop}).
6453 @node Using gcc for Semantic Checking
6454 @subsection Using @command{gcc} for Semantic Checking
6457 @cindex @option{-gnatc} (@command{gcc})
6461 The @code{c} stands for ``check''.
6463 Causes the compiler to operate in semantic check mode,
6464 with full checking for all illegalities specified in the
6465 Ada Reference Manual, but without generation of any object code
6466 (no object file is generated).
6468 Because dependent files must be accessed, you must follow the GNAT
6469 semantic restrictions on file structuring to operate in this mode:
6473 The needed source files must be accessible
6474 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6477 Each file must contain only one compilation unit.
6480 The file name and unit name must match (@pxref{File Naming Rules}).
6483 The output consists of error messages as appropriate. No object file is
6484 generated. An @file{ALI} file is generated for use in the context of
6485 cross-reference tools, but this file is marked as not being suitable
6486 for binding (since no object file is generated).
6487 The checking corresponds exactly to the notion of
6488 legality in the Ada Reference Manual.
6490 Any unit can be compiled in semantics-checking-only mode, including
6491 units that would not normally be compiled (subunits,
6492 and specifications where a separate body is present).
6495 @node Compiling Different Versions of Ada
6496 @subsection Compiling Different Versions of Ada
6499 The switches described in this section allow you to explicitly specify
6500 the version of the Ada language that your programs are written in.
6501 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6502 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6503 indicate Ada 83 compatibility mode.
6506 @cindex Compatibility with Ada 83
6508 @item -gnat83 (Ada 83 Compatibility Mode)
6509 @cindex @option{-gnat83} (@command{gcc})
6510 @cindex ACVC, Ada 83 tests
6514 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6515 specifies that the program is to be compiled in Ada 83 mode. With
6516 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6517 semantics where this can be done easily.
6518 It is not possible to guarantee this switch does a perfect
6519 job; some subtle tests, such as are
6520 found in earlier ACVC tests (and that have been removed from the ACATS suite
6521 for Ada 95), might not compile correctly.
6522 Nevertheless, this switch may be useful in some circumstances, for example
6523 where, due to contractual reasons, existing code needs to be maintained
6524 using only Ada 83 features.
6526 With few exceptions (most notably the need to use @code{<>} on
6527 @cindex Generic formal parameters
6528 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6529 reserved words, and the use of packages
6530 with optional bodies), it is not necessary to specify the
6531 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6532 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6533 a correct Ada 83 program is usually also a correct program
6534 in these later versions of the language standard.
6535 For further information, please refer to @ref{Compatibility and Porting Guide}.
6537 @item -gnat95 (Ada 95 mode)
6538 @cindex @option{-gnat95} (@command{gcc})
6542 This switch directs the compiler to implement the Ada 95 version of the
6544 Since Ada 95 is almost completely upwards
6545 compatible with Ada 83, Ada 83 programs may generally be compiled using
6546 this switch (see the description of the @option{-gnat83} switch for further
6547 information about Ada 83 mode).
6548 If an Ada 2005 program is compiled in Ada 95 mode,
6549 uses of the new Ada 2005 features will cause error
6550 messages or warnings.
6552 This switch also can be used to cancel the effect of a previous
6553 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6555 @item -gnat05 (Ada 2005 mode)
6556 @cindex @option{-gnat05} (@command{gcc})
6557 @cindex Ada 2005 mode
6560 This switch directs the compiler to implement the Ada 2005 version of the
6562 Since Ada 2005 is almost completely upwards
6563 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6564 may generally be compiled using this switch (see the description of the
6565 @option{-gnat83} and @option{-gnat95} switches for further
6568 For information about the approved ``Ada Issues'' that have been incorporated
6569 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6570 Included with GNAT releases is a file @file{features-ada0y} that describes
6571 the set of implemented Ada 2005 features.
6575 @node Character Set Control
6576 @subsection Character Set Control
6578 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6579 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6582 Normally GNAT recognizes the Latin-1 character set in source program
6583 identifiers, as described in the Ada Reference Manual.
6585 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6586 single character ^^or word^ indicating the character set, as follows:
6590 ISO 8859-1 (Latin-1) identifiers
6593 ISO 8859-2 (Latin-2) letters allowed in identifiers
6596 ISO 8859-3 (Latin-3) letters allowed in identifiers
6599 ISO 8859-4 (Latin-4) letters allowed in identifiers
6602 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6605 ISO 8859-15 (Latin-9) letters allowed in identifiers
6608 IBM PC letters (code page 437) allowed in identifiers
6611 IBM PC letters (code page 850) allowed in identifiers
6613 @item ^f^FULL_UPPER^
6614 Full upper-half codes allowed in identifiers
6617 No upper-half codes allowed in identifiers
6620 Wide-character codes (that is, codes greater than 255)
6621 allowed in identifiers
6624 @xref{Foreign Language Representation}, for full details on the
6625 implementation of these character sets.
6627 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6628 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6629 Specify the method of encoding for wide characters.
6630 @var{e} is one of the following:
6635 Hex encoding (brackets coding also recognized)
6638 Upper half encoding (brackets encoding also recognized)
6641 Shift/JIS encoding (brackets encoding also recognized)
6644 EUC encoding (brackets encoding also recognized)
6647 UTF-8 encoding (brackets encoding also recognized)
6650 Brackets encoding only (default value)
6652 For full details on these encoding
6653 methods see @ref{Wide Character Encodings}.
6654 Note that brackets coding is always accepted, even if one of the other
6655 options is specified, so for example @option{-gnatW8} specifies that both
6656 brackets and UTF-8 encodings will be recognized. The units that are
6657 with'ed directly or indirectly will be scanned using the specified
6658 representation scheme, and so if one of the non-brackets scheme is
6659 used, it must be used consistently throughout the program. However,
6660 since brackets encoding is always recognized, it may be conveniently
6661 used in standard libraries, allowing these libraries to be used with
6662 any of the available coding schemes.
6665 If no @option{-gnatW?} parameter is present, then the default
6666 representation is normally Brackets encoding only. However, if the
6667 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6668 byte order mark or BOM for UTF-8), then these three characters are
6669 skipped and the default representation for the file is set to UTF-8.
6671 Note that the wide character representation that is specified (explicitly
6672 or by default) for the main program also acts as the default encoding used
6673 for Wide_Text_IO files if not specifically overridden by a WCEM form
6677 @node File Naming Control
6678 @subsection File Naming Control
6681 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6682 @cindex @option{-gnatk} (@command{gcc})
6683 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6684 1-999, indicates the maximum allowable length of a file name (not
6685 including the @file{.ads} or @file{.adb} extension). The default is not
6686 to enable file name krunching.
6688 For the source file naming rules, @xref{File Naming Rules}.
6691 @node Subprogram Inlining Control
6692 @subsection Subprogram Inlining Control
6697 @cindex @option{-gnatn} (@command{gcc})
6699 The @code{n} here is intended to suggest the first syllable of the
6702 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6703 inlining to actually occur, optimization must be enabled. To enable
6704 inlining of subprograms specified by pragma @code{Inline},
6705 you must also specify this switch.
6706 In the absence of this switch, GNAT does not attempt
6707 inlining and does not need to access the bodies of
6708 subprograms for which @code{pragma Inline} is specified if they are not
6709 in the current unit.
6711 If you specify this switch the compiler will access these bodies,
6712 creating an extra source dependency for the resulting object file, and
6713 where possible, the call will be inlined.
6714 For further details on when inlining is possible
6715 see @ref{Inlining of Subprograms}.
6718 @cindex @option{-gnatN} (@command{gcc})
6719 The front end inlining activated by this switch is generally more extensive,
6720 and quite often more effective than the standard @option{-gnatn} inlining mode.
6721 It will also generate additional dependencies.
6723 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6724 to specify both options.
6727 @node Auxiliary Output Control
6728 @subsection Auxiliary Output Control
6732 @cindex @option{-gnatt} (@command{gcc})
6733 @cindex Writing internal trees
6734 @cindex Internal trees, writing to file
6735 Causes GNAT to write the internal tree for a unit to a file (with the
6736 extension @file{.adt}.
6737 This not normally required, but is used by separate analysis tools.
6739 these tools do the necessary compilations automatically, so you should
6740 not have to specify this switch in normal operation.
6743 @cindex @option{-gnatu} (@command{gcc})
6744 Print a list of units required by this compilation on @file{stdout}.
6745 The listing includes all units on which the unit being compiled depends
6746 either directly or indirectly.
6749 @item -pass-exit-codes
6750 @cindex @option{-pass-exit-codes} (@command{gcc})
6751 If this switch is not used, the exit code returned by @command{gcc} when
6752 compiling multiple files indicates whether all source files have
6753 been successfully used to generate object files or not.
6755 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6756 exit status and allows an integrated development environment to better
6757 react to a compilation failure. Those exit status are:
6761 There was an error in at least one source file.
6763 At least one source file did not generate an object file.
6765 The compiler died unexpectedly (internal error for example).
6767 An object file has been generated for every source file.
6772 @node Debugging Control
6773 @subsection Debugging Control
6777 @cindex Debugging options
6780 @cindex @option{-gnatd} (@command{gcc})
6781 Activate internal debugging switches. @var{x} is a letter or digit, or
6782 string of letters or digits, which specifies the type of debugging
6783 outputs desired. Normally these are used only for internal development
6784 or system debugging purposes. You can find full documentation for these
6785 switches in the body of the @code{Debug} unit in the compiler source
6786 file @file{debug.adb}.
6790 @cindex @option{-gnatG} (@command{gcc})
6791 This switch causes the compiler to generate auxiliary output containing
6792 a pseudo-source listing of the generated expanded code. Like most Ada
6793 compilers, GNAT works by first transforming the high level Ada code into
6794 lower level constructs. For example, tasking operations are transformed
6795 into calls to the tasking run-time routines. A unique capability of GNAT
6796 is to list this expanded code in a form very close to normal Ada source.
6797 This is very useful in understanding the implications of various Ada
6798 usage on the efficiency of the generated code. There are many cases in
6799 Ada (e.g.@: the use of controlled types), where simple Ada statements can
6800 generate a lot of run-time code. By using @option{-gnatG} you can identify
6801 these cases, and consider whether it may be desirable to modify the coding
6802 approach to improve efficiency.
6804 The optional parameter @code{nn} if present after -gnatG specifies an
6805 alternative maximum line length that overrides the normal default of 72.
6806 This value is in the range 40-999999, values less than 40 being silently
6809 The format of the output is very similar to standard Ada source, and is
6810 easily understood by an Ada programmer. The following special syntactic
6811 additions correspond to low level features used in the generated code that
6812 do not have any exact analogies in pure Ada source form. The following
6813 is a partial list of these special constructions. See the spec
6814 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6816 If the switch @option{-gnatL} is used in conjunction with
6817 @cindex @option{-gnatL} (@command{gcc})
6818 @option{-gnatG}, then the original source lines are interspersed
6819 in the expanded source (as comment lines with the original line number).
6822 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
6823 Shows the storage pool being used for an allocator.
6825 @item at end @var{procedure-name};
6826 Shows the finalization (cleanup) procedure for a scope.
6828 @item (if @var{expr} then @var{expr} else @var{expr})
6829 Conditional expression equivalent to the @code{x?y:z} construction in C.
6831 @item @var{target}^^^(@var{source})
6832 A conversion with floating-point truncation instead of rounding.
6834 @item @var{target}?(@var{source})
6835 A conversion that bypasses normal Ada semantic checking. In particular
6836 enumeration types and fixed-point types are treated simply as integers.
6838 @item @var{target}?^^^(@var{source})
6839 Combines the above two cases.
6841 @item @var{x} #/ @var{y}
6842 @itemx @var{x} #mod @var{y}
6843 @itemx @var{x} #* @var{y}
6844 @itemx @var{x} #rem @var{y}
6845 A division or multiplication of fixed-point values which are treated as
6846 integers without any kind of scaling.
6848 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
6849 Shows the storage pool associated with a @code{free} statement.
6851 @item [subtype or type declaration]
6852 Used to list an equivalent declaration for an internally generated
6853 type that is referenced elsewhere in the listing.
6855 @item freeze @var{type-name} @ovar{actions}
6856 Shows the point at which @var{type-name} is frozen, with possible
6857 associated actions to be performed at the freeze point.
6859 @item reference @var{itype}
6860 Reference (and hence definition) to internal type @var{itype}.
6862 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6863 Intrinsic function call.
6865 @item @var{label-name} : label
6866 Declaration of label @var{labelname}.
6868 @item #$ @var{subprogram-name}
6869 An implicit call to a run-time support routine
6870 (to meet the requirement of H.3.1(9) in a
6873 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
6874 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6875 @var{expr}, but handled more efficiently).
6877 @item [constraint_error]
6878 Raise the @code{Constraint_Error} exception.
6880 @item @var{expression}'reference
6881 A pointer to the result of evaluating @var{expression}.
6883 @item @var{target-type}!(@var{source-expression})
6884 An unchecked conversion of @var{source-expression} to @var{target-type}.
6886 @item [@var{numerator}/@var{denominator}]
6887 Used to represent internal real literals (that) have no exact
6888 representation in base 2-16 (for example, the result of compile time
6889 evaluation of the expression 1.0/27.0).
6893 @cindex @option{-gnatD} (@command{gcc})
6894 When used in conjunction with @option{-gnatG}, this switch causes
6895 the expanded source, as described above for
6896 @option{-gnatG} to be written to files with names
6897 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6898 instead of to the standard output file. For
6899 example, if the source file name is @file{hello.adb}, then a file
6900 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
6901 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6902 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6903 you to do source level debugging using the generated code which is
6904 sometimes useful for complex code, for example to find out exactly
6905 which part of a complex construction raised an exception. This switch
6906 also suppress generation of cross-reference information (see
6907 @option{-gnatx}) since otherwise the cross-reference information
6908 would refer to the @file{^.dg^.DG^} file, which would cause
6909 confusion since this is not the original source file.
6911 Note that @option{-gnatD} actually implies @option{-gnatG}
6912 automatically, so it is not necessary to give both options.
6913 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6915 If the switch @option{-gnatL} is used in conjunction with
6916 @cindex @option{-gnatL} (@command{gcc})
6917 @option{-gnatDG}, then the original source lines are interspersed
6918 in the expanded source (as comment lines with the original line number).
6920 The optional parameter @code{nn} if present after -gnatD specifies an
6921 alternative maximum line length that overrides the normal default of 72.
6922 This value is in the range 40-999999, values less than 40 being silently
6926 @cindex @option{-gnatr} (@command{gcc})
6927 @cindex pragma Restrictions
6928 This switch causes pragma Restrictions to be treated as Restriction_Warnings
6929 so that violation of restrictions causes warnings rather than illegalities.
6930 This is useful during the development process when new restrictions are added
6931 or investigated. The switch also causes pragma Profile to be treated as
6932 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
6933 restriction warnings rather than restrictions.
6936 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
6937 @cindex @option{-gnatR} (@command{gcc})
6938 This switch controls output from the compiler of a listing showing
6939 representation information for declared types and objects. For
6940 @option{-gnatR0}, no information is output (equivalent to omitting
6941 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6942 so @option{-gnatR} with no parameter has the same effect), size and alignment
6943 information is listed for declared array and record types. For
6944 @option{-gnatR2}, size and alignment information is listed for all
6945 declared types and objects. Finally @option{-gnatR3} includes symbolic
6946 expressions for values that are computed at run time for
6947 variant records. These symbolic expressions have a mostly obvious
6948 format with #n being used to represent the value of the n'th
6949 discriminant. See source files @file{repinfo.ads/adb} in the
6950 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6951 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
6952 the output is to a file with the name @file{^file.rep^file_REP^} where
6953 file is the name of the corresponding source file.
6956 @item /REPRESENTATION_INFO
6957 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6958 This qualifier controls output from the compiler of a listing showing
6959 representation information for declared types and objects. For
6960 @option{/REPRESENTATION_INFO=NONE}, no information is output
6961 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6962 @option{/REPRESENTATION_INFO} without option is equivalent to
6963 @option{/REPRESENTATION_INFO=ARRAYS}.
6964 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6965 information is listed for declared array and record types. For
6966 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6967 is listed for all expression information for values that are computed
6968 at run time for variant records. These symbolic expressions have a mostly
6969 obvious format with #n being used to represent the value of the n'th
6970 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6971 @code{GNAT} sources for full details on the format of
6972 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6973 If _FILE is added at the end of an option
6974 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6975 then the output is to a file with the name @file{file_REP} where
6976 file is the name of the corresponding source file.
6978 Note that it is possible for record components to have zero size. In
6979 this case, the component clause uses an obvious extension of permitted
6980 Ada syntax, for example @code{at 0 range 0 .. -1}.
6982 Representation information requires that code be generated (since it is the
6983 code generator that lays out complex data structures). If an attempt is made
6984 to output representation information when no code is generated, for example
6985 when a subunit is compiled on its own, then no information can be generated
6986 and the compiler outputs a message to this effect.
6989 @cindex @option{-gnatS} (@command{gcc})
6990 The use of the switch @option{-gnatS} for an
6991 Ada compilation will cause the compiler to output a
6992 representation of package Standard in a form very
6993 close to standard Ada. It is not quite possible to
6994 do this entirely in standard Ada (since new
6995 numeric base types cannot be created in standard
6996 Ada), but the output is easily
6997 readable to any Ada programmer, and is useful to
6998 determine the characteristics of target dependent
6999 types in package Standard.
7002 @cindex @option{-gnatx} (@command{gcc})
7003 Normally the compiler generates full cross-referencing information in
7004 the @file{ALI} file. This information is used by a number of tools,
7005 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7006 suppresses this information. This saves some space and may slightly
7007 speed up compilation, but means that these tools cannot be used.
7010 @node Exception Handling Control
7011 @subsection Exception Handling Control
7014 GNAT uses two methods for handling exceptions at run-time. The
7015 @code{setjmp/longjmp} method saves the context when entering
7016 a frame with an exception handler. Then when an exception is
7017 raised, the context can be restored immediately, without the
7018 need for tracing stack frames. This method provides very fast
7019 exception propagation, but introduces significant overhead for
7020 the use of exception handlers, even if no exception is raised.
7022 The other approach is called ``zero cost'' exception handling.
7023 With this method, the compiler builds static tables to describe
7024 the exception ranges. No dynamic code is required when entering
7025 a frame containing an exception handler. When an exception is
7026 raised, the tables are used to control a back trace of the
7027 subprogram invocation stack to locate the required exception
7028 handler. This method has considerably poorer performance for
7029 the propagation of exceptions, but there is no overhead for
7030 exception handlers if no exception is raised. Note that in this
7031 mode and in the context of mixed Ada and C/C++ programming,
7032 to propagate an exception through a C/C++ code, the C/C++ code
7033 must be compiled with the @option{-funwind-tables} GCC's
7036 The following switches may be used to control which of the
7037 two exception handling methods is used.
7043 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7044 This switch causes the setjmp/longjmp run-time (when available) to be used
7045 for exception handling. If the default
7046 mechanism for the target is zero cost exceptions, then
7047 this switch can be used to modify this default, and must be
7048 used for all units in the partition.
7049 This option is rarely used. One case in which it may be
7050 advantageous is if you have an application where exception
7051 raising is common and the overall performance of the
7052 application is improved by favoring exception propagation.
7055 @cindex @option{--RTS=zcx} (@command{gnatmake})
7056 @cindex Zero Cost Exceptions
7057 This switch causes the zero cost approach to be used
7058 for exception handling. If this is the default mechanism for the
7059 target (see below), then this switch is unneeded. If the default
7060 mechanism for the target is setjmp/longjmp exceptions, then
7061 this switch can be used to modify this default, and must be
7062 used for all units in the partition.
7063 This option can only be used if the zero cost approach
7064 is available for the target in use, otherwise it will generate an error.
7068 The same option @option{--RTS} must be used both for @command{gcc}
7069 and @command{gnatbind}. Passing this option to @command{gnatmake}
7070 (@pxref{Switches for gnatmake}) will ensure the required consistency
7071 through the compilation and binding steps.
7073 @node Units to Sources Mapping Files
7074 @subsection Units to Sources Mapping Files
7078 @item -gnatem^^=^@var{path}
7079 @cindex @option{-gnatem} (@command{gcc})
7080 A mapping file is a way to communicate to the compiler two mappings:
7081 from unit names to file names (without any directory information) and from
7082 file names to path names (with full directory information). These mappings
7083 are used by the compiler to short-circuit the path search.
7085 The use of mapping files is not required for correct operation of the
7086 compiler, but mapping files can improve efficiency, particularly when
7087 sources are read over a slow network connection. In normal operation,
7088 you need not be concerned with the format or use of mapping files,
7089 and the @option{-gnatem} switch is not a switch that you would use
7090 explicitly. it is intended only for use by automatic tools such as
7091 @command{gnatmake} running under the project file facility. The
7092 description here of the format of mapping files is provided
7093 for completeness and for possible use by other tools.
7095 A mapping file is a sequence of sets of three lines. In each set,
7096 the first line is the unit name, in lower case, with ``@code{%s}''
7098 specs and ``@code{%b}'' appended for bodies; the second line is the
7099 file name; and the third line is the path name.
7105 /gnat/project1/sources/main.2.ada
7108 When the switch @option{-gnatem} is specified, the compiler will create
7109 in memory the two mappings from the specified file. If there is any problem
7110 (nonexistent file, truncated file or duplicate entries), no mapping will
7113 Several @option{-gnatem} switches may be specified; however, only the last
7114 one on the command line will be taken into account.
7116 When using a project file, @command{gnatmake} create a temporary mapping file
7117 and communicates it to the compiler using this switch.
7121 @node Integrated Preprocessing
7122 @subsection Integrated Preprocessing
7125 GNAT sources may be preprocessed immediately before compilation.
7126 In this case, the actual
7127 text of the source is not the text of the source file, but is derived from it
7128 through a process called preprocessing. Integrated preprocessing is specified
7129 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7130 indicates, through a text file, the preprocessing data to be used.
7131 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7134 Note that when integrated preprocessing is used, the output from the
7135 preprocessor is not written to any external file. Instead it is passed
7136 internally to the compiler. If you need to preserve the result of
7137 preprocessing in a file, then you should use @command{gnatprep}
7138 to perform the desired preprocessing in stand-alone mode.
7141 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7142 used when Integrated Preprocessing is used. The reason is that preprocessing
7143 with another Preprocessing Data file without changing the sources will
7144 not trigger recompilation without this switch.
7147 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7148 always trigger recompilation for sources that are preprocessed,
7149 because @command{gnatmake} cannot compute the checksum of the source after
7153 The actual preprocessing function is described in details in section
7154 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7155 preprocessing is triggered and parameterized.
7159 @item -gnatep=@var{file}
7160 @cindex @option{-gnatep} (@command{gcc})
7161 This switch indicates to the compiler the file name (without directory
7162 information) of the preprocessor data file to use. The preprocessor data file
7163 should be found in the source directories.
7166 A preprocessing data file is a text file with significant lines indicating
7167 how should be preprocessed either a specific source or all sources not
7168 mentioned in other lines. A significant line is a nonempty, non-comment line.
7169 Comments are similar to Ada comments.
7172 Each significant line starts with either a literal string or the character '*'.
7173 A literal string is the file name (without directory information) of the source
7174 to preprocess. A character '*' indicates the preprocessing for all the sources
7175 that are not specified explicitly on other lines (order of the lines is not
7176 significant). It is an error to have two lines with the same file name or two
7177 lines starting with the character '*'.
7180 After the file name or the character '*', another optional literal string
7181 indicating the file name of the definition file to be used for preprocessing
7182 (@pxref{Form of Definitions File}). The definition files are found by the
7183 compiler in one of the source directories. In some cases, when compiling
7184 a source in a directory other than the current directory, if the definition
7185 file is in the current directory, it may be necessary to add the current
7186 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7187 the compiler would not find the definition file.
7190 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7191 be found. Those ^switches^switches^ are:
7196 Causes both preprocessor lines and the lines deleted by
7197 preprocessing to be replaced by blank lines, preserving the line number.
7198 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7199 it cancels the effect of @option{-c}.
7202 Causes both preprocessor lines and the lines deleted
7203 by preprocessing to be retained as comments marked
7204 with the special string ``@code{--! }''.
7206 @item -Dsymbol=value
7207 Define or redefine a symbol, associated with value. A symbol is an Ada
7208 identifier, or an Ada reserved word, with the exception of @code{if},
7209 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7210 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7211 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7212 same name defined in a definition file.
7215 Causes a sorted list of symbol names and values to be
7216 listed on the standard output file.
7219 Causes undefined symbols to be treated as having the value @code{FALSE}
7221 of a preprocessor test. In the absence of this option, an undefined symbol in
7222 a @code{#if} or @code{#elsif} test will be treated as an error.
7227 Examples of valid lines in a preprocessor data file:
7230 "toto.adb" "prep.def" -u
7231 -- preprocess "toto.adb", using definition file "prep.def",
7232 -- undefined symbol are False.
7235 -- preprocess all other sources without a definition file;
7236 -- suppressed lined are commented; symbol VERSION has the value V101.
7238 "titi.adb" "prep2.def" -s
7239 -- preprocess "titi.adb", using definition file "prep2.def";
7240 -- list all symbols with their values.
7243 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7244 @cindex @option{-gnateD} (@command{gcc})
7245 Define or redefine a preprocessing symbol, associated with value. If no value
7246 is given on the command line, then the value of the symbol is @code{True}.
7247 A symbol is an identifier, following normal Ada (case-insensitive)
7248 rules for its syntax, and value is any sequence (including an empty sequence)
7249 of characters from the set (letters, digits, period, underline).
7250 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7251 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7254 A symbol declared with this ^switch^switch^ on the command line replaces a
7255 symbol with the same name either in a definition file or specified with a
7256 ^switch^switch^ -D in the preprocessor data file.
7259 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7262 When integrated preprocessing is performed and the preprocessor modifies
7263 the source text, write the result of this preprocessing into a file
7264 <source>^.prep^_prep^.
7268 @node Code Generation Control
7269 @subsection Code Generation Control
7273 The GCC technology provides a wide range of target dependent
7274 @option{-m} switches for controlling
7275 details of code generation with respect to different versions of
7276 architectures. This includes variations in instruction sets (e.g.@:
7277 different members of the power pc family), and different requirements
7278 for optimal arrangement of instructions (e.g.@: different members of
7279 the x86 family). The list of available @option{-m} switches may be
7280 found in the GCC documentation.
7282 Use of these @option{-m} switches may in some cases result in improved
7285 The GNAT Pro technology is tested and qualified without any
7286 @option{-m} switches,
7287 so generally the most reliable approach is to avoid the use of these
7288 switches. However, we generally expect most of these switches to work
7289 successfully with GNAT Pro, and many customers have reported successful
7290 use of these options.
7292 Our general advice is to avoid the use of @option{-m} switches unless
7293 special needs lead to requirements in this area. In particular,
7294 there is no point in using @option{-m} switches to improve performance
7295 unless you actually see a performance improvement.
7299 @subsection Return Codes
7300 @cindex Return Codes
7301 @cindex @option{/RETURN_CODES=VMS}
7304 On VMS, GNAT compiled programs return POSIX-style codes by default,
7305 e.g.@: @option{/RETURN_CODES=POSIX}.
7307 To enable VMS style return codes, use GNAT BIND and LINK with the option
7308 @option{/RETURN_CODES=VMS}. For example:
7311 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7312 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7316 Programs built with /RETURN_CODES=VMS are suitable to be called in
7317 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7318 are suitable for spawning with appropriate GNAT RTL routines.
7322 @node Search Paths and the Run-Time Library (RTL)
7323 @section Search Paths and the Run-Time Library (RTL)
7326 With the GNAT source-based library system, the compiler must be able to
7327 find source files for units that are needed by the unit being compiled.
7328 Search paths are used to guide this process.
7330 The compiler compiles one source file whose name must be given
7331 explicitly on the command line. In other words, no searching is done
7332 for this file. To find all other source files that are needed (the most
7333 common being the specs of units), the compiler examines the following
7334 directories, in the following order:
7338 The directory containing the source file of the main unit being compiled
7339 (the file name on the command line).
7342 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7343 @command{gcc} command line, in the order given.
7346 @findex ADA_PRJ_INCLUDE_FILE
7347 Each of the directories listed in the text file whose name is given
7348 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7351 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7352 driver when project files are used. It should not normally be set
7356 @findex ADA_INCLUDE_PATH
7357 Each of the directories listed in the value of the
7358 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7360 Construct this value
7361 exactly as the @env{PATH} environment variable: a list of directory
7362 names separated by colons (semicolons when working with the NT version).
7365 Normally, define this value as a logical name containing a comma separated
7366 list of directory names.
7368 This variable can also be defined by means of an environment string
7369 (an argument to the HP C exec* set of functions).
7373 DEFINE ANOTHER_PATH FOO:[BAG]
7374 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7377 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7378 first, followed by the standard Ada
7379 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7380 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7381 (Text_IO, Sequential_IO, etc)
7382 instead of the standard Ada packages. Thus, in order to get the standard Ada
7383 packages by default, ADA_INCLUDE_PATH must be redefined.
7387 The content of the @file{ada_source_path} file which is part of the GNAT
7388 installation tree and is used to store standard libraries such as the
7389 GNAT Run Time Library (RTL) source files.
7391 @ref{Installing a library}
7396 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7397 inhibits the use of the directory
7398 containing the source file named in the command line. You can still
7399 have this directory on your search path, but in this case it must be
7400 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7402 Specifying the switch @option{-nostdinc}
7403 inhibits the search of the default location for the GNAT Run Time
7404 Library (RTL) source files.
7406 The compiler outputs its object files and ALI files in the current
7409 Caution: The object file can be redirected with the @option{-o} switch;
7410 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7411 so the @file{ALI} file will not go to the right place. Therefore, you should
7412 avoid using the @option{-o} switch.
7416 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7417 children make up the GNAT RTL, together with the simple @code{System.IO}
7418 package used in the @code{"Hello World"} example. The sources for these units
7419 are needed by the compiler and are kept together in one directory. Not
7420 all of the bodies are needed, but all of the sources are kept together
7421 anyway. In a normal installation, you need not specify these directory
7422 names when compiling or binding. Either the environment variables or
7423 the built-in defaults cause these files to be found.
7425 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7426 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7427 consisting of child units of @code{GNAT}. This is a collection of generally
7428 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7429 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7431 Besides simplifying access to the RTL, a major use of search paths is
7432 in compiling sources from multiple directories. This can make
7433 development environments much more flexible.
7435 @node Order of Compilation Issues
7436 @section Order of Compilation Issues
7439 If, in our earlier example, there was a spec for the @code{hello}
7440 procedure, it would be contained in the file @file{hello.ads}; yet this
7441 file would not have to be explicitly compiled. This is the result of the
7442 model we chose to implement library management. Some of the consequences
7443 of this model are as follows:
7447 There is no point in compiling specs (except for package
7448 specs with no bodies) because these are compiled as needed by clients. If
7449 you attempt a useless compilation, you will receive an error message.
7450 It is also useless to compile subunits because they are compiled as needed
7454 There are no order of compilation requirements: performing a
7455 compilation never obsoletes anything. The only way you can obsolete
7456 something and require recompilations is to modify one of the
7457 source files on which it depends.
7460 There is no library as such, apart from the ALI files
7461 (@pxref{The Ada Library Information Files}, for information on the format
7462 of these files). For now we find it convenient to create separate ALI files,
7463 but eventually the information therein may be incorporated into the object
7467 When you compile a unit, the source files for the specs of all units
7468 that it @code{with}'s, all its subunits, and the bodies of any generics it
7469 instantiates must be available (reachable by the search-paths mechanism
7470 described above), or you will receive a fatal error message.
7477 The following are some typical Ada compilation command line examples:
7480 @item $ gcc -c xyz.adb
7481 Compile body in file @file{xyz.adb} with all default options.
7484 @item $ gcc -c -O2 -gnata xyz-def.adb
7487 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7490 Compile the child unit package in file @file{xyz-def.adb} with extensive
7491 optimizations, and pragma @code{Assert}/@code{Debug} statements
7494 @item $ gcc -c -gnatc abc-def.adb
7495 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7499 @node Binding Using gnatbind
7500 @chapter Binding Using @code{gnatbind}
7504 * Running gnatbind::
7505 * Switches for gnatbind::
7506 * Command-Line Access::
7507 * Search Paths for gnatbind::
7508 * Examples of gnatbind Usage::
7512 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7513 to bind compiled GNAT objects.
7515 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7516 driver (see @ref{The GNAT Driver and Project Files}).
7518 The @code{gnatbind} program performs four separate functions:
7522 Checks that a program is consistent, in accordance with the rules in
7523 Chapter 10 of the Ada Reference Manual. In particular, error
7524 messages are generated if a program uses inconsistent versions of a
7528 Checks that an acceptable order of elaboration exists for the program
7529 and issues an error message if it cannot find an order of elaboration
7530 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7533 Generates a main program incorporating the given elaboration order.
7534 This program is a small Ada package (body and spec) that
7535 must be subsequently compiled
7536 using the GNAT compiler. The necessary compilation step is usually
7537 performed automatically by @command{gnatlink}. The two most important
7538 functions of this program
7539 are to call the elaboration routines of units in an appropriate order
7540 and to call the main program.
7543 Determines the set of object files required by the given main program.
7544 This information is output in the forms of comments in the generated program,
7545 to be read by the @command{gnatlink} utility used to link the Ada application.
7548 @node Running gnatbind
7549 @section Running @code{gnatbind}
7552 The form of the @code{gnatbind} command is
7555 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7559 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7560 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7561 package in two files whose names are
7562 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7563 For example, if given the
7564 parameter @file{hello.ali}, for a main program contained in file
7565 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7566 and @file{b~hello.adb}.
7568 When doing consistency checking, the binder takes into consideration
7569 any source files it can locate. For example, if the binder determines
7570 that the given main program requires the package @code{Pack}, whose
7572 file is @file{pack.ali} and whose corresponding source spec file is
7573 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7574 (using the same search path conventions as previously described for the
7575 @command{gcc} command). If it can locate this source file, it checks that
7577 or source checksums of the source and its references to in @file{ALI} files
7578 match. In other words, any @file{ALI} files that mentions this spec must have
7579 resulted from compiling this version of the source file (or in the case
7580 where the source checksums match, a version close enough that the
7581 difference does not matter).
7583 @cindex Source files, use by binder
7584 The effect of this consistency checking, which includes source files, is
7585 that the binder ensures that the program is consistent with the latest
7586 version of the source files that can be located at bind time. Editing a
7587 source file without compiling files that depend on the source file cause
7588 error messages to be generated by the binder.
7590 For example, suppose you have a main program @file{hello.adb} and a
7591 package @code{P}, from file @file{p.ads} and you perform the following
7596 Enter @code{gcc -c hello.adb} to compile the main program.
7599 Enter @code{gcc -c p.ads} to compile package @code{P}.
7602 Edit file @file{p.ads}.
7605 Enter @code{gnatbind hello}.
7609 At this point, the file @file{p.ali} contains an out-of-date time stamp
7610 because the file @file{p.ads} has been edited. The attempt at binding
7611 fails, and the binder generates the following error messages:
7614 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7615 error: "p.ads" has been modified and must be recompiled
7619 Now both files must be recompiled as indicated, and then the bind can
7620 succeed, generating a main program. You need not normally be concerned
7621 with the contents of this file, but for reference purposes a sample
7622 binder output file is given in @ref{Example of Binder Output File}.
7624 In most normal usage, the default mode of @command{gnatbind} which is to
7625 generate the main package in Ada, as described in the previous section.
7626 In particular, this means that any Ada programmer can read and understand
7627 the generated main program. It can also be debugged just like any other
7628 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7629 @command{gnatbind} and @command{gnatlink}.
7631 However for some purposes it may be convenient to generate the main
7632 program in C rather than Ada. This may for example be helpful when you
7633 are generating a mixed language program with the main program in C. The
7634 GNAT compiler itself is an example.
7635 The use of the @option{^-C^/BIND_FILE=C^} switch
7636 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7637 be generated in C (and compiled using the gnu C compiler).
7639 @node Switches for gnatbind
7640 @section Switches for @command{gnatbind}
7643 The following switches are available with @code{gnatbind}; details will
7644 be presented in subsequent sections.
7647 * Consistency-Checking Modes::
7648 * Binder Error Message Control::
7649 * Elaboration Control::
7651 * Binding with Non-Ada Main Programs::
7652 * Binding Programs with No Main Subprogram::
7659 @cindex @option{--version} @command{gnatbind}
7660 Display Copyright and version, then exit disregarding all other options.
7663 @cindex @option{--help} @command{gnatbind}
7664 If @option{--version} was not used, display usage, then exit disregarding
7668 @cindex @option{-a} @command{gnatbind}
7669 Indicates that, if supported by the platform, the adainit procedure should
7670 be treated as an initialisation routine by the linker (a constructor). This
7671 is intended to be used by the Project Manager to automatically initialize
7672 shared Stand-Alone Libraries.
7674 @item ^-aO^/OBJECT_SEARCH^
7675 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7676 Specify directory to be searched for ALI files.
7678 @item ^-aI^/SOURCE_SEARCH^
7679 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7680 Specify directory to be searched for source file.
7682 @item ^-A^/BIND_FILE=ADA^
7683 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7684 Generate binder program in Ada (default)
7686 @item ^-b^/REPORT_ERRORS=BRIEF^
7687 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7688 Generate brief messages to @file{stderr} even if verbose mode set.
7690 @item ^-c^/NOOUTPUT^
7691 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7692 Check only, no generation of binder output file.
7694 @item ^-C^/BIND_FILE=C^
7695 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7696 Generate binder program in C
7698 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7699 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7700 This switch can be used to change the default task stack size value
7701 to a specified size @var{nn}, which is expressed in bytes by default, or
7702 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7704 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7705 in effect, to completing all task specs with
7706 @smallexample @c ada
7707 pragma Storage_Size (nn);
7709 When they do not already have such a pragma.
7711 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7712 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7713 This switch can be used to change the default secondary stack size value
7714 to a specified size @var{nn}, which is expressed in bytes by default, or
7715 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7718 The secondary stack is used to deal with functions that return a variable
7719 sized result, for example a function returning an unconstrained
7720 String. There are two ways in which this secondary stack is allocated.
7722 For most targets, the secondary stack is growing on demand and is allocated
7723 as a chain of blocks in the heap. The -D option is not very
7724 relevant. It only give some control over the size of the allocated
7725 blocks (whose size is the minimum of the default secondary stack size value,
7726 and the actual size needed for the current allocation request).
7728 For certain targets, notably VxWorks 653,
7729 the secondary stack is allocated by carving off a fixed ratio chunk of the
7730 primary task stack. The -D option is used to define the
7731 size of the environment task's secondary stack.
7733 @item ^-e^/ELABORATION_DEPENDENCIES^
7734 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7735 Output complete list of elaboration-order dependencies.
7737 @item ^-E^/STORE_TRACEBACKS^
7738 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7739 Store tracebacks in exception occurrences when the target supports it.
7740 This is the default with the zero cost exception mechanism.
7742 @c The following may get moved to an appendix
7743 This option is currently supported on the following targets:
7744 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7746 See also the packages @code{GNAT.Traceback} and
7747 @code{GNAT.Traceback.Symbolic} for more information.
7749 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7750 @command{gcc} option.
7753 @item ^-F^/FORCE_ELABS_FLAGS^
7754 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7755 Force the checks of elaboration flags. @command{gnatbind} does not normally
7756 generate checks of elaboration flags for the main executable, except when
7757 a Stand-Alone Library is used. However, there are cases when this cannot be
7758 detected by gnatbind. An example is importing an interface of a Stand-Alone
7759 Library through a pragma Import and only specifying through a linker switch
7760 this Stand-Alone Library. This switch is used to guarantee that elaboration
7761 flag checks are generated.
7764 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7765 Output usage (help) information
7768 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7769 Specify directory to be searched for source and ALI files.
7771 @item ^-I-^/NOCURRENT_DIRECTORY^
7772 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7773 Do not look for sources in the current directory where @code{gnatbind} was
7774 invoked, and do not look for ALI files in the directory containing the
7775 ALI file named in the @code{gnatbind} command line.
7777 @item ^-l^/ORDER_OF_ELABORATION^
7778 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7779 Output chosen elaboration order.
7781 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
7782 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7783 Bind the units for library building. In this case the adainit and
7784 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7785 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
7786 ^@var{xxx}final^@var{XXX}FINAL^.
7787 Implies ^-n^/NOCOMPILE^.
7789 (@xref{GNAT and Libraries}, for more details.)
7792 On OpenVMS, these init and final procedures are exported in uppercase
7793 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7794 the init procedure will be "TOTOINIT" and the exported name of the final
7795 procedure will be "TOTOFINAL".
7798 @item ^-Mxyz^/RENAME_MAIN=xyz^
7799 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7800 Rename generated main program from main to xyz. This option is
7801 supported on cross environments only.
7803 @item ^-m^/ERROR_LIMIT=^@var{n}
7804 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7805 Limit number of detected errors to @var{n}, where @var{n} is
7806 in the range 1..999_999. The default value if no switch is
7807 given is 9999. Binding is terminated if the limit is exceeded.
7809 Furthermore, under Windows, the sources pointed to by the libraries path
7810 set in the registry are not searched for.
7814 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7818 @cindex @option{-nostdinc} (@command{gnatbind})
7819 Do not look for sources in the system default directory.
7822 @cindex @option{-nostdlib} (@command{gnatbind})
7823 Do not look for library files in the system default directory.
7825 @item --RTS=@var{rts-path}
7826 @cindex @option{--RTS} (@code{gnatbind})
7827 Specifies the default location of the runtime library. Same meaning as the
7828 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7830 @item ^-o ^/OUTPUT=^@var{file}
7831 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7832 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7833 Note that if this option is used, then linking must be done manually,
7834 gnatlink cannot be used.
7836 @item ^-O^/OBJECT_LIST^
7837 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7840 @item ^-p^/PESSIMISTIC_ELABORATION^
7841 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7842 Pessimistic (worst-case) elaboration order
7845 @cindex @option{^-R^-R^} (@command{gnatbind})
7846 Output closure source list.
7848 @item ^-s^/READ_SOURCES=ALL^
7849 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7850 Require all source files to be present.
7852 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7853 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7854 Specifies the value to be used when detecting uninitialized scalar
7855 objects with pragma Initialize_Scalars.
7856 The @var{xxx} ^string specified with the switch^option^ may be either
7858 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7859 @item ``@option{^lo^LOW^}'' for the lowest possible value
7860 @item ``@option{^hi^HIGH^}'' for the highest possible value
7861 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
7862 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
7865 In addition, you can specify @option{-Sev} to indicate that the value is
7866 to be set at run time. In this case, the program will look for an environment
7867 @cindex GNAT_INIT_SCALARS
7868 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
7869 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
7870 If no environment variable is found, or if it does not have a valid value,
7871 then the default is @option{in} (invalid values).
7875 @cindex @option{-static} (@code{gnatbind})
7876 Link against a static GNAT run time.
7879 @cindex @option{-shared} (@code{gnatbind})
7880 Link against a shared GNAT run time when available.
7883 @item ^-t^/NOTIME_STAMP_CHECK^
7884 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7885 Tolerate time stamp and other consistency errors
7887 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7888 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7889 Set the time slice value to @var{n} milliseconds. If the system supports
7890 the specification of a specific time slice value, then the indicated value
7891 is used. If the system does not support specific time slice values, but
7892 does support some general notion of round-robin scheduling, then any
7893 nonzero value will activate round-robin scheduling.
7895 A value of zero is treated specially. It turns off time
7896 slicing, and in addition, indicates to the tasking run time that the
7897 semantics should match as closely as possible the Annex D
7898 requirements of the Ada RM, and in particular sets the default
7899 scheduling policy to @code{FIFO_Within_Priorities}.
7901 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7902 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7903 Enable dynamic stack usage, with @var{n} results stored and displayed
7904 at program termination. A result is generated when a task
7905 terminates. Results that can't be stored are displayed on the fly, at
7906 task termination. This option is currently not supported on Itanium
7907 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7909 @item ^-v^/REPORT_ERRORS=VERBOSE^
7910 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7911 Verbose mode. Write error messages, header, summary output to
7916 @cindex @option{-w} (@code{gnatbind})
7917 Warning mode (@var{x}=s/e for suppress/treat as error)
7921 @item /WARNINGS=NORMAL
7922 @cindex @option{/WARNINGS} (@code{gnatbind})
7923 Normal warnings mode. Warnings are issued but ignored
7925 @item /WARNINGS=SUPPRESS
7926 @cindex @option{/WARNINGS} (@code{gnatbind})
7927 All warning messages are suppressed
7929 @item /WARNINGS=ERROR
7930 @cindex @option{/WARNINGS} (@code{gnatbind})
7931 Warning messages are treated as fatal errors
7934 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7935 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7936 Override default wide character encoding for standard Text_IO files.
7938 @item ^-x^/READ_SOURCES=NONE^
7939 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7940 Exclude source files (check object consistency only).
7943 @item /READ_SOURCES=AVAILABLE
7944 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7945 Default mode, in which sources are checked for consistency only if
7949 @item ^-y^/ENABLE_LEAP_SECONDS^
7950 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7951 Enable leap seconds support in @code{Ada.Calendar} and its children.
7953 @item ^-z^/ZERO_MAIN^
7954 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7960 You may obtain this listing of switches by running @code{gnatbind} with
7964 @node Consistency-Checking Modes
7965 @subsection Consistency-Checking Modes
7968 As described earlier, by default @code{gnatbind} checks
7969 that object files are consistent with one another and are consistent
7970 with any source files it can locate. The following switches control binder
7975 @item ^-s^/READ_SOURCES=ALL^
7976 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7977 Require source files to be present. In this mode, the binder must be
7978 able to locate all source files that are referenced, in order to check
7979 their consistency. In normal mode, if a source file cannot be located it
7980 is simply ignored. If you specify this switch, a missing source
7983 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7984 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7985 Override default wide character encoding for standard Text_IO files.
7986 Normally the default wide character encoding method used for standard
7987 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
7988 the main source input (see description of switch
7989 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
7990 use of this switch for the binder (which has the same set of
7991 possible arguments) overrides this default as specified.
7993 @item ^-x^/READ_SOURCES=NONE^
7994 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7995 Exclude source files. In this mode, the binder only checks that ALI
7996 files are consistent with one another. Source files are not accessed.
7997 The binder runs faster in this mode, and there is still a guarantee that
7998 the resulting program is self-consistent.
7999 If a source file has been edited since it was last compiled, and you
8000 specify this switch, the binder will not detect that the object
8001 file is out of date with respect to the source file. Note that this is the
8002 mode that is automatically used by @command{gnatmake} because in this
8003 case the checking against sources has already been performed by
8004 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8007 @item /READ_SOURCES=AVAILABLE
8008 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8009 This is the default mode in which source files are checked if they are
8010 available, and ignored if they are not available.
8014 @node Binder Error Message Control
8015 @subsection Binder Error Message Control
8018 The following switches provide control over the generation of error
8019 messages from the binder:
8023 @item ^-v^/REPORT_ERRORS=VERBOSE^
8024 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8025 Verbose mode. In the normal mode, brief error messages are generated to
8026 @file{stderr}. If this switch is present, a header is written
8027 to @file{stdout} and any error messages are directed to @file{stdout}.
8028 All that is written to @file{stderr} is a brief summary message.
8030 @item ^-b^/REPORT_ERRORS=BRIEF^
8031 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8032 Generate brief error messages to @file{stderr} even if verbose mode is
8033 specified. This is relevant only when used with the
8034 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8038 @cindex @option{-m} (@code{gnatbind})
8039 Limits the number of error messages to @var{n}, a decimal integer in the
8040 range 1-999. The binder terminates immediately if this limit is reached.
8043 @cindex @option{-M} (@code{gnatbind})
8044 Renames the generated main program from @code{main} to @code{xxx}.
8045 This is useful in the case of some cross-building environments, where
8046 the actual main program is separate from the one generated
8050 @item ^-ws^/WARNINGS=SUPPRESS^
8051 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8053 Suppress all warning messages.
8055 @item ^-we^/WARNINGS=ERROR^
8056 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8057 Treat any warning messages as fatal errors.
8060 @item /WARNINGS=NORMAL
8061 Standard mode with warnings generated, but warnings do not get treated
8065 @item ^-t^/NOTIME_STAMP_CHECK^
8066 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8067 @cindex Time stamp checks, in binder
8068 @cindex Binder consistency checks
8069 @cindex Consistency checks, in binder
8070 The binder performs a number of consistency checks including:
8074 Check that time stamps of a given source unit are consistent
8076 Check that checksums of a given source unit are consistent
8078 Check that consistent versions of @code{GNAT} were used for compilation
8080 Check consistency of configuration pragmas as required
8084 Normally failure of such checks, in accordance with the consistency
8085 requirements of the Ada Reference Manual, causes error messages to be
8086 generated which abort the binder and prevent the output of a binder
8087 file and subsequent link to obtain an executable.
8089 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8090 into warnings, so that
8091 binding and linking can continue to completion even in the presence of such
8092 errors. The result may be a failed link (due to missing symbols), or a
8093 non-functional executable which has undefined semantics.
8094 @emph{This means that
8095 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8099 @node Elaboration Control
8100 @subsection Elaboration Control
8103 The following switches provide additional control over the elaboration
8104 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8107 @item ^-p^/PESSIMISTIC_ELABORATION^
8108 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8109 Normally the binder attempts to choose an elaboration order that is
8110 likely to minimize the likelihood of an elaboration order error resulting
8111 in raising a @code{Program_Error} exception. This switch reverses the
8112 action of the binder, and requests that it deliberately choose an order
8113 that is likely to maximize the likelihood of an elaboration error.
8114 This is useful in ensuring portability and avoiding dependence on
8115 accidental fortuitous elaboration ordering.
8117 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8119 elaboration checking is used (@option{-gnatE} switch used for compilation).
8120 This is because in the default static elaboration mode, all necessary
8121 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8122 These implicit pragmas are still respected by the binder in
8123 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8124 safe elaboration order is assured.
8127 @node Output Control
8128 @subsection Output Control
8131 The following switches allow additional control over the output
8132 generated by the binder.
8137 @item ^-A^/BIND_FILE=ADA^
8138 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8139 Generate binder program in Ada (default). The binder program is named
8140 @file{b~@var{mainprog}.adb} by default. This can be changed with
8141 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8143 @item ^-c^/NOOUTPUT^
8144 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8145 Check only. Do not generate the binder output file. In this mode the
8146 binder performs all error checks but does not generate an output file.
8148 @item ^-C^/BIND_FILE=C^
8149 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8150 Generate binder program in C. The binder program is named
8151 @file{b_@var{mainprog}.c}.
8152 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8155 @item ^-e^/ELABORATION_DEPENDENCIES^
8156 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8157 Output complete list of elaboration-order dependencies, showing the
8158 reason for each dependency. This output can be rather extensive but may
8159 be useful in diagnosing problems with elaboration order. The output is
8160 written to @file{stdout}.
8163 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8164 Output usage information. The output is written to @file{stdout}.
8166 @item ^-K^/LINKER_OPTION_LIST^
8167 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8168 Output linker options to @file{stdout}. Includes library search paths,
8169 contents of pragmas Ident and Linker_Options, and libraries added
8172 @item ^-l^/ORDER_OF_ELABORATION^
8173 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8174 Output chosen elaboration order. The output is written to @file{stdout}.
8176 @item ^-O^/OBJECT_LIST^
8177 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8178 Output full names of all the object files that must be linked to provide
8179 the Ada component of the program. The output is written to @file{stdout}.
8180 This list includes the files explicitly supplied and referenced by the user
8181 as well as implicitly referenced run-time unit files. The latter are
8182 omitted if the corresponding units reside in shared libraries. The
8183 directory names for the run-time units depend on the system configuration.
8185 @item ^-o ^/OUTPUT=^@var{file}
8186 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8187 Set name of output file to @var{file} instead of the normal
8188 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8189 binder generated body filename. In C mode you would normally give
8190 @var{file} an extension of @file{.c} because it will be a C source program.
8191 Note that if this option is used, then linking must be done manually.
8192 It is not possible to use gnatlink in this case, since it cannot locate
8195 @item ^-r^/RESTRICTION_LIST^
8196 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8197 Generate list of @code{pragma Restrictions} that could be applied to
8198 the current unit. This is useful for code audit purposes, and also may
8199 be used to improve code generation in some cases.
8203 @node Binding with Non-Ada Main Programs
8204 @subsection Binding with Non-Ada Main Programs
8207 In our description so far we have assumed that the main
8208 program is in Ada, and that the task of the binder is to generate a
8209 corresponding function @code{main} that invokes this Ada main
8210 program. GNAT also supports the building of executable programs where
8211 the main program is not in Ada, but some of the called routines are
8212 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8213 The following switch is used in this situation:
8217 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8218 No main program. The main program is not in Ada.
8222 In this case, most of the functions of the binder are still required,
8223 but instead of generating a main program, the binder generates a file
8224 containing the following callable routines:
8229 You must call this routine to initialize the Ada part of the program by
8230 calling the necessary elaboration routines. A call to @code{adainit} is
8231 required before the first call to an Ada subprogram.
8233 Note that it is assumed that the basic execution environment must be setup
8234 to be appropriate for Ada execution at the point where the first Ada
8235 subprogram is called. In particular, if the Ada code will do any
8236 floating-point operations, then the FPU must be setup in an appropriate
8237 manner. For the case of the x86, for example, full precision mode is
8238 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8239 that the FPU is in the right state.
8243 You must call this routine to perform any library-level finalization
8244 required by the Ada subprograms. A call to @code{adafinal} is required
8245 after the last call to an Ada subprogram, and before the program
8250 If the @option{^-n^/NOMAIN^} switch
8251 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8252 @cindex Binder, multiple input files
8253 is given, more than one ALI file may appear on
8254 the command line for @code{gnatbind}. The normal @dfn{closure}
8255 calculation is performed for each of the specified units. Calculating
8256 the closure means finding out the set of units involved by tracing
8257 @code{with} references. The reason it is necessary to be able to
8258 specify more than one ALI file is that a given program may invoke two or
8259 more quite separate groups of Ada units.
8261 The binder takes the name of its output file from the last specified ALI
8262 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8263 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8264 The output is an Ada unit in source form that can
8265 be compiled with GNAT unless the -C switch is used in which case the
8266 output is a C source file, which must be compiled using the C compiler.
8267 This compilation occurs automatically as part of the @command{gnatlink}
8270 Currently the GNAT run time requires a FPU using 80 bits mode
8271 precision. Under targets where this is not the default it is required to
8272 call GNAT.Float_Control.Reset before using floating point numbers (this
8273 include float computation, float input and output) in the Ada code. A
8274 side effect is that this could be the wrong mode for the foreign code
8275 where floating point computation could be broken after this call.
8277 @node Binding Programs with No Main Subprogram
8278 @subsection Binding Programs with No Main Subprogram
8281 It is possible to have an Ada program which does not have a main
8282 subprogram. This program will call the elaboration routines of all the
8283 packages, then the finalization routines.
8285 The following switch is used to bind programs organized in this manner:
8288 @item ^-z^/ZERO_MAIN^
8289 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8290 Normally the binder checks that the unit name given on the command line
8291 corresponds to a suitable main subprogram. When this switch is used,
8292 a list of ALI files can be given, and the execution of the program
8293 consists of elaboration of these units in an appropriate order. Note
8294 that the default wide character encoding method for standard Text_IO
8295 files is always set to Brackets if this switch is set (you can use
8297 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8300 @node Command-Line Access
8301 @section Command-Line Access
8304 The package @code{Ada.Command_Line} provides access to the command-line
8305 arguments and program name. In order for this interface to operate
8306 correctly, the two variables
8318 are declared in one of the GNAT library routines. These variables must
8319 be set from the actual @code{argc} and @code{argv} values passed to the
8320 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8321 generates the C main program to automatically set these variables.
8322 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8323 set these variables. If they are not set, the procedures in
8324 @code{Ada.Command_Line} will not be available, and any attempt to use
8325 them will raise @code{Constraint_Error}. If command line access is
8326 required, your main program must set @code{gnat_argc} and
8327 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8330 @node Search Paths for gnatbind
8331 @section Search Paths for @code{gnatbind}
8334 The binder takes the name of an ALI file as its argument and needs to
8335 locate source files as well as other ALI files to verify object consistency.
8337 For source files, it follows exactly the same search rules as @command{gcc}
8338 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8339 directories searched are:
8343 The directory containing the ALI file named in the command line, unless
8344 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8347 All directories specified by @option{^-I^/SEARCH^}
8348 switches on the @code{gnatbind}
8349 command line, in the order given.
8352 @findex ADA_PRJ_OBJECTS_FILE
8353 Each of the directories listed in the text file whose name is given
8354 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8357 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8358 driver when project files are used. It should not normally be set
8362 @findex ADA_OBJECTS_PATH
8363 Each of the directories listed in the value of the
8364 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8366 Construct this value
8367 exactly as the @env{PATH} environment variable: a list of directory
8368 names separated by colons (semicolons when working with the NT version
8372 Normally, define this value as a logical name containing a comma separated
8373 list of directory names.
8375 This variable can also be defined by means of an environment string
8376 (an argument to the HP C exec* set of functions).
8380 DEFINE ANOTHER_PATH FOO:[BAG]
8381 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8384 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8385 first, followed by the standard Ada
8386 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8387 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8388 (Text_IO, Sequential_IO, etc)
8389 instead of the standard Ada packages. Thus, in order to get the standard Ada
8390 packages by default, ADA_OBJECTS_PATH must be redefined.
8394 The content of the @file{ada_object_path} file which is part of the GNAT
8395 installation tree and is used to store standard libraries such as the
8396 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8399 @ref{Installing a library}
8404 In the binder the switch @option{^-I^/SEARCH^}
8405 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8406 is used to specify both source and
8407 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8408 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8409 instead if you want to specify
8410 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8411 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8412 if you want to specify library paths
8413 only. This means that for the binder
8414 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8415 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8416 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8417 The binder generates the bind file (a C language source file) in the
8418 current working directory.
8424 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8425 children make up the GNAT Run-Time Library, together with the package
8426 GNAT and its children, which contain a set of useful additional
8427 library functions provided by GNAT. The sources for these units are
8428 needed by the compiler and are kept together in one directory. The ALI
8429 files and object files generated by compiling the RTL are needed by the
8430 binder and the linker and are kept together in one directory, typically
8431 different from the directory containing the sources. In a normal
8432 installation, you need not specify these directory names when compiling
8433 or binding. Either the environment variables or the built-in defaults
8434 cause these files to be found.
8436 Besides simplifying access to the RTL, a major use of search paths is
8437 in compiling sources from multiple directories. This can make
8438 development environments much more flexible.
8440 @node Examples of gnatbind Usage
8441 @section Examples of @code{gnatbind} Usage
8444 This section contains a number of examples of using the GNAT binding
8445 utility @code{gnatbind}.
8448 @item gnatbind hello
8449 The main program @code{Hello} (source program in @file{hello.adb}) is
8450 bound using the standard switch settings. The generated main program is
8451 @file{b~hello.adb}. This is the normal, default use of the binder.
8454 @item gnatbind hello -o mainprog.adb
8457 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8459 The main program @code{Hello} (source program in @file{hello.adb}) is
8460 bound using the standard switch settings. The generated main program is
8461 @file{mainprog.adb} with the associated spec in
8462 @file{mainprog.ads}. Note that you must specify the body here not the
8463 spec, in the case where the output is in Ada. Note that if this option
8464 is used, then linking must be done manually, since gnatlink will not
8465 be able to find the generated file.
8468 @item gnatbind main -C -o mainprog.c -x
8471 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8473 The main program @code{Main} (source program in
8474 @file{main.adb}) is bound, excluding source files from the
8475 consistency checking, generating
8476 the file @file{mainprog.c}.
8479 @item gnatbind -x main_program -C -o mainprog.c
8480 This command is exactly the same as the previous example. Switches may
8481 appear anywhere in the command line, and single letter switches may be
8482 combined into a single switch.
8486 @item gnatbind -n math dbase -C -o ada-control.c
8489 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8491 The main program is in a language other than Ada, but calls to
8492 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8493 to @code{gnatbind} generates the file @file{ada-control.c} containing
8494 the @code{adainit} and @code{adafinal} routines to be called before and
8495 after accessing the Ada units.
8498 @c ------------------------------------
8499 @node Linking Using gnatlink
8500 @chapter Linking Using @command{gnatlink}
8501 @c ------------------------------------
8505 This chapter discusses @command{gnatlink}, a tool that links
8506 an Ada program and builds an executable file. This utility
8507 invokes the system linker ^(via the @command{gcc} command)^^
8508 with a correct list of object files and library references.
8509 @command{gnatlink} automatically determines the list of files and
8510 references for the Ada part of a program. It uses the binder file
8511 generated by the @command{gnatbind} to determine this list.
8513 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8514 driver (see @ref{The GNAT Driver and Project Files}).
8517 * Running gnatlink::
8518 * Switches for gnatlink::
8521 @node Running gnatlink
8522 @section Running @command{gnatlink}
8525 The form of the @command{gnatlink} command is
8528 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8529 @ovar{non-Ada objects} @ovar{linker options}
8533 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8535 or linker options) may be in any order, provided that no non-Ada object may
8536 be mistaken for a main @file{ALI} file.
8537 Any file name @file{F} without the @file{.ali}
8538 extension will be taken as the main @file{ALI} file if a file exists
8539 whose name is the concatenation of @file{F} and @file{.ali}.
8542 @file{@var{mainprog}.ali} references the ALI file of the main program.
8543 The @file{.ali} extension of this file can be omitted. From this
8544 reference, @command{gnatlink} locates the corresponding binder file
8545 @file{b~@var{mainprog}.adb} and, using the information in this file along
8546 with the list of non-Ada objects and linker options, constructs a
8547 linker command file to create the executable.
8549 The arguments other than the @command{gnatlink} switches and the main
8550 @file{ALI} file are passed to the linker uninterpreted.
8551 They typically include the names of
8552 object files for units written in other languages than Ada and any library
8553 references required to resolve references in any of these foreign language
8554 units, or in @code{Import} pragmas in any Ada units.
8556 @var{linker options} is an optional list of linker specific
8558 The default linker called by gnatlink is @command{gcc} which in
8559 turn calls the appropriate system linker.
8560 Standard options for the linker such as @option{-lmy_lib} or
8561 @option{-Ldir} can be added as is.
8562 For options that are not recognized by
8563 @command{gcc} as linker options, use the @command{gcc} switches
8564 @option{-Xlinker} or @option{-Wl,}.
8565 Refer to the GCC documentation for
8566 details. Here is an example showing how to generate a linker map:
8569 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8572 Using @var{linker options} it is possible to set the program stack and
8575 See @ref{Setting Stack Size from gnatlink} and
8576 @ref{Setting Heap Size from gnatlink}.
8579 @command{gnatlink} determines the list of objects required by the Ada
8580 program and prepends them to the list of objects passed to the linker.
8581 @command{gnatlink} also gathers any arguments set by the use of
8582 @code{pragma Linker_Options} and adds them to the list of arguments
8583 presented to the linker.
8586 @command{gnatlink} accepts the following types of extra files on the command
8587 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8588 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8589 handled according to their extension.
8592 @node Switches for gnatlink
8593 @section Switches for @command{gnatlink}
8596 The following switches are available with the @command{gnatlink} utility:
8602 @cindex @option{--version} @command{gnatlink}
8603 Display Copyright and version, then exit disregarding all other options.
8606 @cindex @option{--help} @command{gnatlink}
8607 If @option{--version} was not used, display usage, then exit disregarding
8610 @item ^-A^/BIND_FILE=ADA^
8611 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8612 The binder has generated code in Ada. This is the default.
8614 @item ^-C^/BIND_FILE=C^
8615 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8616 If instead of generating a file in Ada, the binder has generated one in
8617 C, then the linker needs to know about it. Use this switch to signal
8618 to @command{gnatlink} that the binder has generated C code rather than
8621 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8622 @cindex Command line length
8623 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8624 On some targets, the command line length is limited, and @command{gnatlink}
8625 will generate a separate file for the linker if the list of object files
8627 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8628 to be generated even if
8629 the limit is not exceeded. This is useful in some cases to deal with
8630 special situations where the command line length is exceeded.
8633 @cindex Debugging information, including
8634 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8635 The option to include debugging information causes the Ada bind file (in
8636 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8637 @option{^-g^/DEBUG^}.
8638 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8639 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8640 Without @option{^-g^/DEBUG^}, the binder removes these files by
8641 default. The same procedure apply if a C bind file was generated using
8642 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8643 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8645 @item ^-n^/NOCOMPILE^
8646 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8647 Do not compile the file generated by the binder. This may be used when
8648 a link is rerun with different options, but there is no need to recompile
8652 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8653 Causes additional information to be output, including a full list of the
8654 included object files. This switch option is most useful when you want
8655 to see what set of object files are being used in the link step.
8657 @item ^-v -v^/VERBOSE/VERBOSE^
8658 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8659 Very verbose mode. Requests that the compiler operate in verbose mode when
8660 it compiles the binder file, and that the system linker run in verbose mode.
8662 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8663 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8664 @var{exec-name} specifies an alternate name for the generated
8665 executable program. If this switch is omitted, the executable has the same
8666 name as the main unit. For example, @code{gnatlink try.ali} creates
8667 an executable called @file{^try^TRY.EXE^}.
8670 @item -b @var{target}
8671 @cindex @option{-b} (@command{gnatlink})
8672 Compile your program to run on @var{target}, which is the name of a
8673 system configuration. You must have a GNAT cross-compiler built if
8674 @var{target} is not the same as your host system.
8677 @cindex @option{-B} (@command{gnatlink})
8678 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8679 from @var{dir} instead of the default location. Only use this switch
8680 when multiple versions of the GNAT compiler are available.
8681 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8682 for further details. You would normally use the @option{-b} or
8683 @option{-V} switch instead.
8685 @item --GCC=@var{compiler_name}
8686 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8687 Program used for compiling the binder file. The default is
8688 @command{gcc}. You need to use quotes around @var{compiler_name} if
8689 @code{compiler_name} contains spaces or other separator characters.
8690 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8691 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8692 inserted after your command name. Thus in the above example the compiler
8693 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8694 A limitation of this syntax is that the name and path name of the executable
8695 itself must not include any embedded spaces. If the compiler executable is
8696 different from the default one (gcc or <prefix>-gcc), then the back-end
8697 switches in the ALI file are not used to compile the binder generated source.
8698 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8699 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8700 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8701 is taken into account. However, all the additional switches are also taken
8703 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8704 @option{--GCC="bar -x -y -z -t"}.
8706 @item --LINK=@var{name}
8707 @cindex @option{--LINK=} (@command{gnatlink})
8708 @var{name} is the name of the linker to be invoked. This is especially
8709 useful in mixed language programs since languages such as C++ require
8710 their own linker to be used. When this switch is omitted, the default
8711 name for the linker is @command{gcc}. When this switch is used, the
8712 specified linker is called instead of @command{gcc} with exactly the same
8713 parameters that would have been passed to @command{gcc} so if the desired
8714 linker requires different parameters it is necessary to use a wrapper
8715 script that massages the parameters before invoking the real linker. It
8716 may be useful to control the exact invocation by using the verbose
8722 @item /DEBUG=TRACEBACK
8723 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8724 This qualifier causes sufficient information to be included in the
8725 executable file to allow a traceback, but does not include the full
8726 symbol information needed by the debugger.
8728 @item /IDENTIFICATION="<string>"
8729 @code{"<string>"} specifies the string to be stored in the image file
8730 identification field in the image header.
8731 It overrides any pragma @code{Ident} specified string.
8733 @item /NOINHIBIT-EXEC
8734 Generate the executable file even if there are linker warnings.
8736 @item /NOSTART_FILES
8737 Don't link in the object file containing the ``main'' transfer address.
8738 Used when linking with a foreign language main program compiled with an
8742 Prefer linking with object libraries over sharable images, even without
8748 @node The GNAT Make Program gnatmake
8749 @chapter The GNAT Make Program @command{gnatmake}
8753 * Running gnatmake::
8754 * Switches for gnatmake::
8755 * Mode Switches for gnatmake::
8756 * Notes on the Command Line::
8757 * How gnatmake Works::
8758 * Examples of gnatmake Usage::
8761 A typical development cycle when working on an Ada program consists of
8762 the following steps:
8766 Edit some sources to fix bugs.
8772 Compile all sources affected.
8782 The third step can be tricky, because not only do the modified files
8783 @cindex Dependency rules
8784 have to be compiled, but any files depending on these files must also be
8785 recompiled. The dependency rules in Ada can be quite complex, especially
8786 in the presence of overloading, @code{use} clauses, generics and inlined
8789 @command{gnatmake} automatically takes care of the third and fourth steps
8790 of this process. It determines which sources need to be compiled,
8791 compiles them, and binds and links the resulting object files.
8793 Unlike some other Ada make programs, the dependencies are always
8794 accurately recomputed from the new sources. The source based approach of
8795 the GNAT compilation model makes this possible. This means that if
8796 changes to the source program cause corresponding changes in
8797 dependencies, they will always be tracked exactly correctly by
8800 @node Running gnatmake
8801 @section Running @command{gnatmake}
8804 The usual form of the @command{gnatmake} command is
8807 $ gnatmake @ovar{switches} @var{file_name}
8808 @ovar{file_names} @ovar{mode_switches}
8812 The only required argument is one @var{file_name}, which specifies
8813 a compilation unit that is a main program. Several @var{file_names} can be
8814 specified: this will result in several executables being built.
8815 If @code{switches} are present, they can be placed before the first
8816 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8817 If @var{mode_switches} are present, they must always be placed after
8818 the last @var{file_name} and all @code{switches}.
8820 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
8821 extension may be omitted from the @var{file_name} arguments. However, if
8822 you are using non-standard extensions, then it is required that the
8823 extension be given. A relative or absolute directory path can be
8824 specified in a @var{file_name}, in which case, the input source file will
8825 be searched for in the specified directory only. Otherwise, the input
8826 source file will first be searched in the directory where
8827 @command{gnatmake} was invoked and if it is not found, it will be search on
8828 the source path of the compiler as described in
8829 @ref{Search Paths and the Run-Time Library (RTL)}.
8831 All @command{gnatmake} output (except when you specify
8832 @option{^-M^/DEPENDENCIES_LIST^}) is to
8833 @file{stderr}. The output produced by the
8834 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8837 @node Switches for gnatmake
8838 @section Switches for @command{gnatmake}
8841 You may specify any of the following switches to @command{gnatmake}:
8847 @cindex @option{--version} @command{gnatmake}
8848 Display Copyright and version, then exit disregarding all other options.
8851 @cindex @option{--help} @command{gnatmake}
8852 If @option{--version} was not used, display usage, then exit disregarding
8856 @item --GCC=@var{compiler_name}
8857 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8858 Program used for compiling. The default is `@command{gcc}'. You need to use
8859 quotes around @var{compiler_name} if @code{compiler_name} contains
8860 spaces or other separator characters. As an example @option{--GCC="foo -x
8861 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8862 compiler. A limitation of this syntax is that the name and path name of
8863 the executable itself must not include any embedded spaces. Note that
8864 switch @option{-c} is always inserted after your command name. Thus in the
8865 above example the compiler command that will be used by @command{gnatmake}
8866 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8867 used, only the last @var{compiler_name} is taken into account. However,
8868 all the additional switches are also taken into account. Thus,
8869 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8870 @option{--GCC="bar -x -y -z -t"}.
8872 @item --GNATBIND=@var{binder_name}
8873 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8874 Program used for binding. The default is `@code{gnatbind}'. You need to
8875 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8876 or other separator characters. As an example @option{--GNATBIND="bar -x
8877 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8878 binder. Binder switches that are normally appended by @command{gnatmake}
8879 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8880 A limitation of this syntax is that the name and path name of the executable
8881 itself must not include any embedded spaces.
8883 @item --GNATLINK=@var{linker_name}
8884 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8885 Program used for linking. The default is `@command{gnatlink}'. You need to
8886 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8887 or other separator characters. As an example @option{--GNATLINK="lan -x
8888 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8889 linker. Linker switches that are normally appended by @command{gnatmake} to
8890 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8891 A limitation of this syntax is that the name and path name of the executable
8892 itself must not include any embedded spaces.
8896 @item ^-a^/ALL_FILES^
8897 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8898 Consider all files in the make process, even the GNAT internal system
8899 files (for example, the predefined Ada library files), as well as any
8900 locked files. Locked files are files whose ALI file is write-protected.
8902 @command{gnatmake} does not check these files,
8903 because the assumption is that the GNAT internal files are properly up
8904 to date, and also that any write protected ALI files have been properly
8905 installed. Note that if there is an installation problem, such that one
8906 of these files is not up to date, it will be properly caught by the
8908 You may have to specify this switch if you are working on GNAT
8909 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8910 in conjunction with @option{^-f^/FORCE_COMPILE^}
8911 if you need to recompile an entire application,
8912 including run-time files, using special configuration pragmas,
8913 such as a @code{Normalize_Scalars} pragma.
8916 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8919 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8922 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8925 @item ^-b^/ACTIONS=BIND^
8926 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8927 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8928 compilation and binding, but no link.
8929 Can be combined with @option{^-l^/ACTIONS=LINK^}
8930 to do binding and linking. When not combined with
8931 @option{^-c^/ACTIONS=COMPILE^}
8932 all the units in the closure of the main program must have been previously
8933 compiled and must be up to date. The root unit specified by @var{file_name}
8934 may be given without extension, with the source extension or, if no GNAT
8935 Project File is specified, with the ALI file extension.
8937 @item ^-c^/ACTIONS=COMPILE^
8938 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8939 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8940 is also specified. Do not perform linking, except if both
8941 @option{^-b^/ACTIONS=BIND^} and
8942 @option{^-l^/ACTIONS=LINK^} are also specified.
8943 If the root unit specified by @var{file_name} is not a main unit, this is the
8944 default. Otherwise @command{gnatmake} will attempt binding and linking
8945 unless all objects are up to date and the executable is more recent than
8949 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8950 Use a temporary mapping file. A mapping file is a way to communicate to the
8951 compiler two mappings: from unit names to file names (without any directory
8952 information) and from file names to path names (with full directory
8953 information). These mappings are used by the compiler to short-circuit the path
8954 search. When @command{gnatmake} is invoked with this switch, it will create
8955 a temporary mapping file, initially populated by the project manager,
8956 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8957 Each invocation of the compiler will add the newly accessed sources to the
8958 mapping file. This will improve the source search during the next invocation
8961 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8962 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8963 Use a specific mapping file. The file, specified as a path name (absolute or
8964 relative) by this switch, should already exist, otherwise the switch is
8965 ineffective. The specified mapping file will be communicated to the compiler.
8966 This switch is not compatible with a project file
8967 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8968 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8970 @item ^-d^/DISPLAY_PROGRESS^
8971 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
8972 Display progress for each source, up to date or not, as a single line
8975 completed x out of y (zz%)
8978 If the file needs to be compiled this is displayed after the invocation of
8979 the compiler. These lines are displayed even in quiet output mode.
8981 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8982 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8983 Put all object files and ALI file in directory @var{dir}.
8984 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8985 and ALI files go in the current working directory.
8987 This switch cannot be used when using a project file.
8991 @cindex @option{-eL} (@command{gnatmake})
8992 Follow all symbolic links when processing project files.
8995 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
8996 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
8997 Output the commands for the compiler, the binder and the linker
8998 on ^standard output^SYS$OUTPUT^,
8999 instead of ^standard error^SYS$ERROR^.
9001 @item ^-f^/FORCE_COMPILE^
9002 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9003 Force recompilations. Recompile all sources, even though some object
9004 files may be up to date, but don't recompile predefined or GNAT internal
9005 files or locked files (files with a write-protected ALI file),
9006 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9008 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9009 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9010 When using project files, if some errors or warnings are detected during
9011 parsing and verbose mode is not in effect (no use of switch
9012 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9013 file, rather than its simple file name.
9016 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9017 Enable debugging. This switch is simply passed to the compiler and to the
9020 @item ^-i^/IN_PLACE^
9021 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9022 In normal mode, @command{gnatmake} compiles all object files and ALI files
9023 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9024 then instead object files and ALI files that already exist are overwritten
9025 in place. This means that once a large project is organized into separate
9026 directories in the desired manner, then @command{gnatmake} will automatically
9027 maintain and update this organization. If no ALI files are found on the
9028 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9029 the new object and ALI files are created in the
9030 directory containing the source being compiled. If another organization
9031 is desired, where objects and sources are kept in different directories,
9032 a useful technique is to create dummy ALI files in the desired directories.
9033 When detecting such a dummy file, @command{gnatmake} will be forced to
9034 recompile the corresponding source file, and it will be put the resulting
9035 object and ALI files in the directory where it found the dummy file.
9037 @item ^-j^/PROCESSES=^@var{n}
9038 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9039 @cindex Parallel make
9040 Use @var{n} processes to carry out the (re)compilations. On a
9041 multiprocessor machine compilations will occur in parallel. In the
9042 event of compilation errors, messages from various compilations might
9043 get interspersed (but @command{gnatmake} will give you the full ordered
9044 list of failing compiles at the end). If this is problematic, rerun
9045 the make process with n set to 1 to get a clean list of messages.
9047 @item ^-k^/CONTINUE_ON_ERROR^
9048 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9049 Keep going. Continue as much as possible after a compilation error. To
9050 ease the programmer's task in case of compilation errors, the list of
9051 sources for which the compile fails is given when @command{gnatmake}
9054 If @command{gnatmake} is invoked with several @file{file_names} and with this
9055 switch, if there are compilation errors when building an executable,
9056 @command{gnatmake} will not attempt to build the following executables.
9058 @item ^-l^/ACTIONS=LINK^
9059 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9060 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9061 and linking. Linking will not be performed if combined with
9062 @option{^-c^/ACTIONS=COMPILE^}
9063 but not with @option{^-b^/ACTIONS=BIND^}.
9064 When not combined with @option{^-b^/ACTIONS=BIND^}
9065 all the units in the closure of the main program must have been previously
9066 compiled and must be up to date, and the main program needs to have been bound.
9067 The root unit specified by @var{file_name}
9068 may be given without extension, with the source extension or, if no GNAT
9069 Project File is specified, with the ALI file extension.
9071 @item ^-m^/MINIMAL_RECOMPILATION^
9072 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9073 Specify that the minimum necessary amount of recompilations
9074 be performed. In this mode @command{gnatmake} ignores time
9075 stamp differences when the only
9076 modifications to a source file consist in adding/removing comments,
9077 empty lines, spaces or tabs. This means that if you have changed the
9078 comments in a source file or have simply reformatted it, using this
9079 switch will tell @command{gnatmake} not to recompile files that depend on it
9080 (provided other sources on which these files depend have undergone no
9081 semantic modifications). Note that the debugging information may be
9082 out of date with respect to the sources if the @option{-m} switch causes
9083 a compilation to be switched, so the use of this switch represents a
9084 trade-off between compilation time and accurate debugging information.
9086 @item ^-M^/DEPENDENCIES_LIST^
9087 @cindex Dependencies, producing list
9088 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9089 Check if all objects are up to date. If they are, output the object
9090 dependences to @file{stdout} in a form that can be directly exploited in
9091 a @file{Makefile}. By default, each source file is prefixed with its
9092 (relative or absolute) directory name. This name is whatever you
9093 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9094 and @option{^-I^/SEARCH^} switches. If you use
9095 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9096 @option{^-q^/QUIET^}
9097 (see below), only the source file names,
9098 without relative paths, are output. If you just specify the
9099 @option{^-M^/DEPENDENCIES_LIST^}
9100 switch, dependencies of the GNAT internal system files are omitted. This
9101 is typically what you want. If you also specify
9102 the @option{^-a^/ALL_FILES^} switch,
9103 dependencies of the GNAT internal files are also listed. Note that
9104 dependencies of the objects in external Ada libraries (see switch
9105 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9108 @item ^-n^/DO_OBJECT_CHECK^
9109 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9110 Don't compile, bind, or link. Checks if all objects are up to date.
9111 If they are not, the full name of the first file that needs to be
9112 recompiled is printed.
9113 Repeated use of this option, followed by compiling the indicated source
9114 file, will eventually result in recompiling all required units.
9116 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9117 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9118 Output executable name. The name of the final executable program will be
9119 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9120 name for the executable will be the name of the input file in appropriate form
9121 for an executable file on the host system.
9123 This switch cannot be used when invoking @command{gnatmake} with several
9126 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9127 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9128 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9129 automatically missing object directories, library directories and exec
9132 @item ^-P^/PROJECT_FILE=^@var{project}
9133 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9134 Use project file @var{project}. Only one such switch can be used.
9135 @xref{gnatmake and Project Files}.
9138 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9139 Quiet. When this flag is not set, the commands carried out by
9140 @command{gnatmake} are displayed.
9142 @item ^-s^/SWITCH_CHECK/^
9143 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9144 Recompile if compiler switches have changed since last compilation.
9145 All compiler switches but -I and -o are taken into account in the
9147 orders between different ``first letter'' switches are ignored, but
9148 orders between same switches are taken into account. For example,
9149 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9150 is equivalent to @option{-O -g}.
9152 This switch is recommended when Integrated Preprocessing is used.
9155 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9156 Unique. Recompile at most the main files. It implies -c. Combined with
9157 -f, it is equivalent to calling the compiler directly. Note that using
9158 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9159 (@pxref{Project Files and Main Subprograms}).
9161 @item ^-U^/ALL_PROJECTS^
9162 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9163 When used without a project file or with one or several mains on the command
9164 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9165 on the command line, all sources of all project files are checked and compiled
9166 if not up to date, and libraries are rebuilt, if necessary.
9169 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9170 Verbose. Display the reason for all recompilations @command{gnatmake}
9171 decides are necessary, with the highest verbosity level.
9173 @item ^-vl^/LOW_VERBOSITY^
9174 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9175 Verbosity level Low. Display fewer lines than in verbosity Medium.
9177 @item ^-vm^/MEDIUM_VERBOSITY^
9178 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9179 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9181 @item ^-vh^/HIGH_VERBOSITY^
9182 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9183 Verbosity level High. Equivalent to ^-v^/REASONS^.
9185 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9186 Indicate the verbosity of the parsing of GNAT project files.
9187 @xref{Switches Related to Project Files}.
9189 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9190 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9191 Indicate that sources that are not part of any Project File may be compiled.
9192 Normally, when using Project Files, only sources that are part of a Project
9193 File may be compile. When this switch is used, a source outside of all Project
9194 Files may be compiled. The ALI file and the object file will be put in the
9195 object directory of the main Project. The compilation switches used will only
9196 be those specified on the command line. Even when
9197 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9198 command line need to be sources of a project file.
9200 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9201 Indicate that external variable @var{name} has the value @var{value}.
9202 The Project Manager will use this value for occurrences of
9203 @code{external(name)} when parsing the project file.
9204 @xref{Switches Related to Project Files}.
9207 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9208 No main subprogram. Bind and link the program even if the unit name
9209 given on the command line is a package name. The resulting executable
9210 will execute the elaboration routines of the package and its closure,
9211 then the finalization routines.
9216 @item @command{gcc} @asis{switches}
9218 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9219 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9222 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9223 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9224 automatically treated as a compiler switch, and passed on to all
9225 compilations that are carried out.
9230 Source and library search path switches:
9234 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9235 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9236 When looking for source files also look in directory @var{dir}.
9237 The order in which source files search is undertaken is
9238 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9240 @item ^-aL^/SKIP_MISSING=^@var{dir}
9241 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9242 Consider @var{dir} as being an externally provided Ada library.
9243 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9244 files have been located in directory @var{dir}. This allows you to have
9245 missing bodies for the units in @var{dir} and to ignore out of date bodies
9246 for the same units. You still need to specify
9247 the location of the specs for these units by using the switches
9248 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9249 or @option{^-I^/SEARCH=^@var{dir}}.
9250 Note: this switch is provided for compatibility with previous versions
9251 of @command{gnatmake}. The easier method of causing standard libraries
9252 to be excluded from consideration is to write-protect the corresponding
9255 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9256 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9257 When searching for library and object files, look in directory
9258 @var{dir}. The order in which library files are searched is described in
9259 @ref{Search Paths for gnatbind}.
9261 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9262 @cindex Search paths, for @command{gnatmake}
9263 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9264 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9265 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9267 @item ^-I^/SEARCH=^@var{dir}
9268 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9269 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9270 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9272 @item ^-I-^/NOCURRENT_DIRECTORY^
9273 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9274 @cindex Source files, suppressing search
9275 Do not look for source files in the directory containing the source
9276 file named in the command line.
9277 Do not look for ALI or object files in the directory
9278 where @command{gnatmake} was invoked.
9280 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9281 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9282 @cindex Linker libraries
9283 Add directory @var{dir} to the list of directories in which the linker
9284 will search for libraries. This is equivalent to
9285 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9287 Furthermore, under Windows, the sources pointed to by the libraries path
9288 set in the registry are not searched for.
9292 @cindex @option{-nostdinc} (@command{gnatmake})
9293 Do not look for source files in the system default directory.
9296 @cindex @option{-nostdlib} (@command{gnatmake})
9297 Do not look for library files in the system default directory.
9299 @item --RTS=@var{rts-path}
9300 @cindex @option{--RTS} (@command{gnatmake})
9301 Specifies the default location of the runtime library. GNAT looks for the
9303 in the following directories, and stops as soon as a valid runtime is found
9304 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9305 @file{ada_object_path} present):
9308 @item <current directory>/$rts_path
9310 @item <default-search-dir>/$rts_path
9312 @item <default-search-dir>/rts-$rts_path
9316 The selected path is handled like a normal RTS path.
9320 @node Mode Switches for gnatmake
9321 @section Mode Switches for @command{gnatmake}
9324 The mode switches (referred to as @code{mode_switches}) allow the
9325 inclusion of switches that are to be passed to the compiler itself, the
9326 binder or the linker. The effect of a mode switch is to cause all
9327 subsequent switches up to the end of the switch list, or up to the next
9328 mode switch, to be interpreted as switches to be passed on to the
9329 designated component of GNAT.
9333 @item -cargs @var{switches}
9334 @cindex @option{-cargs} (@command{gnatmake})
9335 Compiler switches. Here @var{switches} is a list of switches
9336 that are valid switches for @command{gcc}. They will be passed on to
9337 all compile steps performed by @command{gnatmake}.
9339 @item -bargs @var{switches}
9340 @cindex @option{-bargs} (@command{gnatmake})
9341 Binder switches. Here @var{switches} is a list of switches
9342 that are valid switches for @code{gnatbind}. They will be passed on to
9343 all bind steps performed by @command{gnatmake}.
9345 @item -largs @var{switches}
9346 @cindex @option{-largs} (@command{gnatmake})
9347 Linker switches. Here @var{switches} is a list of switches
9348 that are valid switches for @command{gnatlink}. They will be passed on to
9349 all link steps performed by @command{gnatmake}.
9351 @item -margs @var{switches}
9352 @cindex @option{-margs} (@command{gnatmake})
9353 Make switches. The switches are directly interpreted by @command{gnatmake},
9354 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9358 @node Notes on the Command Line
9359 @section Notes on the Command Line
9362 This section contains some additional useful notes on the operation
9363 of the @command{gnatmake} command.
9367 @cindex Recompilation, by @command{gnatmake}
9368 If @command{gnatmake} finds no ALI files, it recompiles the main program
9369 and all other units required by the main program.
9370 This means that @command{gnatmake}
9371 can be used for the initial compile, as well as during subsequent steps of
9372 the development cycle.
9375 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9376 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9377 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9381 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9382 is used to specify both source and
9383 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9384 instead if you just want to specify
9385 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9386 if you want to specify library paths
9390 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9391 This may conveniently be used to exclude standard libraries from
9392 consideration and in particular it means that the use of the
9393 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9394 unless @option{^-a^/ALL_FILES^} is also specified.
9397 @command{gnatmake} has been designed to make the use of Ada libraries
9398 particularly convenient. Assume you have an Ada library organized
9399 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9400 of your Ada compilation units,
9401 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9402 specs of these units, but no bodies. Then to compile a unit
9403 stored in @code{main.adb}, which uses this Ada library you would just type
9407 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9410 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9411 /SKIP_MISSING=@i{[OBJ_DIR]} main
9416 Using @command{gnatmake} along with the
9417 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9418 switch provides a mechanism for avoiding unnecessary recompilations. Using
9420 you can update the comments/format of your
9421 source files without having to recompile everything. Note, however, that
9422 adding or deleting lines in a source files may render its debugging
9423 info obsolete. If the file in question is a spec, the impact is rather
9424 limited, as that debugging info will only be useful during the
9425 elaboration phase of your program. For bodies the impact can be more
9426 significant. In all events, your debugger will warn you if a source file
9427 is more recent than the corresponding object, and alert you to the fact
9428 that the debugging information may be out of date.
9431 @node How gnatmake Works
9432 @section How @command{gnatmake} Works
9435 Generally @command{gnatmake} automatically performs all necessary
9436 recompilations and you don't need to worry about how it works. However,
9437 it may be useful to have some basic understanding of the @command{gnatmake}
9438 approach and in particular to understand how it uses the results of
9439 previous compilations without incorrectly depending on them.
9441 First a definition: an object file is considered @dfn{up to date} if the
9442 corresponding ALI file exists and if all the source files listed in the
9443 dependency section of this ALI file have time stamps matching those in
9444 the ALI file. This means that neither the source file itself nor any
9445 files that it depends on have been modified, and hence there is no need
9446 to recompile this file.
9448 @command{gnatmake} works by first checking if the specified main unit is up
9449 to date. If so, no compilations are required for the main unit. If not,
9450 @command{gnatmake} compiles the main program to build a new ALI file that
9451 reflects the latest sources. Then the ALI file of the main unit is
9452 examined to find all the source files on which the main program depends,
9453 and @command{gnatmake} recursively applies the above procedure on all these
9456 This process ensures that @command{gnatmake} only trusts the dependencies
9457 in an existing ALI file if they are known to be correct. Otherwise it
9458 always recompiles to determine a new, guaranteed accurate set of
9459 dependencies. As a result the program is compiled ``upside down'' from what may
9460 be more familiar as the required order of compilation in some other Ada
9461 systems. In particular, clients are compiled before the units on which
9462 they depend. The ability of GNAT to compile in any order is critical in
9463 allowing an order of compilation to be chosen that guarantees that
9464 @command{gnatmake} will recompute a correct set of new dependencies if
9467 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9468 imported by several of the executables, it will be recompiled at most once.
9470 Note: when using non-standard naming conventions
9471 (@pxref{Using Other File Names}), changing through a configuration pragmas
9472 file the version of a source and invoking @command{gnatmake} to recompile may
9473 have no effect, if the previous version of the source is still accessible
9474 by @command{gnatmake}. It may be necessary to use the switch
9475 ^-f^/FORCE_COMPILE^.
9477 @node Examples of gnatmake Usage
9478 @section Examples of @command{gnatmake} Usage
9481 @item gnatmake hello.adb
9482 Compile all files necessary to bind and link the main program
9483 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9484 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9486 @item gnatmake main1 main2 main3
9487 Compile all files necessary to bind and link the main programs
9488 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9489 (containing unit @code{Main2}) and @file{main3.adb}
9490 (containing unit @code{Main3}) and bind and link the resulting object files
9491 to generate three executable files @file{^main1^MAIN1.EXE^},
9492 @file{^main2^MAIN2.EXE^}
9493 and @file{^main3^MAIN3.EXE^}.
9496 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9500 @item gnatmake Main_Unit /QUIET
9501 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9502 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9504 Compile all files necessary to bind and link the main program unit
9505 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9506 be done with optimization level 2 and the order of elaboration will be
9507 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9508 displaying commands it is executing.
9511 @c *************************
9512 @node Improving Performance
9513 @chapter Improving Performance
9514 @cindex Improving performance
9517 This chapter presents several topics related to program performance.
9518 It first describes some of the tradeoffs that need to be considered
9519 and some of the techniques for making your program run faster.
9520 It then documents the @command{gnatelim} tool and unused subprogram/data
9521 elimination feature, which can reduce the size of program executables.
9523 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9524 driver (see @ref{The GNAT Driver and Project Files}).
9528 * Performance Considerations::
9529 * Text_IO Suggestions::
9530 * Reducing Size of Ada Executables with gnatelim::
9531 * Reducing Size of Executables with unused subprogram/data elimination::
9535 @c *****************************
9536 @node Performance Considerations
9537 @section Performance Considerations
9540 The GNAT system provides a number of options that allow a trade-off
9545 performance of the generated code
9548 speed of compilation
9551 minimization of dependences and recompilation
9554 the degree of run-time checking.
9558 The defaults (if no options are selected) aim at improving the speed
9559 of compilation and minimizing dependences, at the expense of performance
9560 of the generated code:
9567 no inlining of subprogram calls
9570 all run-time checks enabled except overflow and elaboration checks
9574 These options are suitable for most program development purposes. This
9575 chapter describes how you can modify these choices, and also provides
9576 some guidelines on debugging optimized code.
9579 * Controlling Run-Time Checks::
9580 * Use of Restrictions::
9581 * Optimization Levels::
9582 * Debugging Optimized Code::
9583 * Inlining of Subprograms::
9584 * Other Optimization Switches::
9585 * Optimization and Strict Aliasing::
9588 * Coverage Analysis::
9592 @node Controlling Run-Time Checks
9593 @subsection Controlling Run-Time Checks
9596 By default, GNAT generates all run-time checks, except integer overflow
9597 checks, stack overflow checks, and checks for access before elaboration on
9598 subprogram calls. The latter are not required in default mode, because all
9599 necessary checking is done at compile time.
9600 @cindex @option{-gnatp} (@command{gcc})
9601 @cindex @option{-gnato} (@command{gcc})
9602 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9603 be modified. @xref{Run-Time Checks}.
9605 Our experience is that the default is suitable for most development
9608 We treat integer overflow specially because these
9609 are quite expensive and in our experience are not as important as other
9610 run-time checks in the development process. Note that division by zero
9611 is not considered an overflow check, and divide by zero checks are
9612 generated where required by default.
9614 Elaboration checks are off by default, and also not needed by default, since
9615 GNAT uses a static elaboration analysis approach that avoids the need for
9616 run-time checking. This manual contains a full chapter discussing the issue
9617 of elaboration checks, and if the default is not satisfactory for your use,
9618 you should read this chapter.
9620 For validity checks, the minimal checks required by the Ada Reference
9621 Manual (for case statements and assignments to array elements) are on
9622 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9623 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9624 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9625 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9626 are also suppressed entirely if @option{-gnatp} is used.
9628 @cindex Overflow checks
9629 @cindex Checks, overflow
9632 @cindex pragma Suppress
9633 @cindex pragma Unsuppress
9634 Note that the setting of the switches controls the default setting of
9635 the checks. They may be modified using either @code{pragma Suppress} (to
9636 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9637 checks) in the program source.
9639 @node Use of Restrictions
9640 @subsection Use of Restrictions
9643 The use of pragma Restrictions allows you to control which features are
9644 permitted in your program. Apart from the obvious point that if you avoid
9645 relatively expensive features like finalization (enforceable by the use
9646 of pragma Restrictions (No_Finalization), the use of this pragma does not
9647 affect the generated code in most cases.
9649 One notable exception to this rule is that the possibility of task abort
9650 results in some distributed overhead, particularly if finalization or
9651 exception handlers are used. The reason is that certain sections of code
9652 have to be marked as non-abortable.
9654 If you use neither the @code{abort} statement, nor asynchronous transfer
9655 of control (@code{select @dots{} then abort}), then this distributed overhead
9656 is removed, which may have a general positive effect in improving
9657 overall performance. Especially code involving frequent use of tasking
9658 constructs and controlled types will show much improved performance.
9659 The relevant restrictions pragmas are
9661 @smallexample @c ada
9662 pragma Restrictions (No_Abort_Statements);
9663 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9667 It is recommended that these restriction pragmas be used if possible. Note
9668 that this also means that you can write code without worrying about the
9669 possibility of an immediate abort at any point.
9671 @node Optimization Levels
9672 @subsection Optimization Levels
9673 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9676 Without any optimization ^option,^qualifier,^
9677 the compiler's goal is to reduce the cost of
9678 compilation and to make debugging produce the expected results.
9679 Statements are independent: if you stop the program with a breakpoint between
9680 statements, you can then assign a new value to any variable or change
9681 the program counter to any other statement in the subprogram and get exactly
9682 the results you would expect from the source code.
9684 Turning on optimization makes the compiler attempt to improve the
9685 performance and/or code size at the expense of compilation time and
9686 possibly the ability to debug the program.
9689 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9690 the last such option is the one that is effective.
9693 The default is optimization off. This results in the fastest compile
9694 times, but GNAT makes absolutely no attempt to optimize, and the
9695 generated programs are considerably larger and slower than when
9696 optimization is enabled. You can use the
9698 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9699 @option{-O2}, @option{-O3}, and @option{-Os})
9702 @code{OPTIMIZE} qualifier
9704 to @command{gcc} to control the optimization level:
9707 @item ^-O0^/OPTIMIZE=NONE^
9708 No optimization (the default);
9709 generates unoptimized code but has
9710 the fastest compilation time.
9712 Note that many other compilers do fairly extensive optimization
9713 even if ``no optimization'' is specified. With gcc, it is
9714 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9715 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9716 really does mean no optimization at all. This difference between
9717 gcc and other compilers should be kept in mind when doing
9718 performance comparisons.
9720 @item ^-O1^/OPTIMIZE=SOME^
9721 Moderate optimization;
9722 optimizes reasonably well but does not
9723 degrade compilation time significantly.
9725 @item ^-O2^/OPTIMIZE=ALL^
9727 @itemx /OPTIMIZE=DEVELOPMENT
9730 generates highly optimized code and has
9731 the slowest compilation time.
9733 @item ^-O3^/OPTIMIZE=INLINING^
9734 Full optimization as in @option{-O2},
9735 and also attempts automatic inlining of small
9736 subprograms within a unit (@pxref{Inlining of Subprograms}).
9738 @item ^-Os^/OPTIMIZE=SPACE^
9739 Optimize space usage of resulting program.
9743 Higher optimization levels perform more global transformations on the
9744 program and apply more expensive analysis algorithms in order to generate
9745 faster and more compact code. The price in compilation time, and the
9746 resulting improvement in execution time,
9747 both depend on the particular application and the hardware environment.
9748 You should experiment to find the best level for your application.
9750 Since the precise set of optimizations done at each level will vary from
9751 release to release (and sometime from target to target), it is best to think
9752 of the optimization settings in general terms.
9753 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9754 the GNU Compiler Collection (GCC)}, for details about
9755 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9756 individually enable or disable specific optimizations.
9758 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9759 been tested extensively at all optimization levels. There are some bugs
9760 which appear only with optimization turned on, but there have also been
9761 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9762 level of optimization does not improve the reliability of the code
9763 generator, which in practice is highly reliable at all optimization
9766 Note regarding the use of @option{-O3}: The use of this optimization level
9767 is generally discouraged with GNAT, since it often results in larger
9768 executables which run more slowly. See further discussion of this point
9769 in @ref{Inlining of Subprograms}.
9771 @node Debugging Optimized Code
9772 @subsection Debugging Optimized Code
9773 @cindex Debugging optimized code
9774 @cindex Optimization and debugging
9777 Although it is possible to do a reasonable amount of debugging at
9779 nonzero optimization levels,
9780 the higher the level the more likely that
9783 @option{/OPTIMIZE} settings other than @code{NONE},
9784 such settings will make it more likely that
9786 source-level constructs will have been eliminated by optimization.
9787 For example, if a loop is strength-reduced, the loop
9788 control variable may be completely eliminated and thus cannot be
9789 displayed in the debugger.
9790 This can only happen at @option{-O2} or @option{-O3}.
9791 Explicit temporary variables that you code might be eliminated at
9792 ^level^setting^ @option{-O1} or higher.
9794 The use of the @option{^-g^/DEBUG^} switch,
9795 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9796 which is needed for source-level debugging,
9797 affects the size of the program executable on disk,
9798 and indeed the debugging information can be quite large.
9799 However, it has no effect on the generated code (and thus does not
9800 degrade performance)
9802 Since the compiler generates debugging tables for a compilation unit before
9803 it performs optimizations, the optimizing transformations may invalidate some
9804 of the debugging data. You therefore need to anticipate certain
9805 anomalous situations that may arise while debugging optimized code.
9806 These are the most common cases:
9810 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
9812 the PC bouncing back and forth in the code. This may result from any of
9813 the following optimizations:
9817 @i{Common subexpression elimination:} using a single instance of code for a
9818 quantity that the source computes several times. As a result you
9819 may not be able to stop on what looks like a statement.
9822 @i{Invariant code motion:} moving an expression that does not change within a
9823 loop, to the beginning of the loop.
9826 @i{Instruction scheduling:} moving instructions so as to
9827 overlap loads and stores (typically) with other code, or in
9828 general to move computations of values closer to their uses. Often
9829 this causes you to pass an assignment statement without the assignment
9830 happening and then later bounce back to the statement when the
9831 value is actually needed. Placing a breakpoint on a line of code
9832 and then stepping over it may, therefore, not always cause all the
9833 expected side-effects.
9837 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9838 two identical pieces of code are merged and the program counter suddenly
9839 jumps to a statement that is not supposed to be executed, simply because
9840 it (and the code following) translates to the same thing as the code
9841 that @emph{was} supposed to be executed. This effect is typically seen in
9842 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9843 a @code{break} in a C @code{^switch^switch^} statement.
9846 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9847 There are various reasons for this effect:
9851 In a subprogram prologue, a parameter may not yet have been moved to its
9855 A variable may be dead, and its register re-used. This is
9856 probably the most common cause.
9859 As mentioned above, the assignment of a value to a variable may
9863 A variable may be eliminated entirely by value propagation or
9864 other means. In this case, GCC may incorrectly generate debugging
9865 information for the variable
9869 In general, when an unexpected value appears for a local variable or parameter
9870 you should first ascertain if that value was actually computed by
9871 your program, as opposed to being incorrectly reported by the debugger.
9873 array elements in an object designated by an access value
9874 are generally less of a problem, once you have ascertained that the access
9876 Typically, this means checking variables in the preceding code and in the
9877 calling subprogram to verify that the value observed is explainable from other
9878 values (one must apply the procedure recursively to those
9879 other values); or re-running the code and stopping a little earlier
9880 (perhaps before the call) and stepping to better see how the variable obtained
9881 the value in question; or continuing to step @emph{from} the point of the
9882 strange value to see if code motion had simply moved the variable's
9887 In light of such anomalies, a recommended technique is to use @option{-O0}
9888 early in the software development cycle, when extensive debugging capabilities
9889 are most needed, and then move to @option{-O1} and later @option{-O2} as
9890 the debugger becomes less critical.
9891 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9892 a release management issue.
9894 Note that if you use @option{-g} you can then use the @command{strip} program
9895 on the resulting executable,
9896 which removes both debugging information and global symbols.
9899 @node Inlining of Subprograms
9900 @subsection Inlining of Subprograms
9903 A call to a subprogram in the current unit is inlined if all the
9904 following conditions are met:
9908 The optimization level is at least @option{-O1}.
9911 The called subprogram is suitable for inlining: It must be small enough
9912 and not contain something that @command{gcc} cannot support in inlined
9916 @cindex pragma Inline
9918 Either @code{pragma Inline} applies to the subprogram, or it is local
9919 to the unit and called once from within it, or it is small and automatic
9920 inlining (optimization level @option{-O3}) is specified.
9924 Calls to subprograms in @code{with}'ed units are normally not inlined.
9925 To achieve actual inlining (that is, replacement of the call by the code
9926 in the body of the subprogram), the following conditions must all be true.
9930 The optimization level is at least @option{-O1}.
9933 The called subprogram is suitable for inlining: It must be small enough
9934 and not contain something that @command{gcc} cannot support in inlined
9938 The call appears in a body (not in a package spec).
9941 There is a @code{pragma Inline} for the subprogram.
9944 @cindex @option{-gnatn} (@command{gcc})
9945 The @option{^-gnatn^/INLINE^} switch
9946 is used in the @command{gcc} command line
9949 Even if all these conditions are met, it may not be possible for
9950 the compiler to inline the call, due to the length of the body,
9951 or features in the body that make it impossible for the compiler
9954 Note that specifying the @option{-gnatn} switch causes additional
9955 compilation dependencies. Consider the following:
9957 @smallexample @c ada
9977 With the default behavior (no @option{-gnatn} switch specified), the
9978 compilation of the @code{Main} procedure depends only on its own source,
9979 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9980 means that editing the body of @code{R} does not require recompiling
9983 On the other hand, the call @code{R.Q} is not inlined under these
9984 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9985 is compiled, the call will be inlined if the body of @code{Q} is small
9986 enough, but now @code{Main} depends on the body of @code{R} in
9987 @file{r.adb} as well as on the spec. This means that if this body is edited,
9988 the main program must be recompiled. Note that this extra dependency
9989 occurs whether or not the call is in fact inlined by @command{gcc}.
9991 The use of front end inlining with @option{-gnatN} generates similar
9992 additional dependencies.
9994 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9995 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9996 can be used to prevent
9997 all inlining. This switch overrides all other conditions and ensures
9998 that no inlining occurs. The extra dependences resulting from
9999 @option{-gnatn} will still be active, even if
10000 this switch is used to suppress the resulting inlining actions.
10002 @cindex @option{-fno-inline-functions} (@command{gcc})
10003 Note: The @option{-fno-inline-functions} switch can be used to prevent
10004 automatic inlining of small subprograms if @option{-O3} is used.
10006 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10007 Note: The @option{-fno-inline-functions-called-once} switch
10008 can be used to prevent inlining of subprograms local to the unit
10009 and called once from within it if @option{-O1} is used.
10011 Note regarding the use of @option{-O3}: There is no difference in inlining
10012 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10013 pragma @code{Inline} assuming the use of @option{-gnatn}
10014 or @option{-gnatN} (the switches that activate inlining). If you have used
10015 pragma @code{Inline} in appropriate cases, then it is usually much better
10016 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10017 in this case only has the effect of inlining subprograms you did not
10018 think should be inlined. We often find that the use of @option{-O3} slows
10019 down code by performing excessive inlining, leading to increased instruction
10020 cache pressure from the increased code size. So the bottom line here is
10021 that you should not automatically assume that @option{-O3} is better than
10022 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10023 it actually improves performance.
10025 @node Other Optimization Switches
10026 @subsection Other Optimization Switches
10027 @cindex Optimization Switches
10029 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10030 @command{gcc} optimization switches are potentially usable. These switches
10031 have not been extensively tested with GNAT but can generally be expected
10032 to work. Examples of switches in this category are
10033 @option{-funroll-loops} and
10034 the various target-specific @option{-m} options (in particular, it has been
10035 observed that @option{-march=pentium4} can significantly improve performance
10036 on appropriate machines). For full details of these switches, see
10037 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10038 the GNU Compiler Collection (GCC)}.
10040 @node Optimization and Strict Aliasing
10041 @subsection Optimization and Strict Aliasing
10043 @cindex Strict Aliasing
10044 @cindex No_Strict_Aliasing
10047 The strong typing capabilities of Ada allow an optimizer to generate
10048 efficient code in situations where other languages would be forced to
10049 make worst case assumptions preventing such optimizations. Consider
10050 the following example:
10052 @smallexample @c ada
10055 type Int1 is new Integer;
10056 type Int2 is new Integer;
10057 type Int1A is access Int1;
10058 type Int2A is access Int2;
10065 for J in Data'Range loop
10066 if Data (J) = Int1V.all then
10067 Int2V.all := Int2V.all + 1;
10076 In this example, since the variable @code{Int1V} can only access objects
10077 of type @code{Int1}, and @code{Int2V} can only access objects of type
10078 @code{Int2}, there is no possibility that the assignment to
10079 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10080 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10081 for all iterations of the loop and avoid the extra memory reference
10082 required to dereference it each time through the loop.
10084 This kind of optimization, called strict aliasing analysis, is
10085 triggered by specifying an optimization level of @option{-O2} or
10086 higher and allows @code{GNAT} to generate more efficient code
10087 when access values are involved.
10089 However, although this optimization is always correct in terms of
10090 the formal semantics of the Ada Reference Manual, difficulties can
10091 arise if features like @code{Unchecked_Conversion} are used to break
10092 the typing system. Consider the following complete program example:
10094 @smallexample @c ada
10097 type int1 is new integer;
10098 type int2 is new integer;
10099 type a1 is access int1;
10100 type a2 is access int2;
10105 function to_a2 (Input : a1) return a2;
10108 with Unchecked_Conversion;
10110 function to_a2 (Input : a1) return a2 is
10112 new Unchecked_Conversion (a1, a2);
10114 return to_a2u (Input);
10120 with Text_IO; use Text_IO;
10122 v1 : a1 := new int1;
10123 v2 : a2 := to_a2 (v1);
10127 put_line (int1'image (v1.all));
10133 This program prints out 0 in @option{-O0} or @option{-O1}
10134 mode, but it prints out 1 in @option{-O2} mode. That's
10135 because in strict aliasing mode, the compiler can and
10136 does assume that the assignment to @code{v2.all} could not
10137 affect the value of @code{v1.all}, since different types
10140 This behavior is not a case of non-conformance with the standard, since
10141 the Ada RM specifies that an unchecked conversion where the resulting
10142 bit pattern is not a correct value of the target type can result in an
10143 abnormal value and attempting to reference an abnormal value makes the
10144 execution of a program erroneous. That's the case here since the result
10145 does not point to an object of type @code{int2}. This means that the
10146 effect is entirely unpredictable.
10148 However, although that explanation may satisfy a language
10149 lawyer, in practice an applications programmer expects an
10150 unchecked conversion involving pointers to create true
10151 aliases and the behavior of printing 1 seems plain wrong.
10152 In this case, the strict aliasing optimization is unwelcome.
10154 Indeed the compiler recognizes this possibility, and the
10155 unchecked conversion generates a warning:
10158 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10159 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10160 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10164 Unfortunately the problem is recognized when compiling the body of
10165 package @code{p2}, but the actual "bad" code is generated while
10166 compiling the body of @code{m} and this latter compilation does not see
10167 the suspicious @code{Unchecked_Conversion}.
10169 As implied by the warning message, there are approaches you can use to
10170 avoid the unwanted strict aliasing optimization in a case like this.
10172 One possibility is to simply avoid the use of @option{-O2}, but
10173 that is a bit drastic, since it throws away a number of useful
10174 optimizations that do not involve strict aliasing assumptions.
10176 A less drastic approach is to compile the program using the
10177 option @option{-fno-strict-aliasing}. Actually it is only the
10178 unit containing the dereferencing of the suspicious pointer
10179 that needs to be compiled. So in this case, if we compile
10180 unit @code{m} with this switch, then we get the expected
10181 value of zero printed. Analyzing which units might need
10182 the switch can be painful, so a more reasonable approach
10183 is to compile the entire program with options @option{-O2}
10184 and @option{-fno-strict-aliasing}. If the performance is
10185 satisfactory with this combination of options, then the
10186 advantage is that the entire issue of possible "wrong"
10187 optimization due to strict aliasing is avoided.
10189 To avoid the use of compiler switches, the configuration
10190 pragma @code{No_Strict_Aliasing} with no parameters may be
10191 used to specify that for all access types, the strict
10192 aliasing optimization should be suppressed.
10194 However, these approaches are still overkill, in that they causes
10195 all manipulations of all access values to be deoptimized. A more
10196 refined approach is to concentrate attention on the specific
10197 access type identified as problematic.
10199 First, if a careful analysis of uses of the pointer shows
10200 that there are no possible problematic references, then
10201 the warning can be suppressed by bracketing the
10202 instantiation of @code{Unchecked_Conversion} to turn
10205 @smallexample @c ada
10206 pragma Warnings (Off);
10208 new Unchecked_Conversion (a1, a2);
10209 pragma Warnings (On);
10213 Of course that approach is not appropriate for this particular
10214 example, since indeed there is a problematic reference. In this
10215 case we can take one of two other approaches.
10217 The first possibility is to move the instantiation of unchecked
10218 conversion to the unit in which the type is declared. In
10219 this example, we would move the instantiation of
10220 @code{Unchecked_Conversion} from the body of package
10221 @code{p2} to the spec of package @code{p1}. Now the
10222 warning disappears. That's because any use of the
10223 access type knows there is a suspicious unchecked
10224 conversion, and the strict aliasing optimization
10225 is automatically suppressed for the type.
10227 If it is not practical to move the unchecked conversion to the same unit
10228 in which the destination access type is declared (perhaps because the
10229 source type is not visible in that unit), you may use pragma
10230 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10231 same declarative sequence as the declaration of the access type:
10233 @smallexample @c ada
10234 type a2 is access int2;
10235 pragma No_Strict_Aliasing (a2);
10239 Here again, the compiler now knows that the strict aliasing optimization
10240 should be suppressed for any reference to type @code{a2} and the
10241 expected behavior is obtained.
10243 Finally, note that although the compiler can generate warnings for
10244 simple cases of unchecked conversions, there are tricker and more
10245 indirect ways of creating type incorrect aliases which the compiler
10246 cannot detect. Examples are the use of address overlays and unchecked
10247 conversions involving composite types containing access types as
10248 components. In such cases, no warnings are generated, but there can
10249 still be aliasing problems. One safe coding practice is to forbid the
10250 use of address clauses for type overlaying, and to allow unchecked
10251 conversion only for primitive types. This is not really a significant
10252 restriction since any possible desired effect can be achieved by
10253 unchecked conversion of access values.
10256 @node Coverage Analysis
10257 @subsection Coverage Analysis
10260 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10261 the user to determine the distribution of execution time across a program,
10262 @pxref{Profiling} for details of usage.
10266 @node Text_IO Suggestions
10267 @section @code{Text_IO} Suggestions
10268 @cindex @code{Text_IO} and performance
10271 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10272 the requirement of maintaining page and line counts. If performance
10273 is critical, a recommendation is to use @code{Stream_IO} instead of
10274 @code{Text_IO} for volume output, since this package has less overhead.
10276 If @code{Text_IO} must be used, note that by default output to the standard
10277 output and standard error files is unbuffered (this provides better
10278 behavior when output statements are used for debugging, or if the
10279 progress of a program is observed by tracking the output, e.g. by
10280 using the Unix @command{tail -f} command to watch redirected output.
10282 If you are generating large volumes of output with @code{Text_IO} and
10283 performance is an important factor, use a designated file instead
10284 of the standard output file, or change the standard output file to
10285 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10289 @node Reducing Size of Ada Executables with gnatelim
10290 @section Reducing Size of Ada Executables with @code{gnatelim}
10294 This section describes @command{gnatelim}, a tool which detects unused
10295 subprograms and helps the compiler to create a smaller executable for your
10300 * Running gnatelim::
10301 * Correcting the List of Eliminate Pragmas::
10302 * Making Your Executables Smaller::
10303 * Summary of the gnatelim Usage Cycle::
10306 @node About gnatelim
10307 @subsection About @code{gnatelim}
10310 When a program shares a set of Ada
10311 packages with other programs, it may happen that this program uses
10312 only a fraction of the subprograms defined in these packages. The code
10313 created for these unused subprograms increases the size of the executable.
10315 @code{gnatelim} tracks unused subprograms in an Ada program and
10316 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10317 subprograms that are declared but never called. By placing the list of
10318 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10319 recompiling your program, you may decrease the size of its executable,
10320 because the compiler will not generate the code for 'eliminated' subprograms.
10321 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10322 information about this pragma.
10324 @code{gnatelim} needs as its input data the name of the main subprogram
10325 and a bind file for a main subprogram.
10327 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10328 the main subprogram. @code{gnatelim} can work with both Ada and C
10329 bind files; when both are present, it uses the Ada bind file.
10330 The following commands will build the program and create the bind file:
10333 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10334 $ gnatbind main_prog
10337 Note that @code{gnatelim} needs neither object nor ALI files.
10339 @node Running gnatelim
10340 @subsection Running @code{gnatelim}
10343 @code{gnatelim} has the following command-line interface:
10346 $ gnatelim @ovar{options} name
10350 @code{name} should be a name of a source file that contains the main subprogram
10351 of a program (partition).
10353 @code{gnatelim} has the following switches:
10358 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10359 Quiet mode: by default @code{gnatelim} outputs to the standard error
10360 stream the number of program units left to be processed. This option turns
10363 @item ^-v^/VERBOSE^
10364 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10365 Verbose mode: @code{gnatelim} version information is printed as Ada
10366 comments to the standard output stream. Also, in addition to the number of
10367 program units left @code{gnatelim} will output the name of the current unit
10371 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10372 Also look for subprograms from the GNAT run time that can be eliminated. Note
10373 that when @file{gnat.adc} is produced using this switch, the entire program
10374 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10376 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10377 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10378 When looking for source files also look in directory @var{dir}. Specifying
10379 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10380 sources in the current directory.
10382 @item ^-b^/BIND_FILE=^@var{bind_file}
10383 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10384 Specifies @var{bind_file} as the bind file to process. If not set, the name
10385 of the bind file is computed from the full expanded Ada name
10386 of a main subprogram.
10388 @item ^-C^/CONFIG_FILE=^@var{config_file}
10389 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10390 Specifies a file @var{config_file} that contains configuration pragmas. The
10391 file must be specified with full path.
10393 @item ^--GCC^/COMPILER^=@var{compiler_name}
10394 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10395 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10396 available on the path.
10398 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10399 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10400 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10401 available on the path.
10405 @code{gnatelim} sends its output to the standard output stream, and all the
10406 tracing and debug information is sent to the standard error stream.
10407 In order to produce a proper GNAT configuration file
10408 @file{gnat.adc}, redirection must be used:
10412 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10415 $ gnatelim main_prog.adb > gnat.adc
10424 $ gnatelim main_prog.adb >> gnat.adc
10428 in order to append the @code{gnatelim} output to the existing contents of
10432 @node Correcting the List of Eliminate Pragmas
10433 @subsection Correcting the List of Eliminate Pragmas
10436 In some rare cases @code{gnatelim} may try to eliminate
10437 subprograms that are actually called in the program. In this case, the
10438 compiler will generate an error message of the form:
10441 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10445 You will need to manually remove the wrong @code{Eliminate} pragmas from
10446 the @file{gnat.adc} file. You should recompile your program
10447 from scratch after that, because you need a consistent @file{gnat.adc} file
10448 during the entire compilation.
10450 @node Making Your Executables Smaller
10451 @subsection Making Your Executables Smaller
10454 In order to get a smaller executable for your program you now have to
10455 recompile the program completely with the new @file{gnat.adc} file
10456 created by @code{gnatelim} in your current directory:
10459 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10463 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10464 recompile everything
10465 with the set of pragmas @code{Eliminate} that you have obtained with
10466 @command{gnatelim}).
10468 Be aware that the set of @code{Eliminate} pragmas is specific to each
10469 program. It is not recommended to merge sets of @code{Eliminate}
10470 pragmas created for different programs in one @file{gnat.adc} file.
10472 @node Summary of the gnatelim Usage Cycle
10473 @subsection Summary of the gnatelim Usage Cycle
10476 Here is a quick summary of the steps to be taken in order to reduce
10477 the size of your executables with @code{gnatelim}. You may use
10478 other GNAT options to control the optimization level,
10479 to produce the debugging information, to set search path, etc.
10483 Produce a bind file
10486 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10487 $ gnatbind main_prog
10491 Generate a list of @code{Eliminate} pragmas
10494 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10497 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10502 Recompile the application
10505 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10510 @node Reducing Size of Executables with unused subprogram/data elimination
10511 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10512 @findex unused subprogram/data elimination
10515 This section describes how you can eliminate unused subprograms and data from
10516 your executable just by setting options at compilation time.
10519 * About unused subprogram/data elimination::
10520 * Compilation options::
10521 * Example of unused subprogram/data elimination::
10524 @node About unused subprogram/data elimination
10525 @subsection About unused subprogram/data elimination
10528 By default, an executable contains all code and data of its composing objects
10529 (directly linked or coming from statically linked libraries), even data or code
10530 never used by this executable.
10532 This feature will allow you to eliminate such unused code from your
10533 executable, making it smaller (in disk and in memory).
10535 This functionality is available on all Linux platforms except for the IA-64
10536 architecture and on all cross platforms using the ELF binary file format.
10537 In both cases GNU binutils version 2.16 or later are required to enable it.
10539 @node Compilation options
10540 @subsection Compilation options
10543 The operation of eliminating the unused code and data from the final executable
10544 is directly performed by the linker.
10546 In order to do this, it has to work with objects compiled with the
10548 @option{-ffunction-sections} @option{-fdata-sections}.
10549 @cindex @option{-ffunction-sections} (@command{gcc})
10550 @cindex @option{-fdata-sections} (@command{gcc})
10551 These options are usable with C and Ada files.
10552 They will place respectively each
10553 function or data in a separate section in the resulting object file.
10555 Once the objects and static libraries are created with these options, the
10556 linker can perform the dead code elimination. You can do this by setting
10557 the @option{-Wl,--gc-sections} option to gcc command or in the
10558 @option{-largs} section of @command{gnatmake}. This will perform a
10559 garbage collection of code and data never referenced.
10561 If the linker performs a partial link (@option{-r} ld linker option), then you
10562 will need to provide one or several entry point using the
10563 @option{-e} / @option{--entry} ld option.
10565 Note that objects compiled without the @option{-ffunction-sections} and
10566 @option{-fdata-sections} options can still be linked with the executable.
10567 However, no dead code elimination will be performed on those objects (they will
10570 The GNAT static library is now compiled with -ffunction-sections and
10571 -fdata-sections on some platforms. This allows you to eliminate the unused code
10572 and data of the GNAT library from your executable.
10574 @node Example of unused subprogram/data elimination
10575 @subsection Example of unused subprogram/data elimination
10578 Here is a simple example:
10580 @smallexample @c ada
10589 Used_Data : Integer;
10590 Unused_Data : Integer;
10592 procedure Used (Data : Integer);
10593 procedure Unused (Data : Integer);
10596 package body Aux is
10597 procedure Used (Data : Integer) is
10602 procedure Unused (Data : Integer) is
10604 Unused_Data := Data;
10610 @code{Unused} and @code{Unused_Data} are never referenced in this code
10611 excerpt, and hence they may be safely removed from the final executable.
10616 $ nm test | grep used
10617 020015f0 T aux__unused
10618 02005d88 B aux__unused_data
10619 020015cc T aux__used
10620 02005d84 B aux__used_data
10622 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10623 -largs -Wl,--gc-sections
10625 $ nm test | grep used
10626 02005350 T aux__used
10627 0201ffe0 B aux__used_data
10631 It can be observed that the procedure @code{Unused} and the object
10632 @code{Unused_Data} are removed by the linker when using the
10633 appropriate options.
10635 @c ********************************
10636 @node Renaming Files Using gnatchop
10637 @chapter Renaming Files Using @code{gnatchop}
10641 This chapter discusses how to handle files with multiple units by using
10642 the @code{gnatchop} utility. This utility is also useful in renaming
10643 files to meet the standard GNAT default file naming conventions.
10646 * Handling Files with Multiple Units::
10647 * Operating gnatchop in Compilation Mode::
10648 * Command Line for gnatchop::
10649 * Switches for gnatchop::
10650 * Examples of gnatchop Usage::
10653 @node Handling Files with Multiple Units
10654 @section Handling Files with Multiple Units
10657 The basic compilation model of GNAT requires that a file submitted to the
10658 compiler have only one unit and there be a strict correspondence
10659 between the file name and the unit name.
10661 The @code{gnatchop} utility allows both of these rules to be relaxed,
10662 allowing GNAT to process files which contain multiple compilation units
10663 and files with arbitrary file names. @code{gnatchop}
10664 reads the specified file and generates one or more output files,
10665 containing one unit per file. The unit and the file name correspond,
10666 as required by GNAT.
10668 If you want to permanently restructure a set of ``foreign'' files so that
10669 they match the GNAT rules, and do the remaining development using the
10670 GNAT structure, you can simply use @command{gnatchop} once, generate the
10671 new set of files and work with them from that point on.
10673 Alternatively, if you want to keep your files in the ``foreign'' format,
10674 perhaps to maintain compatibility with some other Ada compilation
10675 system, you can set up a procedure where you use @command{gnatchop} each
10676 time you compile, regarding the source files that it writes as temporary
10677 files that you throw away.
10679 @node Operating gnatchop in Compilation Mode
10680 @section Operating gnatchop in Compilation Mode
10683 The basic function of @code{gnatchop} is to take a file with multiple units
10684 and split it into separate files. The boundary between files is reasonably
10685 clear, except for the issue of comments and pragmas. In default mode, the
10686 rule is that any pragmas between units belong to the previous unit, except
10687 that configuration pragmas always belong to the following unit. Any comments
10688 belong to the following unit. These rules
10689 almost always result in the right choice of
10690 the split point without needing to mark it explicitly and most users will
10691 find this default to be what they want. In this default mode it is incorrect to
10692 submit a file containing only configuration pragmas, or one that ends in
10693 configuration pragmas, to @code{gnatchop}.
10695 However, using a special option to activate ``compilation mode'',
10697 can perform another function, which is to provide exactly the semantics
10698 required by the RM for handling of configuration pragmas in a compilation.
10699 In the absence of configuration pragmas (at the main file level), this
10700 option has no effect, but it causes such configuration pragmas to be handled
10701 in a quite different manner.
10703 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10704 only configuration pragmas, then this file is appended to the
10705 @file{gnat.adc} file in the current directory. This behavior provides
10706 the required behavior described in the RM for the actions to be taken
10707 on submitting such a file to the compiler, namely that these pragmas
10708 should apply to all subsequent compilations in the same compilation
10709 environment. Using GNAT, the current directory, possibly containing a
10710 @file{gnat.adc} file is the representation
10711 of a compilation environment. For more information on the
10712 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10714 Second, in compilation mode, if @code{gnatchop}
10715 is given a file that starts with
10716 configuration pragmas, and contains one or more units, then these
10717 configuration pragmas are prepended to each of the chopped files. This
10718 behavior provides the required behavior described in the RM for the
10719 actions to be taken on compiling such a file, namely that the pragmas
10720 apply to all units in the compilation, but not to subsequently compiled
10723 Finally, if configuration pragmas appear between units, they are appended
10724 to the previous unit. This results in the previous unit being illegal,
10725 since the compiler does not accept configuration pragmas that follow
10726 a unit. This provides the required RM behavior that forbids configuration
10727 pragmas other than those preceding the first compilation unit of a
10730 For most purposes, @code{gnatchop} will be used in default mode. The
10731 compilation mode described above is used only if you need exactly
10732 accurate behavior with respect to compilations, and you have files
10733 that contain multiple units and configuration pragmas. In this
10734 circumstance the use of @code{gnatchop} with the compilation mode
10735 switch provides the required behavior, and is for example the mode
10736 in which GNAT processes the ACVC tests.
10738 @node Command Line for gnatchop
10739 @section Command Line for @code{gnatchop}
10742 The @code{gnatchop} command has the form:
10745 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
10750 The only required argument is the file name of the file to be chopped.
10751 There are no restrictions on the form of this file name. The file itself
10752 contains one or more Ada units, in normal GNAT format, concatenated
10753 together. As shown, more than one file may be presented to be chopped.
10755 When run in default mode, @code{gnatchop} generates one output file in
10756 the current directory for each unit in each of the files.
10758 @var{directory}, if specified, gives the name of the directory to which
10759 the output files will be written. If it is not specified, all files are
10760 written to the current directory.
10762 For example, given a
10763 file called @file{hellofiles} containing
10765 @smallexample @c ada
10770 with Text_IO; use Text_IO;
10773 Put_Line ("Hello");
10783 $ gnatchop ^hellofiles^HELLOFILES.^
10787 generates two files in the current directory, one called
10788 @file{hello.ads} containing the single line that is the procedure spec,
10789 and the other called @file{hello.adb} containing the remaining text. The
10790 original file is not affected. The generated files can be compiled in
10794 When gnatchop is invoked on a file that is empty or that contains only empty
10795 lines and/or comments, gnatchop will not fail, but will not produce any
10798 For example, given a
10799 file called @file{toto.txt} containing
10801 @smallexample @c ada
10813 $ gnatchop ^toto.txt^TOT.TXT^
10817 will not produce any new file and will result in the following warnings:
10820 toto.txt:1:01: warning: empty file, contains no compilation units
10821 no compilation units found
10822 no source files written
10825 @node Switches for gnatchop
10826 @section Switches for @code{gnatchop}
10829 @command{gnatchop} recognizes the following switches:
10835 @cindex @option{--version} @command{gnatchop}
10836 Display Copyright and version, then exit disregarding all other options.
10839 @cindex @option{--help} @command{gnatchop}
10840 If @option{--version} was not used, display usage, then exit disregarding
10843 @item ^-c^/COMPILATION^
10844 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10845 Causes @code{gnatchop} to operate in compilation mode, in which
10846 configuration pragmas are handled according to strict RM rules. See
10847 previous section for a full description of this mode.
10850 @item -gnat@var{xxx}
10851 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
10852 used to parse the given file. Not all @var{xxx} options make sense,
10853 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10854 process a source file that uses Latin-2 coding for identifiers.
10858 Causes @code{gnatchop} to generate a brief help summary to the standard
10859 output file showing usage information.
10861 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10862 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10863 Limit generated file names to the specified number @code{mm}
10865 This is useful if the
10866 resulting set of files is required to be interoperable with systems
10867 which limit the length of file names.
10869 If no value is given, or
10870 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10871 a default of 39, suitable for OpenVMS Alpha
10872 Systems, is assumed
10875 No space is allowed between the @option{-k} and the numeric value. The numeric
10876 value may be omitted in which case a default of @option{-k8},
10878 with DOS-like file systems, is used. If no @option{-k} switch
10880 there is no limit on the length of file names.
10883 @item ^-p^/PRESERVE^
10884 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10885 Causes the file ^modification^creation^ time stamp of the input file to be
10886 preserved and used for the time stamp of the output file(s). This may be
10887 useful for preserving coherency of time stamps in an environment where
10888 @code{gnatchop} is used as part of a standard build process.
10891 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10892 Causes output of informational messages indicating the set of generated
10893 files to be suppressed. Warnings and error messages are unaffected.
10895 @item ^-r^/REFERENCE^
10896 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10897 @findex Source_Reference
10898 Generate @code{Source_Reference} pragmas. Use this switch if the output
10899 files are regarded as temporary and development is to be done in terms
10900 of the original unchopped file. This switch causes
10901 @code{Source_Reference} pragmas to be inserted into each of the
10902 generated files to refers back to the original file name and line number.
10903 The result is that all error messages refer back to the original
10905 In addition, the debugging information placed into the object file (when
10906 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10908 also refers back to this original file so that tools like profilers and
10909 debuggers will give information in terms of the original unchopped file.
10911 If the original file to be chopped itself contains
10912 a @code{Source_Reference}
10913 pragma referencing a third file, then gnatchop respects
10914 this pragma, and the generated @code{Source_Reference} pragmas
10915 in the chopped file refer to the original file, with appropriate
10916 line numbers. This is particularly useful when @code{gnatchop}
10917 is used in conjunction with @code{gnatprep} to compile files that
10918 contain preprocessing statements and multiple units.
10920 @item ^-v^/VERBOSE^
10921 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10922 Causes @code{gnatchop} to operate in verbose mode. The version
10923 number and copyright notice are output, as well as exact copies of
10924 the gnat1 commands spawned to obtain the chop control information.
10926 @item ^-w^/OVERWRITE^
10927 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10928 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10929 fatal error if there is already a file with the same name as a
10930 file it would otherwise output, in other words if the files to be
10931 chopped contain duplicated units. This switch bypasses this
10932 check, and causes all but the last instance of such duplicated
10933 units to be skipped.
10936 @item --GCC=@var{xxxx}
10937 @cindex @option{--GCC=} (@code{gnatchop})
10938 Specify the path of the GNAT parser to be used. When this switch is used,
10939 no attempt is made to add the prefix to the GNAT parser executable.
10943 @node Examples of gnatchop Usage
10944 @section Examples of @code{gnatchop} Usage
10948 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10951 @item gnatchop -w hello_s.ada prerelease/files
10954 Chops the source file @file{hello_s.ada}. The output files will be
10955 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10957 files with matching names in that directory (no files in the current
10958 directory are modified).
10960 @item gnatchop ^archive^ARCHIVE.^
10961 Chops the source file @file{^archive^ARCHIVE.^}
10962 into the current directory. One
10963 useful application of @code{gnatchop} is in sending sets of sources
10964 around, for example in email messages. The required sources are simply
10965 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10967 @command{gnatchop} is used at the other end to reconstitute the original
10970 @item gnatchop file1 file2 file3 direc
10971 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10972 the resulting files in the directory @file{direc}. Note that if any units
10973 occur more than once anywhere within this set of files, an error message
10974 is generated, and no files are written. To override this check, use the
10975 @option{^-w^/OVERWRITE^} switch,
10976 in which case the last occurrence in the last file will
10977 be the one that is output, and earlier duplicate occurrences for a given
10978 unit will be skipped.
10981 @node Configuration Pragmas
10982 @chapter Configuration Pragmas
10983 @cindex Configuration pragmas
10984 @cindex Pragmas, configuration
10987 Configuration pragmas include those pragmas described as
10988 such in the Ada Reference Manual, as well as
10989 implementation-dependent pragmas that are configuration pragmas.
10990 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
10991 for details on these additional GNAT-specific configuration pragmas.
10992 Most notably, the pragma @code{Source_File_Name}, which allows
10993 specifying non-default names for source files, is a configuration
10994 pragma. The following is a complete list of configuration pragmas
10995 recognized by GNAT:
11007 Compile_Time_Warning
11009 Component_Alignment
11016 External_Name_Casing
11019 Float_Representation
11032 Priority_Specific_Dispatching
11035 Propagate_Exceptions
11038 Restricted_Run_Time
11040 Restrictions_Warnings
11043 Source_File_Name_Project
11046 Suppress_Exception_Locations
11047 Task_Dispatching_Policy
11053 Wide_Character_Encoding
11058 * Handling of Configuration Pragmas::
11059 * The Configuration Pragmas Files::
11062 @node Handling of Configuration Pragmas
11063 @section Handling of Configuration Pragmas
11065 Configuration pragmas may either appear at the start of a compilation
11066 unit, in which case they apply only to that unit, or they may apply to
11067 all compilations performed in a given compilation environment.
11069 GNAT also provides the @code{gnatchop} utility to provide an automatic
11070 way to handle configuration pragmas following the semantics for
11071 compilations (that is, files with multiple units), described in the RM.
11072 See @ref{Operating gnatchop in Compilation Mode} for details.
11073 However, for most purposes, it will be more convenient to edit the
11074 @file{gnat.adc} file that contains configuration pragmas directly,
11075 as described in the following section.
11077 @node The Configuration Pragmas Files
11078 @section The Configuration Pragmas Files
11079 @cindex @file{gnat.adc}
11082 In GNAT a compilation environment is defined by the current
11083 directory at the time that a compile command is given. This current
11084 directory is searched for a file whose name is @file{gnat.adc}. If
11085 this file is present, it is expected to contain one or more
11086 configuration pragmas that will be applied to the current compilation.
11087 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11090 Configuration pragmas may be entered into the @file{gnat.adc} file
11091 either by running @code{gnatchop} on a source file that consists only of
11092 configuration pragmas, or more conveniently by
11093 direct editing of the @file{gnat.adc} file, which is a standard format
11096 In addition to @file{gnat.adc}, additional files containing configuration
11097 pragmas may be applied to the current compilation using the switch
11098 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11099 contains only configuration pragmas. These configuration pragmas are
11100 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11101 is present and switch @option{-gnatA} is not used).
11103 It is allowed to specify several switches @option{-gnatec}, all of which
11104 will be taken into account.
11106 If you are using project file, a separate mechanism is provided using
11107 project attributes, see @ref{Specifying Configuration Pragmas} for more
11111 Of special interest to GNAT OpenVMS Alpha is the following
11112 configuration pragma:
11114 @smallexample @c ada
11116 pragma Extend_System (Aux_DEC);
11121 In the presence of this pragma, GNAT adds to the definition of the
11122 predefined package SYSTEM all the additional types and subprograms that are
11123 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11126 @node Handling Arbitrary File Naming Conventions Using gnatname
11127 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11128 @cindex Arbitrary File Naming Conventions
11131 * Arbitrary File Naming Conventions::
11132 * Running gnatname::
11133 * Switches for gnatname::
11134 * Examples of gnatname Usage::
11137 @node Arbitrary File Naming Conventions
11138 @section Arbitrary File Naming Conventions
11141 The GNAT compiler must be able to know the source file name of a compilation
11142 unit. When using the standard GNAT default file naming conventions
11143 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11144 does not need additional information.
11147 When the source file names do not follow the standard GNAT default file naming
11148 conventions, the GNAT compiler must be given additional information through
11149 a configuration pragmas file (@pxref{Configuration Pragmas})
11151 When the non-standard file naming conventions are well-defined,
11152 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11153 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11154 if the file naming conventions are irregular or arbitrary, a number
11155 of pragma @code{Source_File_Name} for individual compilation units
11157 To help maintain the correspondence between compilation unit names and
11158 source file names within the compiler,
11159 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11162 @node Running gnatname
11163 @section Running @code{gnatname}
11166 The usual form of the @code{gnatname} command is
11169 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11170 @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11174 All of the arguments are optional. If invoked without any argument,
11175 @code{gnatname} will display its usage.
11178 When used with at least one naming pattern, @code{gnatname} will attempt to
11179 find all the compilation units in files that follow at least one of the
11180 naming patterns. To find these compilation units,
11181 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11185 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11186 Each Naming Pattern is enclosed between double quotes.
11187 A Naming Pattern is a regular expression similar to the wildcard patterns
11188 used in file names by the Unix shells or the DOS prompt.
11191 @code{gnatname} may be called with several sections of directories/patterns.
11192 Sections are separated by switch @code{--and}. In each section, there must be
11193 at least one pattern. If no directory is specified in a section, the current
11194 directory (or the project directory is @code{-P} is used) is implied.
11195 The options other that the directory switches and the patterns apply globally
11196 even if they are in different sections.
11199 Examples of Naming Patterns are
11208 For a more complete description of the syntax of Naming Patterns,
11209 see the second kind of regular expressions described in @file{g-regexp.ads}
11210 (the ``Glob'' regular expressions).
11213 When invoked with no switch @code{-P}, @code{gnatname} will create a
11214 configuration pragmas file @file{gnat.adc} in the current working directory,
11215 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11218 @node Switches for gnatname
11219 @section Switches for @code{gnatname}
11222 Switches for @code{gnatname} must precede any specified Naming Pattern.
11225 You may specify any of the following switches to @code{gnatname}:
11231 @cindex @option{--version} @command{gnatname}
11232 Display Copyright and version, then exit disregarding all other options.
11235 @cindex @option{--help} @command{gnatname}
11236 If @option{--version} was not used, display usage, then exit disregarding
11240 Start another section of directories/patterns.
11242 @item ^-c^/CONFIG_FILE=^@file{file}
11243 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11244 Create a configuration pragmas file @file{file} (instead of the default
11247 There may be zero, one or more space between @option{-c} and
11250 @file{file} may include directory information. @file{file} must be
11251 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11252 When a switch @option{^-c^/CONFIG_FILE^} is
11253 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11255 @item ^-d^/SOURCE_DIRS=^@file{dir}
11256 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11257 Look for source files in directory @file{dir}. There may be zero, one or more
11258 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11259 When a switch @option{^-d^/SOURCE_DIRS^}
11260 is specified, the current working directory will not be searched for source
11261 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11262 or @option{^-D^/DIR_FILES^} switch.
11263 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11264 If @file{dir} is a relative path, it is relative to the directory of
11265 the configuration pragmas file specified with switch
11266 @option{^-c^/CONFIG_FILE^},
11267 or to the directory of the project file specified with switch
11268 @option{^-P^/PROJECT_FILE^} or,
11269 if neither switch @option{^-c^/CONFIG_FILE^}
11270 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11271 current working directory. The directory
11272 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11274 @item ^-D^/DIRS_FILE=^@file{file}
11275 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11276 Look for source files in all directories listed in text file @file{file}.
11277 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11279 @file{file} must be an existing, readable text file.
11280 Each nonempty line in @file{file} must be a directory.
11281 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11282 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11285 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11286 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11287 Foreign patterns. Using this switch, it is possible to add sources of languages
11288 other than Ada to the list of sources of a project file.
11289 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11292 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11295 will look for Ada units in all files with the @file{.ada} extension,
11296 and will add to the list of file for project @file{prj.gpr} the C files
11297 with extension @file{.^c^C^}.
11300 @cindex @option{^-h^/HELP^} (@code{gnatname})
11301 Output usage (help) information. The output is written to @file{stdout}.
11303 @item ^-P^/PROJECT_FILE=^@file{proj}
11304 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11305 Create or update project file @file{proj}. There may be zero, one or more space
11306 between @option{-P} and @file{proj}. @file{proj} may include directory
11307 information. @file{proj} must be writable.
11308 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11309 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11310 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11312 @item ^-v^/VERBOSE^
11313 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11314 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11315 This includes name of the file written, the name of the directories to search
11316 and, for each file in those directories whose name matches at least one of
11317 the Naming Patterns, an indication of whether the file contains a unit,
11318 and if so the name of the unit.
11320 @item ^-v -v^/VERBOSE /VERBOSE^
11321 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11322 Very Verbose mode. In addition to the output produced in verbose mode,
11323 for each file in the searched directories whose name matches none of
11324 the Naming Patterns, an indication is given that there is no match.
11326 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11327 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11328 Excluded patterns. Using this switch, it is possible to exclude some files
11329 that would match the name patterns. For example,
11331 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11334 will look for Ada units in all files with the @file{.ada} extension,
11335 except those whose names end with @file{_nt.ada}.
11339 @node Examples of gnatname Usage
11340 @section Examples of @code{gnatname} Usage
11344 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11350 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11355 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11356 and be writable. In addition, the directory
11357 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11358 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11361 Note the optional spaces after @option{-c} and @option{-d}.
11366 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11367 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11370 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
11371 /EXCLUDED_PATTERN=*_nt_body.ada
11372 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11373 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11377 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11378 even in conjunction with one or several switches
11379 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11380 are used in this example.
11382 @c *****************************************
11383 @c * G N A T P r o j e c t M a n a g e r *
11384 @c *****************************************
11385 @node GNAT Project Manager
11386 @chapter GNAT Project Manager
11390 * Examples of Project Files::
11391 * Project File Syntax::
11392 * Objects and Sources in Project Files::
11393 * Importing Projects::
11394 * Project Extension::
11395 * Project Hierarchy Extension::
11396 * External References in Project Files::
11397 * Packages in Project Files::
11398 * Variables from Imported Projects::
11400 * Library Projects::
11401 * Stand-alone Library Projects::
11402 * Switches Related to Project Files::
11403 * Tools Supporting Project Files::
11404 * An Extended Example::
11405 * Project File Complete Syntax::
11408 @c ****************
11409 @c * Introduction *
11410 @c ****************
11413 @section Introduction
11416 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11417 you to manage complex builds involving a number of source files, directories,
11418 and compilation options for different system configurations. In particular,
11419 project files allow you to specify:
11422 The directory or set of directories containing the source files, and/or the
11423 names of the specific source files themselves
11425 The directory in which the compiler's output
11426 (@file{ALI} files, object files, tree files) is to be placed
11428 The directory in which the executable programs is to be placed
11430 ^Switch^Switch^ settings for any of the project-enabled tools
11431 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11432 @code{gnatfind}); you can apply these settings either globally or to individual
11435 The source files containing the main subprogram(s) to be built
11437 The source programming language(s) (currently Ada and/or C)
11439 Source file naming conventions; you can specify these either globally or for
11440 individual compilation units
11447 @node Project Files
11448 @subsection Project Files
11451 Project files are written in a syntax close to that of Ada, using familiar
11452 notions such as packages, context clauses, declarations, default values,
11453 assignments, and inheritance. Finally, project files can be built
11454 hierarchically from other project files, simplifying complex system
11455 integration and project reuse.
11457 A @dfn{project} is a specific set of values for various compilation properties.
11458 The settings for a given project are described by means of
11459 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11460 Property values in project files are either strings or lists of strings.
11461 Properties that are not explicitly set receive default values. A project
11462 file may interrogate the values of @dfn{external variables} (user-defined
11463 command-line switches or environment variables), and it may specify property
11464 settings conditionally, based on the value of such variables.
11466 In simple cases, a project's source files depend only on other source files
11467 in the same project, or on the predefined libraries. (@emph{Dependence} is
11469 the Ada technical sense; as in one Ada unit @code{with}ing another.) However,
11470 the Project Manager also allows more sophisticated arrangements,
11471 where the source files in one project depend on source files in other
11475 One project can @emph{import} other projects containing needed source files.
11477 You can organize GNAT projects in a hierarchy: a @emph{child} project
11478 can extend a @emph{parent} project, inheriting the parent's source files and
11479 optionally overriding any of them with alternative versions
11483 More generally, the Project Manager lets you structure large development
11484 efforts into hierarchical subsystems, where build decisions are delegated
11485 to the subsystem level, and thus different compilation environments
11486 (^switch^switch^ settings) used for different subsystems.
11488 The Project Manager is invoked through the
11489 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11490 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11492 There may be zero, one or more spaces between @option{-P} and
11493 @option{@emph{projectfile}}.
11495 If you want to define (on the command line) an external variable that is
11496 queried by the project file, you must use the
11497 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11498 The Project Manager parses and interprets the project file, and drives the
11499 invoked tool based on the project settings.
11501 The Project Manager supports a wide range of development strategies,
11502 for systems of all sizes. Here are some typical practices that are
11506 Using a common set of source files, but generating object files in different
11507 directories via different ^switch^switch^ settings
11509 Using a mostly-shared set of source files, but with different versions of
11514 The destination of an executable can be controlled inside a project file
11515 using the @option{^-o^-o^}
11517 In the absence of such a ^switch^switch^ either inside
11518 the project file or on the command line, any executable files generated by
11519 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11520 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11521 in the object directory of the project.
11523 You can use project files to achieve some of the effects of a source
11524 versioning system (for example, defining separate projects for
11525 the different sets of sources that comprise different releases) but the
11526 Project Manager is independent of any source configuration management tools
11527 that might be used by the developers.
11529 The next section introduces the main features of GNAT's project facility
11530 through a sequence of examples; subsequent sections will present the syntax
11531 and semantics in more detail. A more formal description of the project
11532 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11535 @c *****************************
11536 @c * Examples of Project Files *
11537 @c *****************************
11539 @node Examples of Project Files
11540 @section Examples of Project Files
11542 This section illustrates some of the typical uses of project files and
11543 explains their basic structure and behavior.
11546 * Common Sources with Different ^Switches^Switches^ and Directories::
11547 * Using External Variables::
11548 * Importing Other Projects::
11549 * Extending a Project::
11552 @node Common Sources with Different ^Switches^Switches^ and Directories
11553 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11557 * Specifying the Object Directory::
11558 * Specifying the Exec Directory::
11559 * Project File Packages::
11560 * Specifying ^Switch^Switch^ Settings::
11561 * Main Subprograms::
11562 * Executable File Names::
11563 * Source File Naming Conventions::
11564 * Source Language(s)::
11568 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11569 @file{proc.adb} are in the @file{/common} directory. The file
11570 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11571 package @code{Pack}. We want to compile these source files under two sets
11572 of ^switches^switches^:
11575 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11576 and the @option{^-gnata^-gnata^},
11577 @option{^-gnato^-gnato^},
11578 and @option{^-gnatE^-gnatE^} switches to the
11579 compiler; the compiler's output is to appear in @file{/common/debug}
11581 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11582 to the compiler; the compiler's output is to appear in @file{/common/release}
11586 The GNAT project files shown below, respectively @file{debug.gpr} and
11587 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11600 ^/common/debug^[COMMON.DEBUG]^
11605 ^/common/release^[COMMON.RELEASE]^
11610 Here are the corresponding project files:
11612 @smallexample @c projectfile
11615 for Object_Dir use "debug";
11616 for Main use ("proc");
11619 for ^Default_Switches^Default_Switches^ ("Ada")
11621 for Executable ("proc.adb") use "proc1";
11626 package Compiler is
11627 for ^Default_Switches^Default_Switches^ ("Ada")
11628 use ("-fstack-check",
11631 "^-gnatE^-gnatE^");
11637 @smallexample @c projectfile
11640 for Object_Dir use "release";
11641 for Exec_Dir use ".";
11642 for Main use ("proc");
11644 package Compiler is
11645 for ^Default_Switches^Default_Switches^ ("Ada")
11653 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11654 insensitive), and analogously the project defined by @file{release.gpr} is
11655 @code{"Release"}. For consistency the file should have the same name as the
11656 project, and the project file's extension should be @code{"gpr"}. These
11657 conventions are not required, but a warning is issued if they are not followed.
11659 If the current directory is @file{^/temp^[TEMP]^}, then the command
11661 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11665 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11666 as well as the @code{^proc1^PROC1.EXE^} executable,
11667 using the ^switch^switch^ settings defined in the project file.
11669 Likewise, the command
11671 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11675 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11676 and the @code{^proc^PROC.EXE^}
11677 executable in @file{^/common^[COMMON]^},
11678 using the ^switch^switch^ settings from the project file.
11681 @unnumberedsubsubsec Source Files
11684 If a project file does not explicitly specify a set of source directories or
11685 a set of source files, then by default the project's source files are the
11686 Ada source files in the project file directory. Thus @file{pack.ads},
11687 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11689 @node Specifying the Object Directory
11690 @unnumberedsubsubsec Specifying the Object Directory
11693 Several project properties are modeled by Ada-style @emph{attributes};
11694 a property is defined by supplying the equivalent of an Ada attribute
11695 definition clause in the project file.
11696 A project's object directory is another such a property; the corresponding
11697 attribute is @code{Object_Dir}, and its value is also a string expression,
11698 specified either as absolute or relative. In the later case,
11699 it is relative to the project file directory. Thus the compiler's
11700 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11701 (for the @code{Debug} project)
11702 and to @file{^/common/release^[COMMON.RELEASE]^}
11703 (for the @code{Release} project).
11704 If @code{Object_Dir} is not specified, then the default is the project file
11707 @node Specifying the Exec Directory
11708 @unnumberedsubsubsec Specifying the Exec Directory
11711 A project's exec directory is another property; the corresponding
11712 attribute is @code{Exec_Dir}, and its value is also a string expression,
11713 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11714 then the default is the object directory (which may also be the project file
11715 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11716 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11717 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11718 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11720 @node Project File Packages
11721 @unnumberedsubsubsec Project File Packages
11724 A GNAT tool that is integrated with the Project Manager is modeled by a
11725 corresponding package in the project file. In the example above,
11726 The @code{Debug} project defines the packages @code{Builder}
11727 (for @command{gnatmake}) and @code{Compiler};
11728 the @code{Release} project defines only the @code{Compiler} package.
11730 The Ada-like package syntax is not to be taken literally. Although packages in
11731 project files bear a surface resemblance to packages in Ada source code, the
11732 notation is simply a way to convey a grouping of properties for a named
11733 entity. Indeed, the package names permitted in project files are restricted
11734 to a predefined set, corresponding to the project-aware tools, and the contents
11735 of packages are limited to a small set of constructs.
11736 The packages in the example above contain attribute definitions.
11738 @node Specifying ^Switch^Switch^ Settings
11739 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11742 ^Switch^Switch^ settings for a project-aware tool can be specified through
11743 attributes in the package that corresponds to the tool.
11744 The example above illustrates one of the relevant attributes,
11745 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11746 in both project files.
11747 Unlike simple attributes like @code{Source_Dirs},
11748 @code{^Default_Switches^Default_Switches^} is
11749 known as an @emph{associative array}. When you define this attribute, you must
11750 supply an ``index'' (a literal string), and the effect of the attribute
11751 definition is to set the value of the array at the specified index.
11752 For the @code{^Default_Switches^Default_Switches^} attribute,
11753 the index is a programming language (in our case, Ada),
11754 and the value specified (after @code{use}) must be a list
11755 of string expressions.
11757 The attributes permitted in project files are restricted to a predefined set.
11758 Some may appear at project level, others in packages.
11759 For any attribute that is an associative array, the index must always be a
11760 literal string, but the restrictions on this string (e.g., a file name or a
11761 language name) depend on the individual attribute.
11762 Also depending on the attribute, its specified value will need to be either a
11763 string or a string list.
11765 In the @code{Debug} project, we set the switches for two tools,
11766 @command{gnatmake} and the compiler, and thus we include the two corresponding
11767 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11768 attribute with index @code{"Ada"}.
11769 Note that the package corresponding to
11770 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
11771 similar, but only includes the @code{Compiler} package.
11773 In project @code{Debug} above, the ^switches^switches^ starting with
11774 @option{-gnat} that are specified in package @code{Compiler}
11775 could have been placed in package @code{Builder}, since @command{gnatmake}
11776 transmits all such ^switches^switches^ to the compiler.
11778 @node Main Subprograms
11779 @unnumberedsubsubsec Main Subprograms
11782 One of the specifiable properties of a project is a list of files that contain
11783 main subprograms. This property is captured in the @code{Main} attribute,
11784 whose value is a list of strings. If a project defines the @code{Main}
11785 attribute, it is not necessary to identify the main subprogram(s) when
11786 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11788 @node Executable File Names
11789 @unnumberedsubsubsec Executable File Names
11792 By default, the executable file name corresponding to a main source is
11793 deduced from the main source file name. Through the attributes
11794 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11795 it is possible to change this default.
11796 In project @code{Debug} above, the executable file name
11797 for main source @file{^proc.adb^PROC.ADB^} is
11798 @file{^proc1^PROC1.EXE^}.
11799 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11800 of the executable files, when no attribute @code{Executable} applies:
11801 its value replace the platform-specific executable suffix.
11802 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11803 specify a non-default executable file name when several mains are built at once
11804 in a single @command{gnatmake} command.
11806 @node Source File Naming Conventions
11807 @unnumberedsubsubsec Source File Naming Conventions
11810 Since the project files above do not specify any source file naming
11811 conventions, the GNAT defaults are used. The mechanism for defining source
11812 file naming conventions -- a package named @code{Naming} --
11813 is described below (@pxref{Naming Schemes}).
11815 @node Source Language(s)
11816 @unnumberedsubsubsec Source Language(s)
11819 Since the project files do not specify a @code{Languages} attribute, by
11820 default the GNAT tools assume that the language of the project file is Ada.
11821 More generally, a project can comprise source files
11822 in Ada, C, and/or other languages.
11824 @node Using External Variables
11825 @subsection Using External Variables
11828 Instead of supplying different project files for debug and release, we can
11829 define a single project file that queries an external variable (set either
11830 on the command line or via an ^environment variable^logical name^) in order to
11831 conditionally define the appropriate settings. Again, assume that the
11832 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11833 located in directory @file{^/common^[COMMON]^}. The following project file,
11834 @file{build.gpr}, queries the external variable named @code{STYLE} and
11835 defines an object directory and ^switch^switch^ settings based on whether
11836 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11837 the default is @code{"deb"}.
11839 @smallexample @c projectfile
11842 for Main use ("proc");
11844 type Style_Type is ("deb", "rel");
11845 Style : Style_Type := external ("STYLE", "deb");
11849 for Object_Dir use "debug";
11852 for Object_Dir use "release";
11853 for Exec_Dir use ".";
11862 for ^Default_Switches^Default_Switches^ ("Ada")
11864 for Executable ("proc") use "proc1";
11873 package Compiler is
11877 for ^Default_Switches^Default_Switches^ ("Ada")
11878 use ("^-gnata^-gnata^",
11880 "^-gnatE^-gnatE^");
11883 for ^Default_Switches^Default_Switches^ ("Ada")
11894 @code{Style_Type} is an example of a @emph{string type}, which is the project
11895 file analog of an Ada enumeration type but whose components are string literals
11896 rather than identifiers. @code{Style} is declared as a variable of this type.
11898 The form @code{external("STYLE", "deb")} is known as an
11899 @emph{external reference}; its first argument is the name of an
11900 @emph{external variable}, and the second argument is a default value to be
11901 used if the external variable doesn't exist. You can define an external
11902 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11903 or you can use ^an environment variable^a logical name^
11904 as an external variable.
11906 Each @code{case} construct is expanded by the Project Manager based on the
11907 value of @code{Style}. Thus the command
11910 gnatmake -P/common/build.gpr -XSTYLE=deb
11916 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11921 is equivalent to the @command{gnatmake} invocation using the project file
11922 @file{debug.gpr} in the earlier example. So is the command
11924 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11928 since @code{"deb"} is the default for @code{STYLE}.
11934 gnatmake -P/common/build.gpr -XSTYLE=rel
11940 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11945 is equivalent to the @command{gnatmake} invocation using the project file
11946 @file{release.gpr} in the earlier example.
11948 @node Importing Other Projects
11949 @subsection Importing Other Projects
11950 @cindex @code{ADA_PROJECT_PATH}
11953 A compilation unit in a source file in one project may depend on compilation
11954 units in source files in other projects. To compile this unit under
11955 control of a project file, the
11956 dependent project must @emph{import} the projects containing the needed source
11958 This effect is obtained using syntax similar to an Ada @code{with} clause,
11959 but where @code{with}ed entities are strings that denote project files.
11961 As an example, suppose that the two projects @code{GUI_Proj} and
11962 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11963 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11964 and @file{^/comm^[COMM]^}, respectively.
11965 Suppose that the source files for @code{GUI_Proj} are
11966 @file{gui.ads} and @file{gui.adb}, and that the source files for
11967 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11968 files is located in its respective project file directory. Schematically:
11987 We want to develop an application in directory @file{^/app^[APP]^} that
11988 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11989 the corresponding project files (e.g.@: the ^switch^switch^ settings
11990 and object directory).
11991 Skeletal code for a main procedure might be something like the following:
11993 @smallexample @c ada
11996 procedure App_Main is
12005 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12008 @smallexample @c projectfile
12010 with "/gui/gui_proj", "/comm/comm_proj";
12011 project App_Proj is
12012 for Main use ("app_main");
12018 Building an executable is achieved through the command:
12020 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12023 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12024 in the directory where @file{app_proj.gpr} resides.
12026 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12027 (as illustrated above) the @code{with} clause can omit the extension.
12029 Our example specified an absolute path for each imported project file.
12030 Alternatively, the directory name of an imported object can be omitted
12034 The imported project file is in the same directory as the importing project
12037 You have defined ^an environment variable^a logical name^
12038 that includes the directory containing
12039 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12040 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12041 directory names separated by colons (semicolons on Windows).
12045 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12046 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12049 @smallexample @c projectfile
12051 with "gui_proj", "comm_proj";
12052 project App_Proj is
12053 for Main use ("app_main");
12059 Importing other projects can create ambiguities.
12060 For example, the same unit might be present in different imported projects, or
12061 it might be present in both the importing project and in an imported project.
12062 Both of these conditions are errors. Note that in the current version of
12063 the Project Manager, it is illegal to have an ambiguous unit even if the
12064 unit is never referenced by the importing project. This restriction may be
12065 relaxed in a future release.
12067 @node Extending a Project
12068 @subsection Extending a Project
12071 In large software systems it is common to have multiple
12072 implementations of a common interface; in Ada terms, multiple versions of a
12073 package body for the same spec. For example, one implementation
12074 might be safe for use in tasking programs, while another might only be used
12075 in sequential applications. This can be modeled in GNAT using the concept
12076 of @emph{project extension}. If one project (the ``child'') @emph{extends}
12077 another project (the ``parent'') then by default all source files of the
12078 parent project are inherited by the child, but the child project can
12079 override any of the parent's source files with new versions, and can also
12080 add new files. This facility is the project analog of a type extension in
12081 Object-Oriented Programming. Project hierarchies are permitted (a child
12082 project may be the parent of yet another project), and a project that
12083 inherits one project can also import other projects.
12085 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12086 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12087 @file{pack.adb}, and @file{proc.adb}:
12100 Note that the project file can simply be empty (that is, no attribute or
12101 package is defined):
12103 @smallexample @c projectfile
12105 project Seq_Proj is
12111 implying that its source files are all the Ada source files in the project
12114 Suppose we want to supply an alternate version of @file{pack.adb}, in
12115 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12116 @file{pack.ads} and @file{proc.adb}. We can define a project
12117 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12121 ^/tasking^[TASKING]^
12127 project Tasking_Proj extends "/seq/seq_proj" is
12133 The version of @file{pack.adb} used in a build depends on which project file
12136 Note that we could have obtained the desired behavior using project import
12137 rather than project inheritance; a @code{base} project would contain the
12138 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12139 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12140 would import @code{base} and add a different version of @file{pack.adb}. The
12141 choice depends on whether other sources in the original project need to be
12142 overridden. If they do, then project extension is necessary, otherwise,
12143 importing is sufficient.
12146 In a project file that extends another project file, it is possible to
12147 indicate that an inherited source is not part of the sources of the extending
12148 project. This is necessary sometimes when a package spec has been overloaded
12149 and no longer requires a body: in this case, it is necessary to indicate that
12150 the inherited body is not part of the sources of the project, otherwise there
12151 will be a compilation error when compiling the spec.
12153 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12154 Its value is a string list: a list of file names. It is also possible to use
12155 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12156 the file name of a text file containing a list of file names, one per line.
12158 @smallexample @c @projectfile
12159 project B extends "a" is
12160 for Source_Files use ("pkg.ads");
12161 -- New spec of Pkg does not need a completion
12162 for Excluded_Source_Files use ("pkg.adb");
12166 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12167 is still needed: if it is possible to build using @command{gnatmake} when such
12168 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12169 it is possible to remove the source completely from a system that includes
12172 @c ***********************
12173 @c * Project File Syntax *
12174 @c ***********************
12176 @node Project File Syntax
12177 @section Project File Syntax
12181 * Qualified Projects::
12187 * Associative Array Attributes::
12188 * case Constructions::
12192 This section describes the structure of project files.
12194 A project may be an @emph{independent project}, entirely defined by a single
12195 project file. Any Ada source file in an independent project depends only
12196 on the predefined library and other Ada source files in the same project.
12199 A project may also @dfn{depend on} other projects, in either or both of
12200 the following ways:
12202 @item It may import any number of projects
12203 @item It may extend at most one other project
12207 The dependence relation is a directed acyclic graph (the subgraph reflecting
12208 the ``extends'' relation is a tree).
12210 A project's @dfn{immediate sources} are the source files directly defined by
12211 that project, either implicitly by residing in the project file's directory,
12212 or explicitly through any of the source-related attributes described below.
12213 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12214 of @var{proj} together with the immediate sources (unless overridden) of any
12215 project on which @var{proj} depends (either directly or indirectly).
12218 @subsection Basic Syntax
12221 As seen in the earlier examples, project files have an Ada-like syntax.
12222 The minimal project file is:
12223 @smallexample @c projectfile
12232 The identifier @code{Empty} is the name of the project.
12233 This project name must be present after the reserved
12234 word @code{end} at the end of the project file, followed by a semi-colon.
12236 Any name in a project file, such as the project name or a variable name,
12237 has the same syntax as an Ada identifier.
12239 The reserved words of project files are the Ada 95 reserved words plus
12240 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
12241 reserved words currently used in project file syntax are:
12277 Comments in project files have the same syntax as in Ada, two consecutive
12278 hyphens through the end of the line.
12280 @node Qualified Projects
12281 @subsection Qualified Projects
12284 Before the reserved @code{project}, there may be one or two "qualifiers", that
12285 is identifiers or other reserved words, to qualify the project.
12287 The current list of qualifiers is:
12291 @code{abstract}: qualify a project with no sources. An abstract project must
12292 have a declaration specifying that there are no sources in the project, and,
12293 if it extends another project, the project it extends must also be a qualified
12297 @code{standard}: a standard project is a non library project with sources.
12300 @code{aggregate}: for future extension
12303 @code{aggregate library}: for future extension
12306 @code{library}: a library project must declare both attributes
12307 @code{Library_Name} and @code{Library_Dir}.
12310 @code{configuration}: a configuration project cannot be in a project tree.
12314 @subsection Packages
12317 A project file may contain @emph{packages}. The name of a package must be one
12318 of the identifiers from the following list. A package
12319 with a given name may only appear once in a project file. Package names are
12320 case insensitive. The following package names are legal:
12336 @code{Cross_Reference}
12340 @code{Pretty_Printer}
12350 @code{Language_Processing}
12354 In its simplest form, a package may be empty:
12356 @smallexample @c projectfile
12366 A package may contain @emph{attribute declarations},
12367 @emph{variable declarations} and @emph{case constructions}, as will be
12370 When there is ambiguity between a project name and a package name,
12371 the name always designates the project. To avoid possible confusion, it is
12372 always a good idea to avoid naming a project with one of the
12373 names allowed for packages or any name that starts with @code{gnat}.
12376 @subsection Expressions
12379 An @emph{expression} is either a @emph{string expression} or a
12380 @emph{string list expression}.
12382 A @emph{string expression} is either a @emph{simple string expression} or a
12383 @emph{compound string expression}.
12385 A @emph{simple string expression} is one of the following:
12387 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12388 @item A string-valued variable reference (@pxref{Variables})
12389 @item A string-valued attribute reference (@pxref{Attributes})
12390 @item An external reference (@pxref{External References in Project Files})
12394 A @emph{compound string expression} is a concatenation of string expressions,
12395 using the operator @code{"&"}
12397 Path & "/" & File_Name & ".ads"
12401 A @emph{string list expression} is either a
12402 @emph{simple string list expression} or a
12403 @emph{compound string list expression}.
12405 A @emph{simple string list expression} is one of the following:
12407 @item A parenthesized list of zero or more string expressions,
12408 separated by commas
12410 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12413 @item A string list-valued variable reference
12414 @item A string list-valued attribute reference
12418 A @emph{compound string list expression} is the concatenation (using
12419 @code{"&"}) of a simple string list expression and an expression. Note that
12420 each term in a compound string list expression, except the first, may be
12421 either a string expression or a string list expression.
12423 @smallexample @c projectfile
12425 File_Name_List := () & File_Name; -- One string in this list
12426 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12428 Big_List := File_Name_List & Extended_File_Name_List;
12429 -- Concatenation of two string lists: three strings
12430 Illegal_List := "gnat.adc" & Extended_File_Name_List;
12431 -- Illegal: must start with a string list
12436 @subsection String Types
12439 A @emph{string type declaration} introduces a discrete set of string literals.
12440 If a string variable is declared to have this type, its value
12441 is restricted to the given set of literals.
12443 Here is an example of a string type declaration:
12445 @smallexample @c projectfile
12446 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12450 Variables of a string type are called @emph{typed variables}; all other
12451 variables are called @emph{untyped variables}. Typed variables are
12452 particularly useful in @code{case} constructions, to support conditional
12453 attribute declarations.
12454 (@pxref{case Constructions}).
12456 The string literals in the list are case sensitive and must all be different.
12457 They may include any graphic characters allowed in Ada, including spaces.
12459 A string type may only be declared at the project level, not inside a package.
12461 A string type may be referenced by its name if it has been declared in the same
12462 project file, or by an expanded name whose prefix is the name of the project
12463 in which it is declared.
12466 @subsection Variables
12469 A variable may be declared at the project file level, or within a package.
12470 Here are some examples of variable declarations:
12472 @smallexample @c projectfile
12474 This_OS : OS := external ("OS"); -- a typed variable declaration
12475 That_OS := "GNU/Linux"; -- an untyped variable declaration
12480 The syntax of a @emph{typed variable declaration} is identical to the Ada
12481 syntax for an object declaration. By contrast, the syntax of an untyped
12482 variable declaration is identical to an Ada assignment statement. In fact,
12483 variable declarations in project files have some of the characteristics of
12484 an assignment, in that successive declarations for the same variable are
12485 allowed. Untyped variable declarations do establish the expected kind of the
12486 variable (string or string list), and successive declarations for it must
12487 respect the initial kind.
12490 A string variable declaration (typed or untyped) declares a variable
12491 whose value is a string. This variable may be used as a string expression.
12492 @smallexample @c projectfile
12493 File_Name := "readme.txt";
12494 Saved_File_Name := File_Name & ".saved";
12498 A string list variable declaration declares a variable whose value is a list
12499 of strings. The list may contain any number (zero or more) of strings.
12501 @smallexample @c projectfile
12503 List_With_One_Element := ("^-gnaty^-gnaty^");
12504 List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12505 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12506 "pack2.ada", "util_.ada", "util.ada");
12510 The same typed variable may not be declared more than once at project level,
12511 and it may not be declared more than once in any package; it is in effect
12514 The same untyped variable may be declared several times. Declarations are
12515 elaborated in the order in which they appear, so the new value replaces
12516 the old one, and any subsequent reference to the variable uses the new value.
12517 However, as noted above, if a variable has been declared as a string, all
12519 declarations must give it a string value. Similarly, if a variable has
12520 been declared as a string list, all subsequent declarations
12521 must give it a string list value.
12523 A @emph{variable reference} may take several forms:
12526 @item The simple variable name, for a variable in the current package (if any)
12527 or in the current project
12528 @item An expanded name, whose prefix is a context name.
12532 A @emph{context} may be one of the following:
12535 @item The name of an existing package in the current project
12536 @item The name of an imported project of the current project
12537 @item The name of an ancestor project (i.e., a project extended by the current
12538 project, either directly or indirectly)
12539 @item An expanded name whose prefix is an imported/parent project name, and
12540 whose selector is a package name in that project.
12544 A variable reference may be used in an expression.
12547 @subsection Attributes
12550 A project (and its packages) may have @emph{attributes} that define
12551 the project's properties. Some attributes have values that are strings;
12552 others have values that are string lists.
12554 There are two categories of attributes: @emph{simple attributes}
12555 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12557 Legal project attribute names, and attribute names for each legal package are
12558 listed below. Attributes names are case-insensitive.
12560 The following attributes are defined on projects (all are simple attributes):
12562 @multitable @columnfractions .4 .3
12563 @item @emph{Attribute Name}
12565 @item @code{Source_Files}
12567 @item @code{Source_Dirs}
12569 @item @code{Source_List_File}
12571 @item @code{Object_Dir}
12573 @item @code{Exec_Dir}
12575 @item @code{Excluded_Source_Dirs}
12577 @item @code{Excluded_Source_Files}
12579 @item @code{Excluded_Source_List_File}
12581 @item @code{Languages}
12585 @item @code{Library_Dir}
12587 @item @code{Library_Name}
12589 @item @code{Library_Kind}
12591 @item @code{Library_Version}
12593 @item @code{Library_Interface}
12595 @item @code{Library_Auto_Init}
12597 @item @code{Library_Options}
12599 @item @code{Library_Src_Dir}
12601 @item @code{Library_ALI_Dir}
12603 @item @code{Library_GCC}
12605 @item @code{Library_Symbol_File}
12607 @item @code{Library_Symbol_Policy}
12609 @item @code{Library_Reference_Symbol_File}
12611 @item @code{Externally_Built}
12616 The following attributes are defined for package @code{Naming}
12617 (@pxref{Naming Schemes}):
12619 @multitable @columnfractions .4 .2 .2 .2
12620 @item Attribute Name @tab Category @tab Index @tab Value
12621 @item @code{Spec_Suffix}
12622 @tab associative array
12625 @item @code{Body_Suffix}
12626 @tab associative array
12629 @item @code{Separate_Suffix}
12630 @tab simple attribute
12633 @item @code{Casing}
12634 @tab simple attribute
12637 @item @code{Dot_Replacement}
12638 @tab simple attribute
12642 @tab associative array
12646 @tab associative array
12649 @item @code{Specification_Exceptions}
12650 @tab associative array
12653 @item @code{Implementation_Exceptions}
12654 @tab associative array
12660 The following attributes are defined for packages @code{Builder},
12661 @code{Compiler}, @code{Binder},
12662 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12663 (@pxref{^Switches^Switches^ and Project Files}).
12665 @multitable @columnfractions .4 .2 .2 .2
12666 @item Attribute Name @tab Category @tab Index @tab Value
12667 @item @code{^Default_Switches^Default_Switches^}
12668 @tab associative array
12671 @item @code{^Switches^Switches^}
12672 @tab associative array
12678 In addition, package @code{Compiler} has a single string attribute
12679 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12680 string attribute @code{Global_Configuration_Pragmas}.
12683 Each simple attribute has a default value: the empty string (for string-valued
12684 attributes) and the empty list (for string list-valued attributes).
12686 An attribute declaration defines a new value for an attribute.
12688 Examples of simple attribute declarations:
12690 @smallexample @c projectfile
12691 for Object_Dir use "objects";
12692 for Source_Dirs use ("units", "test/drivers");
12696 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12697 attribute definition clause in Ada.
12699 Attributes references may be appear in expressions.
12700 The general form for such a reference is @code{<entity>'<attribute>}:
12701 Associative array attributes are functions. Associative
12702 array attribute references must have an argument that is a string literal.
12706 @smallexample @c projectfile
12708 Naming'Dot_Replacement
12709 Imported_Project'Source_Dirs
12710 Imported_Project.Naming'Casing
12711 Builder'^Default_Switches^Default_Switches^("Ada")
12715 The prefix of an attribute may be:
12717 @item @code{project} for an attribute of the current project
12718 @item The name of an existing package of the current project
12719 @item The name of an imported project
12720 @item The name of a parent project that is extended by the current project
12721 @item An expanded name whose prefix is imported/parent project name,
12722 and whose selector is a package name
12727 @smallexample @c projectfile
12730 for Source_Dirs use project'Source_Dirs & "units";
12731 for Source_Dirs use project'Source_Dirs & "test/drivers"
12737 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12738 has the default value: an empty string list. After this declaration,
12739 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12740 After the second attribute declaration @code{Source_Dirs} is a string list of
12741 two elements: @code{"units"} and @code{"test/drivers"}.
12743 Note: this example is for illustration only. In practice,
12744 the project file would contain only one attribute declaration:
12746 @smallexample @c projectfile
12747 for Source_Dirs use ("units", "test/drivers");
12750 @node Associative Array Attributes
12751 @subsection Associative Array Attributes
12754 Some attributes are defined as @emph{associative arrays}. An associative
12755 array may be regarded as a function that takes a string as a parameter
12756 and delivers a string or string list value as its result.
12758 Here are some examples of single associative array attribute associations:
12760 @smallexample @c projectfile
12761 for Body ("main") use "Main.ada";
12762 for ^Switches^Switches^ ("main.ada")
12764 "^-gnatv^-gnatv^");
12765 for ^Switches^Switches^ ("main.ada")
12766 use Builder'^Switches^Switches^ ("main.ada")
12771 Like untyped variables and simple attributes, associative array attributes
12772 may be declared several times. Each declaration supplies a new value for the
12773 attribute, and replaces the previous setting.
12776 An associative array attribute may be declared as a full associative array
12777 declaration, with the value of the same attribute in an imported or extended
12780 @smallexample @c projectfile
12782 for Default_Switches use Default.Builder'Default_Switches;
12787 In this example, @code{Default} must be either a project imported by the
12788 current project, or the project that the current project extends. If the
12789 attribute is in a package (in this case, in package @code{Builder}), the same
12790 package needs to be specified.
12793 A full associative array declaration replaces any other declaration for the
12794 attribute, including other full associative array declaration. Single
12795 associative array associations may be declare after a full associative
12796 declaration, modifying the value for a single association of the attribute.
12798 @node case Constructions
12799 @subsection @code{case} Constructions
12802 A @code{case} construction is used in a project file to effect conditional
12804 Here is a typical example:
12806 @smallexample @c projectfile
12809 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12811 OS : OS_Type := external ("OS", "GNU/Linux");
12815 package Compiler is
12817 when "GNU/Linux" | "Unix" =>
12818 for ^Default_Switches^Default_Switches^ ("Ada")
12819 use ("^-gnath^-gnath^");
12821 for ^Default_Switches^Default_Switches^ ("Ada")
12822 use ("^-gnatP^-gnatP^");
12831 The syntax of a @code{case} construction is based on the Ada case statement
12832 (although there is no @code{null} construction for empty alternatives).
12834 The case expression must be a typed string variable.
12835 Each alternative comprises the reserved word @code{when}, either a list of
12836 literal strings separated by the @code{"|"} character or the reserved word
12837 @code{others}, and the @code{"=>"} token.
12838 Each literal string must belong to the string type that is the type of the
12840 An @code{others} alternative, if present, must occur last.
12842 After each @code{=>}, there are zero or more constructions. The only
12843 constructions allowed in a case construction are other case constructions,
12844 attribute declarations and variable declarations. String type declarations and
12845 package declarations are not allowed. Variable declarations are restricted to
12846 variables that have already been declared before the case construction.
12848 The value of the case variable is often given by an external reference
12849 (@pxref{External References in Project Files}).
12851 @c ****************************************
12852 @c * Objects and Sources in Project Files *
12853 @c ****************************************
12855 @node Objects and Sources in Project Files
12856 @section Objects and Sources in Project Files
12859 * Object Directory::
12861 * Source Directories::
12862 * Source File Names::
12866 Each project has exactly one object directory and one or more source
12867 directories. The source directories must contain at least one source file,
12868 unless the project file explicitly specifies that no source files are present
12869 (@pxref{Source File Names}).
12871 @node Object Directory
12872 @subsection Object Directory
12875 The object directory for a project is the directory containing the compiler's
12876 output (such as @file{ALI} files and object files) for the project's immediate
12879 The object directory is given by the value of the attribute @code{Object_Dir}
12880 in the project file.
12882 @smallexample @c projectfile
12883 for Object_Dir use "objects";
12887 The attribute @code{Object_Dir} has a string value, the path name of the object
12888 directory. The path name may be absolute or relative to the directory of the
12889 project file. This directory must already exist, and be readable and writable.
12891 By default, when the attribute @code{Object_Dir} is not given an explicit value
12892 or when its value is the empty string, the object directory is the same as the
12893 directory containing the project file.
12895 @node Exec Directory
12896 @subsection Exec Directory
12899 The exec directory for a project is the directory containing the executables
12900 for the project's main subprograms.
12902 The exec directory is given by the value of the attribute @code{Exec_Dir}
12903 in the project file.
12905 @smallexample @c projectfile
12906 for Exec_Dir use "executables";
12910 The attribute @code{Exec_Dir} has a string value, the path name of the exec
12911 directory. The path name may be absolute or relative to the directory of the
12912 project file. This directory must already exist, and be writable.
12914 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12915 or when its value is the empty string, the exec directory is the same as the
12916 object directory of the project file.
12918 @node Source Directories
12919 @subsection Source Directories
12922 The source directories of a project are specified by the project file
12923 attribute @code{Source_Dirs}.
12925 This attribute's value is a string list. If the attribute is not given an
12926 explicit value, then there is only one source directory, the one where the
12927 project file resides.
12929 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12932 @smallexample @c projectfile
12933 for Source_Dirs use ();
12937 indicates that the project contains no source files.
12939 Otherwise, each string in the string list designates one or more
12940 source directories.
12942 @smallexample @c projectfile
12943 for Source_Dirs use ("sources", "test/drivers");
12947 If a string in the list ends with @code{"/**"}, then the directory whose path
12948 name precedes the two asterisks, as well as all its subdirectories
12949 (recursively), are source directories.
12951 @smallexample @c projectfile
12952 for Source_Dirs use ("/system/sources/**");
12956 Here the directory @code{/system/sources} and all of its subdirectories
12957 (recursively) are source directories.
12959 To specify that the source directories are the directory of the project file
12960 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12961 @smallexample @c projectfile
12962 for Source_Dirs use ("./**");
12966 Each of the source directories must exist and be readable.
12968 @node Source File Names
12969 @subsection Source File Names
12972 In a project that contains source files, their names may be specified by the
12973 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12974 (a string). Source file names never include any directory information.
12976 If the attribute @code{Source_Files} is given an explicit value, then each
12977 element of the list is a source file name.
12979 @smallexample @c projectfile
12980 for Source_Files use ("main.adb");
12981 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12985 If the attribute @code{Source_Files} is not given an explicit value,
12986 but the attribute @code{Source_List_File} is given a string value,
12987 then the source file names are contained in the text file whose path name
12988 (absolute or relative to the directory of the project file) is the
12989 value of the attribute @code{Source_List_File}.
12991 Each line in the file that is not empty or is not a comment
12992 contains a source file name.
12994 @smallexample @c projectfile
12995 for Source_List_File use "source_list.txt";
12999 By default, if neither the attribute @code{Source_Files} nor the attribute
13000 @code{Source_List_File} is given an explicit value, then each file in the
13001 source directories that conforms to the project's naming scheme
13002 (@pxref{Naming Schemes}) is an immediate source of the project.
13004 A warning is issued if both attributes @code{Source_Files} and
13005 @code{Source_List_File} are given explicit values. In this case, the attribute
13006 @code{Source_Files} prevails.
13008 Each source file name must be the name of one existing source file
13009 in one of the source directories.
13011 A @code{Source_Files} attribute whose value is an empty list
13012 indicates that there are no source files in the project.
13014 If the order of the source directories is known statically, that is if
13015 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13016 be several files with the same source file name. In this case, only the file
13017 in the first directory is considered as an immediate source of the project
13018 file. If the order of the source directories is not known statically, it is
13019 an error to have several files with the same source file name.
13021 Projects can be specified to have no Ada source
13022 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
13023 list, or the @code{"Ada"} may be absent from @code{Languages}:
13025 @smallexample @c projectfile
13026 for Source_Dirs use ();
13027 for Source_Files use ();
13028 for Languages use ("C", "C++");
13032 Otherwise, a project must contain at least one immediate source.
13034 Projects with no source files are useful as template packages
13035 (@pxref{Packages in Project Files}) for other projects; in particular to
13036 define a package @code{Naming} (@pxref{Naming Schemes}).
13038 @c ****************************
13039 @c * Importing Projects *
13040 @c ****************************
13042 @node Importing Projects
13043 @section Importing Projects
13044 @cindex @code{ADA_PROJECT_PATH}
13047 An immediate source of a project P may depend on source files that
13048 are neither immediate sources of P nor in the predefined library.
13049 To get this effect, P must @emph{import} the projects that contain the needed
13052 @smallexample @c projectfile
13054 with "project1", "utilities.gpr";
13055 with "/namings/apex.gpr";
13062 As can be seen in this example, the syntax for importing projects is similar
13063 to the syntax for importing compilation units in Ada. However, project files
13064 use literal strings instead of names, and the @code{with} clause identifies
13065 project files rather than packages.
13067 Each literal string is the file name or path name (absolute or relative) of a
13068 project file. If a string corresponds to a file name, with no path or a
13069 relative path, then its location is determined by the @emph{project path}. The
13070 latter can be queried using @code{gnatls -v}. It contains:
13074 In first position, the directory containing the current project file.
13076 In last position, the default project directory. This default project directory
13077 is part of the GNAT installation and is the standard place to install project
13078 files giving access to standard support libraries.
13080 @ref{Installing a library}
13084 In between, all the directories referenced in the
13085 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13089 If a relative pathname is used, as in
13091 @smallexample @c projectfile
13096 then the full path for the project is constructed by concatenating this
13097 relative path to those in the project path, in order, until a matching file is
13098 found. Any symbolic link will be fully resolved in the directory of the
13099 importing project file before the imported project file is examined.
13101 If the @code{with}'ed project file name does not have an extension,
13102 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13103 then the file name as specified in the @code{with} clause (no extension) will
13104 be used. In the above example, if a file @code{project1.gpr} is found, then it
13105 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13106 then it will be used; if neither file exists, this is an error.
13108 A warning is issued if the name of the project file does not match the
13109 name of the project; this check is case insensitive.
13111 Any source file that is an immediate source of the imported project can be
13112 used by the immediate sources of the importing project, transitively. Thus
13113 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13114 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13115 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13116 because if and when @code{B} ceases to import @code{C}, some sources in
13117 @code{A} will no longer compile.
13119 A side effect of this capability is that normally cyclic dependencies are not
13120 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13121 is not allowed to import @code{A}. However, there are cases when cyclic
13122 dependencies would be beneficial. For these cases, another form of import
13123 between projects exists, the @code{limited with}: a project @code{A} that
13124 imports a project @code{B} with a straight @code{with} may also be imported,
13125 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13126 to @code{A} include at least one @code{limited with}.
13128 @smallexample @c 0projectfile
13134 limited with "../a/a.gpr";
13142 limited with "../a/a.gpr";
13148 In the above legal example, there are two project cycles:
13151 @item A -> C -> D -> A
13155 In each of these cycle there is one @code{limited with}: import of @code{A}
13156 from @code{B} and import of @code{A} from @code{D}.
13158 The difference between straight @code{with} and @code{limited with} is that
13159 the name of a project imported with a @code{limited with} cannot be used in the
13160 project that imports it. In particular, its packages cannot be renamed and
13161 its variables cannot be referred to.
13163 An exception to the above rules for @code{limited with} is that for the main
13164 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13165 @code{limited with} is equivalent to a straight @code{with}. For example,
13166 in the example above, projects @code{B} and @code{D} could not be main
13167 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13168 each have a @code{limited with} that is the only one in a cycle of importing
13171 @c *********************
13172 @c * Project Extension *
13173 @c *********************
13175 @node Project Extension
13176 @section Project Extension
13179 During development of a large system, it is sometimes necessary to use
13180 modified versions of some of the source files, without changing the original
13181 sources. This can be achieved through the @emph{project extension} facility.
13183 @smallexample @c projectfile
13184 project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13188 A project extension declaration introduces an extending project
13189 (the @emph{child}) and a project being extended (the @emph{parent}).
13191 By default, a child project inherits all the sources of its parent.
13192 However, inherited sources can be overridden: a unit in a parent is hidden
13193 by a unit of the same name in the child.
13195 Inherited sources are considered to be sources (but not immediate sources)
13196 of the child project; see @ref{Project File Syntax}.
13198 An inherited source file retains any switches specified in the parent project.
13200 For example if the project @code{Utilities} contains the spec and the
13201 body of an Ada package @code{Util_IO}, then the project
13202 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13203 The original body of @code{Util_IO} will not be considered in program builds.
13204 However, the package spec will still be found in the project
13207 A child project can have only one parent, except when it is qualified as
13208 abstract. But it may import any number of other projects.
13210 A project is not allowed to import directly or indirectly at the same time a
13211 child project and any of its ancestors.
13213 @c *******************************
13214 @c * Project Hierarchy Extension *
13215 @c *******************************
13217 @node Project Hierarchy Extension
13218 @section Project Hierarchy Extension
13221 When extending a large system spanning multiple projects, it is often
13222 inconvenient to extend every project in the hierarchy that is impacted by a
13223 small change introduced. In such cases, it is possible to create a virtual
13224 extension of entire hierarchy using @code{extends all} relationship.
13226 When the project is extended using @code{extends all} inheritance, all projects
13227 that are imported by it, both directly and indirectly, are considered virtually
13228 extended. That is, the Project Manager creates "virtual projects"
13229 that extend every project in the hierarchy; all these virtual projects have
13230 no sources of their own and have as object directory the object directory of
13231 the root of "extending all" project.
13233 It is possible to explicitly extend one or more projects in the hierarchy
13234 in order to modify the sources. These extending projects must be imported by
13235 the "extending all" project, which will replace the corresponding virtual
13236 projects with the explicit ones.
13238 When building such a project hierarchy extension, the Project Manager will
13239 ensure that both modified sources and sources in virtual extending projects
13240 that depend on them, are recompiled.
13242 By means of example, consider the following hierarchy of projects.
13246 project A, containing package P1
13248 project B importing A and containing package P2 which depends on P1
13250 project C importing B and containing package P3 which depends on P2
13254 We want to modify packages P1 and P3.
13256 This project hierarchy will need to be extended as follows:
13260 Create project A1 that extends A, placing modified P1 there:
13262 @smallexample @c 0projectfile
13263 project A1 extends "(@dots{})/A" is
13268 Create project C1 that "extends all" C and imports A1, placing modified
13271 @smallexample @c 0projectfile
13272 with "(@dots{})/A1";
13273 project C1 extends all "(@dots{})/C" is
13278 When you build project C1, your entire modified project space will be
13279 recompiled, including the virtual project B1 that has been impacted by the
13280 "extending all" inheritance of project C.
13282 Note that if a Library Project in the hierarchy is virtually extended,
13283 the virtual project that extends the Library Project is not a Library Project.
13285 @c ****************************************
13286 @c * External References in Project Files *
13287 @c ****************************************
13289 @node External References in Project Files
13290 @section External References in Project Files
13293 A project file may contain references to external variables; such references
13294 are called @emph{external references}.
13296 An external variable is either defined as part of the environment (an
13297 environment variable in Unix, for example) or else specified on the command
13298 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13299 If both, then the command line value is used.
13301 The value of an external reference is obtained by means of the built-in
13302 function @code{external}, which returns a string value.
13303 This function has two forms:
13305 @item @code{external (external_variable_name)}
13306 @item @code{external (external_variable_name, default_value)}
13310 Each parameter must be a string literal. For example:
13312 @smallexample @c projectfile
13314 external ("OS", "GNU/Linux")
13318 In the form with one parameter, the function returns the value of
13319 the external variable given as parameter. If this name is not present in the
13320 environment, the function returns an empty string.
13322 In the form with two string parameters, the second argument is
13323 the value returned when the variable given as the first argument is not
13324 present in the environment. In the example above, if @code{"OS"} is not
13325 the name of ^an environment variable^a logical name^ and is not passed on
13326 the command line, then the returned value is @code{"GNU/Linux"}.
13328 An external reference may be part of a string expression or of a string
13329 list expression, and can therefore appear in a variable declaration or
13330 an attribute declaration.
13332 @smallexample @c projectfile
13334 type Mode_Type is ("Debug", "Release");
13335 Mode : Mode_Type := external ("MODE");
13342 @c *****************************
13343 @c * Packages in Project Files *
13344 @c *****************************
13346 @node Packages in Project Files
13347 @section Packages in Project Files
13350 A @emph{package} defines the settings for project-aware tools within a
13352 For each such tool one can declare a package; the names for these
13353 packages are preset (@pxref{Packages}).
13354 A package may contain variable declarations, attribute declarations, and case
13357 @smallexample @c projectfile
13360 package Builder is -- used by gnatmake
13361 for ^Default_Switches^Default_Switches^ ("Ada")
13370 The syntax of package declarations mimics that of package in Ada.
13372 Most of the packages have an attribute
13373 @code{^Default_Switches^Default_Switches^}.
13374 This attribute is an associative array, and its value is a string list.
13375 The index of the associative array is the name of a programming language (case
13376 insensitive). This attribute indicates the ^switch^switch^
13377 or ^switches^switches^ to be used
13378 with the corresponding tool.
13380 Some packages also have another attribute, @code{^Switches^Switches^},
13381 an associative array whose value is a string list.
13382 The index is the name of a source file.
13383 This attribute indicates the ^switch^switch^
13384 or ^switches^switches^ to be used by the corresponding
13385 tool when dealing with this specific file.
13387 Further information on these ^switch^switch^-related attributes is found in
13388 @ref{^Switches^Switches^ and Project Files}.
13390 A package may be declared as a @emph{renaming} of another package; e.g., from
13391 the project file for an imported project.
13393 @smallexample @c projectfile
13395 with "/global/apex.gpr";
13397 package Naming renames Apex.Naming;
13404 Packages that are renamed in other project files often come from project files
13405 that have no sources: they are just used as templates. Any modification in the
13406 template will be reflected automatically in all the project files that rename
13407 a package from the template.
13409 In addition to the tool-oriented packages, you can also declare a package
13410 named @code{Naming} to establish specialized source file naming conventions
13411 (@pxref{Naming Schemes}).
13413 @c ************************************
13414 @c * Variables from Imported Projects *
13415 @c ************************************
13417 @node Variables from Imported Projects
13418 @section Variables from Imported Projects
13421 An attribute or variable defined in an imported or parent project can
13422 be used in expressions in the importing / extending project.
13423 Such an attribute or variable is denoted by an expanded name whose prefix
13424 is either the name of the project or the expanded name of a package within
13427 @smallexample @c projectfile
13430 project Main extends "base" is
13431 Var1 := Imported.Var;
13432 Var2 := Base.Var & ".new";
13437 for ^Default_Switches^Default_Switches^ ("Ada")
13438 use Imported.Builder'Ada_^Switches^Switches^ &
13439 "^-gnatg^-gnatg^" &
13445 package Compiler is
13446 for ^Default_Switches^Default_Switches^ ("Ada")
13447 use Base.Compiler'Ada_^Switches^Switches^;
13458 The value of @code{Var1} is a copy of the variable @code{Var} defined
13459 in the project file @file{"imported.gpr"}
13461 the value of @code{Var2} is a copy of the value of variable @code{Var}
13462 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13464 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13465 @code{Builder} is a string list that includes in its value a copy of the value
13466 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13467 in project file @file{imported.gpr} plus two new elements:
13468 @option{"^-gnatg^-gnatg^"}
13469 and @option{"^-v^-v^"};
13471 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13472 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13473 defined in the @code{Compiler} package in project file @file{base.gpr},
13474 the project being extended.
13477 @c ******************
13478 @c * Naming Schemes *
13479 @c ******************
13481 @node Naming Schemes
13482 @section Naming Schemes
13485 Sometimes an Ada software system is ported from a foreign compilation
13486 environment to GNAT, and the file names do not use the default GNAT
13487 conventions. Instead of changing all the file names (which for a variety
13488 of reasons might not be possible), you can define the relevant file
13489 naming scheme in the @code{Naming} package in your project file.
13492 Note that the use of pragmas described in
13493 @ref{Alternative File Naming Schemes} by mean of a configuration
13494 pragmas file is not supported when using project files. You must use
13495 the features described in this paragraph. You can however use specify
13496 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13499 For example, the following
13500 package models the Apex file naming rules:
13502 @smallexample @c projectfile
13505 for Casing use "lowercase";
13506 for Dot_Replacement use ".";
13507 for Spec_Suffix ("Ada") use ".1.ada";
13508 for Body_Suffix ("Ada") use ".2.ada";
13515 For example, the following package models the HP Ada file naming rules:
13517 @smallexample @c projectfile
13520 for Casing use "lowercase";
13521 for Dot_Replacement use "__";
13522 for Spec_Suffix ("Ada") use "_.^ada^ada^";
13523 for Body_Suffix ("Ada") use ".^ada^ada^";
13529 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13530 names in lower case)
13534 You can define the following attributes in package @code{Naming}:
13538 @item @code{Casing}
13539 This must be a string with one of the three values @code{"lowercase"},
13540 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13543 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13545 @item @code{Dot_Replacement}
13546 This must be a string whose value satisfies the following conditions:
13549 @item It must not be empty
13550 @item It cannot start or end with an alphanumeric character
13551 @item It cannot be a single underscore
13552 @item It cannot start with an underscore followed by an alphanumeric
13553 @item It cannot contain a dot @code{'.'} except if the entire string
13558 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13560 @item @code{Spec_Suffix}
13561 This is an associative array (indexed by the programming language name, case
13562 insensitive) whose value is a string that must satisfy the following
13566 @item It must not be empty
13567 @item It must include at least one dot
13570 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13571 @code{"^.ads^.ADS^"}.
13573 @item @code{Body_Suffix}
13574 This is an associative array (indexed by the programming language name, case
13575 insensitive) whose value is a string that must satisfy the following
13579 @item It must not be empty
13580 @item It must include at least one dot
13581 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13584 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13585 same string, then a file name that ends with the longest of these two suffixes
13586 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13587 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13589 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13590 @code{"^.adb^.ADB^"}.
13592 @item @code{Separate_Suffix}
13593 This must be a string whose value satisfies the same conditions as
13594 @code{Body_Suffix}. The same "longest suffix" rules apply.
13597 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13598 value as @code{Body_Suffix ("Ada")}.
13602 You can use the associative array attribute @code{Spec} to define
13603 the source file name for an individual Ada compilation unit's spec. The array
13604 index must be a string literal that identifies the Ada unit (case insensitive).
13605 The value of this attribute must be a string that identifies the file that
13606 contains this unit's spec (case sensitive or insensitive depending on the
13609 @smallexample @c projectfile
13610 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13615 You can use the associative array attribute @code{Body} to
13616 define the source file name for an individual Ada compilation unit's body
13617 (possibly a subunit). The array index must be a string literal that identifies
13618 the Ada unit (case insensitive). The value of this attribute must be a string
13619 that identifies the file that contains this unit's body or subunit (case
13620 sensitive or insensitive depending on the operating system).
13622 @smallexample @c projectfile
13623 for Body ("MyPack.MyChild") use "mypack.mychild.body";
13627 @c ********************
13628 @c * Library Projects *
13629 @c ********************
13631 @node Library Projects
13632 @section Library Projects
13635 @emph{Library projects} are projects whose object code is placed in a library.
13636 (Note that this facility is not yet supported on all platforms)
13638 To create a library project, you need to define in its project file
13639 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13640 Additionally, you may define other library-related attributes such as
13641 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13642 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13644 The @code{Library_Name} attribute has a string value. There is no restriction
13645 on the name of a library. It is the responsibility of the developer to
13646 choose a name that will be accepted by the platform. It is recommended to
13647 choose names that could be Ada identifiers; such names are almost guaranteed
13648 to be acceptable on all platforms.
13650 The @code{Library_Dir} attribute has a string value that designates the path
13651 (absolute or relative) of the directory where the library will reside.
13652 It must designate an existing directory, and this directory must be writable,
13653 different from the project's object directory and from any source directory
13654 in the project tree.
13656 If both @code{Library_Name} and @code{Library_Dir} are specified and
13657 are legal, then the project file defines a library project. The optional
13658 library-related attributes are checked only for such project files.
13660 The @code{Library_Kind} attribute has a string value that must be one of the
13661 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13662 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13663 attribute is not specified, the library is a static library, that is
13664 an archive of object files that can be potentially linked into a
13665 static executable. Otherwise, the library may be dynamic or
13666 relocatable, that is a library that is loaded only at the start of execution.
13668 If you need to build both a static and a dynamic library, you should use two
13669 different object directories, since in some cases some extra code needs to
13670 be generated for the latter. For such cases, it is recommended to either use
13671 two different project files, or a single one which uses external variables
13672 to indicate what kind of library should be build.
13674 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13675 directory where the ALI files of the library will be copied. When it is
13676 not specified, the ALI files are copied to the directory specified in
13677 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13678 must be writable and different from the project's object directory and from
13679 any source directory in the project tree.
13681 The @code{Library_Version} attribute has a string value whose interpretation
13682 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13683 used only for dynamic/relocatable libraries as the internal name of the
13684 library (the @code{"soname"}). If the library file name (built from the
13685 @code{Library_Name}) is different from the @code{Library_Version}, then the
13686 library file will be a symbolic link to the actual file whose name will be
13687 @code{Library_Version}.
13691 @smallexample @c projectfile
13697 for Library_Dir use "lib_dir";
13698 for Library_Name use "dummy";
13699 for Library_Kind use "relocatable";
13700 for Library_Version use "libdummy.so." & Version;
13707 Directory @file{lib_dir} will contain the internal library file whose name
13708 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13709 @file{libdummy.so.1}.
13711 When @command{gnatmake} detects that a project file
13712 is a library project file, it will check all immediate sources of the project
13713 and rebuild the library if any of the sources have been recompiled.
13715 Standard project files can import library project files. In such cases,
13716 the libraries will only be rebuilt if some of its sources are recompiled
13717 because they are in the closure of some other source in an importing project.
13718 Sources of the library project files that are not in such a closure will
13719 not be checked, unless the full library is checked, because one of its sources
13720 needs to be recompiled.
13722 For instance, assume the project file @code{A} imports the library project file
13723 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13724 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13725 @file{l2.ads}, @file{l2.adb}.
13727 If @file{l1.adb} has been modified, then the library associated with @code{L}
13728 will be rebuilt when compiling all the immediate sources of @code{A} only
13729 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13732 To be sure that all the sources in the library associated with @code{L} are
13733 up to date, and that all the sources of project @code{A} are also up to date,
13734 the following two commands needs to be used:
13741 When a library is built or rebuilt, an attempt is made first to delete all
13742 files in the library directory.
13743 All @file{ALI} files will also be copied from the object directory to the
13744 library directory. To build executables, @command{gnatmake} will use the
13745 library rather than the individual object files.
13748 It is also possible to create library project files for third-party libraries
13749 that are precompiled and cannot be compiled locally thanks to the
13750 @code{externally_built} attribute. (See @ref{Installing a library}).
13753 @c *******************************
13754 @c * Stand-alone Library Projects *
13755 @c *******************************
13757 @node Stand-alone Library Projects
13758 @section Stand-alone Library Projects
13761 A Stand-alone Library is a library that contains the necessary code to
13762 elaborate the Ada units that are included in the library. A Stand-alone
13763 Library is suitable to be used in an executable when the main is not
13764 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13767 A Stand-alone Library Project is a Library Project where the library is
13768 a Stand-alone Library.
13770 To be a Stand-alone Library Project, in addition to the two attributes
13771 that make a project a Library Project (@code{Library_Name} and
13772 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13773 @code{Library_Interface} must be defined.
13775 @smallexample @c projectfile
13777 for Library_Dir use "lib_dir";
13778 for Library_Name use "dummy";
13779 for Library_Interface use ("int1", "int1.child");
13783 Attribute @code{Library_Interface} has a nonempty string list value,
13784 each string in the list designating a unit contained in an immediate source
13785 of the project file.
13787 When a Stand-alone Library is built, first the binder is invoked to build
13788 a package whose name depends on the library name
13789 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13790 This binder-generated package includes initialization and
13791 finalization procedures whose
13792 names depend on the library name (dummyinit and dummyfinal in the example
13793 above). The object corresponding to this package is included in the library.
13795 A dynamic or relocatable Stand-alone Library is automatically initialized
13796 if automatic initialization of Stand-alone Libraries is supported on the
13797 platform and if attribute @code{Library_Auto_Init} is not specified or
13798 is specified with the value "true". A static Stand-alone Library is never
13799 automatically initialized.
13801 Single string attribute @code{Library_Auto_Init} may be specified with only
13802 two possible values: "false" or "true" (case-insensitive). Specifying
13803 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13804 initialization of dynamic or relocatable libraries.
13806 When a non-automatically initialized Stand-alone Library is used
13807 in an executable, its initialization procedure must be called before
13808 any service of the library is used.
13809 When the main subprogram is in Ada, it may mean that the initialization
13810 procedure has to be called during elaboration of another package.
13812 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13813 (those that are listed in attribute @code{Library_Interface}) are copied to
13814 the Library Directory. As a consequence, only the Interface Units may be
13815 imported from Ada units outside of the library. If other units are imported,
13816 the binding phase will fail.
13818 When a Stand-Alone Library is bound, the switches that are specified in
13819 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13820 used in the call to @command{gnatbind}.
13822 The string list attribute @code{Library_Options} may be used to specified
13823 additional switches to the call to @command{gcc} to link the library.
13825 The attribute @code{Library_Src_Dir}, may be specified for a
13826 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13827 single string value. Its value must be the path (absolute or relative to the
13828 project directory) of an existing directory. This directory cannot be the
13829 object directory or one of the source directories, but it can be the same as
13830 the library directory. The sources of the Interface
13831 Units of the library, necessary to an Ada client of the library, will be
13832 copied to the designated directory, called Interface Copy directory.
13833 These sources includes the specs of the Interface Units, but they may also
13834 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13835 are used, or when there is a generic units in the spec. Before the sources
13836 are copied to the Interface Copy directory, an attempt is made to delete all
13837 files in the Interface Copy directory.
13839 @c *************************************
13840 @c * Switches Related to Project Files *
13841 @c *************************************
13842 @node Switches Related to Project Files
13843 @section Switches Related to Project Files
13846 The following switches are used by GNAT tools that support project files:
13850 @item ^-P^/PROJECT_FILE=^@var{project}
13851 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
13852 Indicates the name of a project file. This project file will be parsed with
13853 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13854 if any, and using the external references indicated
13855 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13857 There may zero, one or more spaces between @option{-P} and @var{project}.
13861 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13864 Since the Project Manager parses the project file only after all the switches
13865 on the command line are checked, the order of the switches
13866 @option{^-P^/PROJECT_FILE^},
13867 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13868 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13870 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13871 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
13872 Indicates that external variable @var{name} has the value @var{value}.
13873 The Project Manager will use this value for occurrences of
13874 @code{external(name)} when parsing the project file.
13878 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13879 put between quotes.
13887 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13888 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13889 @var{name}, only the last one is used.
13892 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13893 takes precedence over the value of the same name in the environment.
13895 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13896 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
13897 Indicates the verbosity of the parsing of GNAT project files.
13900 @option{-vP0} means Default;
13901 @option{-vP1} means Medium;
13902 @option{-vP2} means High.
13906 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13911 The default is ^Default^DEFAULT^: no output for syntactically correct
13914 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13915 only the last one is used.
13917 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
13918 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
13919 Add directory <dir> at the beginning of the project search path, in order,
13920 after the current working directory.
13924 @cindex @option{-eL} (any project-aware tool)
13925 Follow all symbolic links when processing project files.
13928 @item ^--subdirs^/SUBDIRS^=<subdir>
13929 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
13930 This switch is recognized by gnatmake and gnatclean. It indicate that the real
13931 directories (except the source directories) are the subdirectories <subdir>
13932 of the directories specified in the project files. This applies in particular
13933 to object directories, library directories and exec directories. If the
13934 subdirectories do not exist, they are created automatically.
13938 @c **********************************
13939 @c * Tools Supporting Project Files *
13940 @c **********************************
13942 @node Tools Supporting Project Files
13943 @section Tools Supporting Project Files
13946 * gnatmake and Project Files::
13947 * The GNAT Driver and Project Files::
13950 @node gnatmake and Project Files
13951 @subsection gnatmake and Project Files
13954 This section covers several topics related to @command{gnatmake} and
13955 project files: defining ^switches^switches^ for @command{gnatmake}
13956 and for the tools that it invokes; specifying configuration pragmas;
13957 the use of the @code{Main} attribute; building and rebuilding library project
13961 * ^Switches^Switches^ and Project Files::
13962 * Specifying Configuration Pragmas::
13963 * Project Files and Main Subprograms::
13964 * Library Project Files::
13967 @node ^Switches^Switches^ and Project Files
13968 @subsubsection ^Switches^Switches^ and Project Files
13971 It is not currently possible to specify VMS style qualifiers in the project
13972 files; only Unix style ^switches^switches^ may be specified.
13976 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13977 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13978 attribute, a @code{^Switches^Switches^} attribute, or both;
13979 as their names imply, these ^switch^switch^-related
13980 attributes affect the ^switches^switches^ that are used for each of these GNAT
13982 @command{gnatmake} is invoked. As will be explained below, these
13983 component-specific ^switches^switches^ precede
13984 the ^switches^switches^ provided on the @command{gnatmake} command line.
13986 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13987 array indexed by language name (case insensitive) whose value is a string list.
13990 @smallexample @c projectfile
13992 package Compiler is
13993 for ^Default_Switches^Default_Switches^ ("Ada")
13994 use ("^-gnaty^-gnaty^",
14001 The @code{^Switches^Switches^} attribute is also an associative array,
14002 indexed by a file name (which may or may not be case sensitive, depending
14003 on the operating system) whose value is a string list. For example:
14005 @smallexample @c projectfile
14008 for ^Switches^Switches^ ("main1.adb")
14010 for ^Switches^Switches^ ("main2.adb")
14017 For the @code{Builder} package, the file names must designate source files
14018 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
14019 file names must designate @file{ALI} or source files for main subprograms.
14020 In each case just the file name without an explicit extension is acceptable.
14022 For each tool used in a program build (@command{gnatmake}, the compiler, the
14023 binder, and the linker), the corresponding package @dfn{contributes} a set of
14024 ^switches^switches^ for each file on which the tool is invoked, based on the
14025 ^switch^switch^-related attributes defined in the package.
14026 In particular, the ^switches^switches^
14027 that each of these packages contributes for a given file @var{f} comprise:
14031 the value of attribute @code{^Switches^Switches^ (@var{f})},
14032 if it is specified in the package for the given file,
14034 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14035 if it is specified in the package.
14039 If neither of these attributes is defined in the package, then the package does
14040 not contribute any ^switches^switches^ for the given file.
14042 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14043 two sets, in the following order: those contributed for the file
14044 by the @code{Builder} package;
14045 and the switches passed on the command line.
14047 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14048 the ^switches^switches^ passed to the tool comprise three sets,
14049 in the following order:
14053 the applicable ^switches^switches^ contributed for the file
14054 by the @code{Builder} package in the project file supplied on the command line;
14057 those contributed for the file by the package (in the relevant project file --
14058 see below) corresponding to the tool; and
14061 the applicable switches passed on the command line.
14065 The term @emph{applicable ^switches^switches^} reflects the fact that
14066 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14067 tools, depending on the individual ^switch^switch^.
14069 @command{gnatmake} may invoke the compiler on source files from different
14070 projects. The Project Manager will use the appropriate project file to
14071 determine the @code{Compiler} package for each source file being compiled.
14072 Likewise for the @code{Binder} and @code{Linker} packages.
14074 As an example, consider the following package in a project file:
14076 @smallexample @c projectfile
14079 package Compiler is
14080 for ^Default_Switches^Default_Switches^ ("Ada")
14082 for ^Switches^Switches^ ("a.adb")
14084 for ^Switches^Switches^ ("b.adb")
14086 "^-gnaty^-gnaty^");
14093 If @command{gnatmake} is invoked with this project file, and it needs to
14094 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14095 @file{a.adb} will be compiled with the ^switch^switch^
14096 @option{^-O1^-O1^},
14097 @file{b.adb} with ^switches^switches^
14099 and @option{^-gnaty^-gnaty^},
14100 and @file{c.adb} with @option{^-g^-g^}.
14102 The following example illustrates the ordering of the ^switches^switches^
14103 contributed by different packages:
14105 @smallexample @c projectfile
14109 for ^Switches^Switches^ ("main.adb")
14117 package Compiler is
14118 for ^Switches^Switches^ ("main.adb")
14126 If you issue the command:
14129 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14133 then the compiler will be invoked on @file{main.adb} with the following
14134 sequence of ^switches^switches^
14137 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14140 with the last @option{^-O^-O^}
14141 ^switch^switch^ having precedence over the earlier ones;
14142 several other ^switches^switches^
14143 (such as @option{^-c^-c^}) are added implicitly.
14145 The ^switches^switches^
14147 and @option{^-O1^-O1^} are contributed by package
14148 @code{Builder}, @option{^-O2^-O2^} is contributed
14149 by the package @code{Compiler}
14150 and @option{^-O0^-O0^} comes from the command line.
14152 The @option{^-g^-g^}
14153 ^switch^switch^ will also be passed in the invocation of
14154 @command{Gnatlink.}
14156 A final example illustrates switch contributions from packages in different
14159 @smallexample @c projectfile
14162 for Source_Files use ("pack.ads", "pack.adb");
14163 package Compiler is
14164 for ^Default_Switches^Default_Switches^ ("Ada")
14165 use ("^-gnata^-gnata^");
14173 for Source_Files use ("foo_main.adb", "bar_main.adb");
14175 for ^Switches^Switches^ ("foo_main.adb")
14183 -- Ada source file:
14185 procedure Foo_Main is
14193 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14197 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14198 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14199 @option{^-gnato^-gnato^} (passed on the command line).
14200 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14201 are @option{^-g^-g^} from @code{Proj4.Builder},
14202 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14203 and @option{^-gnato^-gnato^} from the command line.
14206 When using @command{gnatmake} with project files, some ^switches^switches^ or
14207 arguments may be expressed as relative paths. As the working directory where
14208 compilation occurs may change, these relative paths are converted to absolute
14209 paths. For the ^switches^switches^ found in a project file, the relative paths
14210 are relative to the project file directory, for the switches on the command
14211 line, they are relative to the directory where @command{gnatmake} is invoked.
14212 The ^switches^switches^ for which this occurs are:
14218 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14220 ^-o^-o^, object files specified in package @code{Linker} or after
14221 -largs on the command line). The exception to this rule is the ^switch^switch^
14222 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14224 @node Specifying Configuration Pragmas
14225 @subsubsection Specifying Configuration Pragmas
14227 When using @command{gnatmake} with project files, if there exists a file
14228 @file{gnat.adc} that contains configuration pragmas, this file will be
14231 Configuration pragmas can be defined by means of the following attributes in
14232 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14233 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14235 Both these attributes are single string attributes. Their values is the path
14236 name of a file containing configuration pragmas. If a path name is relative,
14237 then it is relative to the project directory of the project file where the
14238 attribute is defined.
14240 When compiling a source, the configuration pragmas used are, in order,
14241 those listed in the file designated by attribute
14242 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14243 project file, if it is specified, and those listed in the file designated by
14244 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14245 the project file of the source, if it exists.
14247 @node Project Files and Main Subprograms
14248 @subsubsection Project Files and Main Subprograms
14251 When using a project file, you can invoke @command{gnatmake}
14252 with one or several main subprograms, by specifying their source files on the
14256 gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14260 Each of these needs to be a source file of the same project, except
14261 when the switch ^-u^/UNIQUE^ is used.
14264 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14265 same project, one of the project in the tree rooted at the project specified
14266 on the command line. The package @code{Builder} of this common project, the
14267 "main project" is the one that is considered by @command{gnatmake}.
14270 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14271 imported directly or indirectly by the project specified on the command line.
14272 Note that if such a source file is not part of the project specified on the
14273 command line, the ^switches^switches^ found in package @code{Builder} of the
14274 project specified on the command line, if any, that are transmitted
14275 to the compiler will still be used, not those found in the project file of
14279 When using a project file, you can also invoke @command{gnatmake} without
14280 explicitly specifying any main, and the effect depends on whether you have
14281 defined the @code{Main} attribute. This attribute has a string list value,
14282 where each element in the list is the name of a source file (the file
14283 extension is optional) that contains a unit that can be a main subprogram.
14285 If the @code{Main} attribute is defined in a project file as a non-empty
14286 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14287 line, then invoking @command{gnatmake} with this project file but without any
14288 main on the command line is equivalent to invoking @command{gnatmake} with all
14289 the file names in the @code{Main} attribute on the command line.
14292 @smallexample @c projectfile
14295 for Main use ("main1", "main2", "main3");
14301 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14303 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14305 When the project attribute @code{Main} is not specified, or is specified
14306 as an empty string list, or when the switch @option{-u} is used on the command
14307 line, then invoking @command{gnatmake} with no main on the command line will
14308 result in all immediate sources of the project file being checked, and
14309 potentially recompiled. Depending on the presence of the switch @option{-u},
14310 sources from other project files on which the immediate sources of the main
14311 project file depend are also checked and potentially recompiled. In other
14312 words, the @option{-u} switch is applied to all of the immediate sources of the
14315 When no main is specified on the command line and attribute @code{Main} exists
14316 and includes several mains, or when several mains are specified on the
14317 command line, the default ^switches^switches^ in package @code{Builder} will
14318 be used for all mains, even if there are specific ^switches^switches^
14319 specified for one or several mains.
14321 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14322 the specific ^switches^switches^ for each main, if they are specified.
14324 @node Library Project Files
14325 @subsubsection Library Project Files
14328 When @command{gnatmake} is invoked with a main project file that is a library
14329 project file, it is not allowed to specify one or more mains on the command
14333 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14334 ^-l^/ACTION=LINK^ have special meanings.
14337 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14338 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14341 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14342 to @command{gnatmake} that the binder generated file should be compiled
14343 (in the case of a stand-alone library) and that the library should be built.
14347 @node The GNAT Driver and Project Files
14348 @subsection The GNAT Driver and Project Files
14351 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14352 can benefit from project files:
14353 @command{^gnatbind^gnatbind^},
14354 @command{^gnatcheck^gnatcheck^}),
14355 @command{^gnatclean^gnatclean^}),
14356 @command{^gnatelim^gnatelim^},
14357 @command{^gnatfind^gnatfind^},
14358 @command{^gnatlink^gnatlink^},
14359 @command{^gnatls^gnatls^},
14360 @command{^gnatmetric^gnatmetric^},
14361 @command{^gnatpp^gnatpp^},
14362 @command{^gnatstub^gnatstub^},
14363 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14364 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14365 They must be invoked through the @command{gnat} driver.
14367 The @command{gnat} driver is a wrapper that accepts a number of commands and
14368 calls the corresponding tool. It was designed initially for VMS platforms (to
14369 convert VMS qualifiers to Unix-style switches), but it is now available on all
14372 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14373 (case insensitive):
14377 BIND to invoke @command{^gnatbind^gnatbind^}
14379 CHOP to invoke @command{^gnatchop^gnatchop^}
14381 CLEAN to invoke @command{^gnatclean^gnatclean^}
14383 COMP or COMPILE to invoke the compiler
14385 ELIM to invoke @command{^gnatelim^gnatelim^}
14387 FIND to invoke @command{^gnatfind^gnatfind^}
14389 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14391 LINK to invoke @command{^gnatlink^gnatlink^}
14393 LS or LIST to invoke @command{^gnatls^gnatls^}
14395 MAKE to invoke @command{^gnatmake^gnatmake^}
14397 NAME to invoke @command{^gnatname^gnatname^}
14399 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14401 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14403 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14405 STUB to invoke @command{^gnatstub^gnatstub^}
14407 XREF to invoke @command{^gnatxref^gnatxref^}
14411 (note that the compiler is invoked using the command
14412 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14415 On non-VMS platforms, between @command{gnat} and the command, two
14416 special switches may be used:
14420 @command{-v} to display the invocation of the tool.
14422 @command{-dn} to prevent the @command{gnat} driver from removing
14423 the temporary files it has created. These temporary files are
14424 configuration files and temporary file list files.
14428 The command may be followed by switches and arguments for the invoked
14432 gnat bind -C main.ali
14438 Switches may also be put in text files, one switch per line, and the text
14439 files may be specified with their path name preceded by '@@'.
14442 gnat bind @@args.txt main.ali
14446 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14447 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14448 (@option{^-P^/PROJECT_FILE^},
14449 @option{^-X^/EXTERNAL_REFERENCE^} and
14450 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14451 the switches of the invoking tool.
14454 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14455 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14456 the immediate sources of the specified project file.
14459 When GNAT METRIC is used with a project file, but with no source
14460 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14461 with all the immediate sources of the specified project file and with
14462 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14466 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14467 a project file, no source is specified on the command line and
14468 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14469 the underlying tool (^gnatpp^gnatpp^ or
14470 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14471 not only for the immediate sources of the main project.
14473 (-U stands for Universal or Union of the project files of the project tree)
14477 For each of the following commands, there is optionally a corresponding
14478 package in the main project.
14482 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14485 package @code{Check} for command CHECK (invoking
14486 @code{^gnatcheck^gnatcheck^})
14489 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14492 package @code{Cross_Reference} for command XREF (invoking
14493 @code{^gnatxref^gnatxref^})
14496 package @code{Eliminate} for command ELIM (invoking
14497 @code{^gnatelim^gnatelim^})
14500 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14503 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14506 package @code{Gnatstub} for command STUB
14507 (invoking @code{^gnatstub^gnatstub^})
14510 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14513 package @code{Metrics} for command METRIC
14514 (invoking @code{^gnatmetric^gnatmetric^})
14517 package @code{Pretty_Printer} for command PP or PRETTY
14518 (invoking @code{^gnatpp^gnatpp^})
14523 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14524 a simple variable with a string list value. It contains ^switches^switches^
14525 for the invocation of @code{^gnatls^gnatls^}.
14527 @smallexample @c projectfile
14531 for ^Switches^Switches^
14540 All other packages have two attribute @code{^Switches^Switches^} and
14541 @code{^Default_Switches^Default_Switches^}.
14544 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14545 source file name, that has a string list value: the ^switches^switches^ to be
14546 used when the tool corresponding to the package is invoked for the specific
14550 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14551 indexed by the programming language that has a string list value.
14552 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14553 ^switches^switches^ for the invocation of the tool corresponding
14554 to the package, except if a specific @code{^Switches^Switches^} attribute
14555 is specified for the source file.
14557 @smallexample @c projectfile
14561 for Source_Dirs use ("./**");
14564 for ^Switches^Switches^ use
14571 package Compiler is
14572 for ^Default_Switches^Default_Switches^ ("Ada")
14573 use ("^-gnatv^-gnatv^",
14574 "^-gnatwa^-gnatwa^");
14580 for ^Default_Switches^Default_Switches^ ("Ada")
14588 for ^Default_Switches^Default_Switches^ ("Ada")
14590 for ^Switches^Switches^ ("main.adb")
14599 for ^Default_Switches^Default_Switches^ ("Ada")
14606 package Cross_Reference is
14607 for ^Default_Switches^Default_Switches^ ("Ada")
14612 end Cross_Reference;
14618 With the above project file, commands such as
14621 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14622 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14623 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14624 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14625 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14629 will set up the environment properly and invoke the tool with the switches
14630 found in the package corresponding to the tool:
14631 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14632 except @code{^Switches^Switches^ ("main.adb")}
14633 for @code{^gnatlink^gnatlink^}.
14634 It is also possible to invoke some of the tools,
14635 @code{^gnatcheck^gnatcheck^}),
14636 @code{^gnatmetric^gnatmetric^}),
14637 and @code{^gnatpp^gnatpp^})
14638 on a set of project units thanks to the combination of the switches
14639 @option{-P}, @option{-U} and possibly the main unit when one is interested
14640 in its closure. For instance,
14644 will compute the metrics for all the immediate units of project
14647 gnat metric -Pproj -U
14649 will compute the metrics for all the units of the closure of projects
14650 rooted at @code{proj}.
14652 gnat metric -Pproj -U main_unit
14654 will compute the metrics for the closure of units rooted at
14655 @code{main_unit}. This last possibility relies implicitly
14656 on @command{gnatbind}'s option @option{-R}.
14658 @c **********************
14659 @node An Extended Example
14660 @section An Extended Example
14663 Suppose that we have two programs, @var{prog1} and @var{prog2},
14664 whose sources are in corresponding directories. We would like
14665 to build them with a single @command{gnatmake} command, and we want to place
14666 their object files into @file{build} subdirectories of the source directories.
14667 Furthermore, we want to have to have two separate subdirectories
14668 in @file{build} -- @file{release} and @file{debug} -- which will contain
14669 the object files compiled with different set of compilation flags.
14671 In other words, we have the following structure:
14688 Here are the project files that we must place in a directory @file{main}
14689 to maintain this structure:
14693 @item We create a @code{Common} project with a package @code{Compiler} that
14694 specifies the compilation ^switches^switches^:
14699 @b{project} Common @b{is}
14701 @b{for} Source_Dirs @b{use} (); -- No source files
14705 @b{type} Build_Type @b{is} ("release", "debug");
14706 Build : Build_Type := External ("BUILD", "debug");
14709 @b{package} Compiler @b{is}
14710 @b{case} Build @b{is}
14711 @b{when} "release" =>
14712 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14713 @b{use} ("^-O2^-O2^");
14714 @b{when} "debug" =>
14715 @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14716 @b{use} ("^-g^-g^");
14724 @item We create separate projects for the two programs:
14731 @b{project} Prog1 @b{is}
14733 @b{for} Source_Dirs @b{use} ("prog1");
14734 @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build;
14736 @b{package} Compiler @b{renames} Common.Compiler;
14747 @b{project} Prog2 @b{is}
14749 @b{for} Source_Dirs @b{use} ("prog2");
14750 @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build;
14752 @b{package} Compiler @b{renames} Common.Compiler;
14758 @item We create a wrapping project @code{Main}:
14767 @b{project} Main @b{is}
14769 @b{package} Compiler @b{renames} Common.Compiler;
14775 @item Finally we need to create a dummy procedure that @code{with}s (either
14776 explicitly or implicitly) all the sources of our two programs.
14781 Now we can build the programs using the command
14784 gnatmake ^-P^/PROJECT_FILE=^main dummy
14788 for the Debug mode, or
14792 gnatmake -Pmain -XBUILD=release
14798 GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14803 for the Release mode.
14805 @c ********************************
14806 @c * Project File Complete Syntax *
14807 @c ********************************
14809 @node Project File Complete Syntax
14810 @section Project File Complete Syntax
14814 context_clause project_declaration
14820 @b{with} path_name @{ , path_name @} ;
14825 project_declaration ::=
14826 simple_project_declaration | project_extension
14828 simple_project_declaration ::=
14829 @b{project} <project_>simple_name @b{is}
14830 @{declarative_item@}
14831 @b{end} <project_>simple_name;
14833 project_extension ::=
14834 @b{project} <project_>simple_name @b{extends} path_name @b{is}
14835 @{declarative_item@}
14836 @b{end} <project_>simple_name;
14838 declarative_item ::=
14839 package_declaration |
14840 typed_string_declaration |
14841 other_declarative_item
14843 package_declaration ::=
14844 package_spec | package_renaming
14847 @b{package} package_identifier @b{is}
14848 @{simple_declarative_item@}
14849 @b{end} package_identifier ;
14851 package_identifier ::=
14852 @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14853 @code{Linker} | @code{Finder} | @code{Cross_Reference} |
14854 @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer}
14856 package_renaming ::==
14857 @b{package} package_identifier @b{renames}
14858 <project_>simple_name.package_identifier ;
14860 typed_string_declaration ::=
14861 @b{type} <typed_string_>_simple_name @b{is}
14862 ( string_literal @{, string_literal@} );
14864 other_declarative_item ::=
14865 attribute_declaration |
14866 typed_variable_declaration |
14867 variable_declaration |
14870 attribute_declaration ::=
14871 full_associative_array_declaration |
14872 @b{for} attribute_designator @b{use} expression ;
14874 full_associative_array_declaration ::=
14875 @b{for} <associative_array_attribute_>simple_name @b{use}
14876 <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14878 attribute_designator ::=
14879 <simple_attribute_>simple_name |
14880 <associative_array_attribute_>simple_name ( string_literal )
14882 typed_variable_declaration ::=
14883 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
14885 variable_declaration ::=
14886 <variable_>simple_name := expression;
14896 attribute_reference
14902 ( <string_>expression @{ , <string_>expression @} )
14905 @b{external} ( string_literal [, string_literal] )
14907 attribute_reference ::=
14908 attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14910 attribute_prefix ::=
14912 <project_>simple_name | package_identifier |
14913 <project_>simple_name . package_identifier
14915 case_construction ::=
14916 @b{case} <typed_variable_>name @b{is}
14921 @b{when} discrete_choice_list =>
14922 @{case_construction | attribute_declaration@}
14924 discrete_choice_list ::=
14925 string_literal @{| string_literal@} |
14929 simple_name @{. simple_name@}
14932 identifier (same as Ada)
14936 @node The Cross-Referencing Tools gnatxref and gnatfind
14937 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14942 The compiler generates cross-referencing information (unless
14943 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14944 This information indicates where in the source each entity is declared and
14945 referenced. Note that entities in package Standard are not included, but
14946 entities in all other predefined units are included in the output.
14948 Before using any of these two tools, you need to compile successfully your
14949 application, so that GNAT gets a chance to generate the cross-referencing
14952 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14953 information to provide the user with the capability to easily locate the
14954 declaration and references to an entity. These tools are quite similar,
14955 the difference being that @code{gnatfind} is intended for locating
14956 definitions and/or references to a specified entity or entities, whereas
14957 @code{gnatxref} is oriented to generating a full report of all
14960 To use these tools, you must not compile your application using the
14961 @option{-gnatx} switch on the @command{gnatmake} command line
14962 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14963 information will not be generated.
14965 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14966 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14969 * gnatxref Switches::
14970 * gnatfind Switches::
14971 * Project Files for gnatxref and gnatfind::
14972 * Regular Expressions in gnatfind and gnatxref::
14973 * Examples of gnatxref Usage::
14974 * Examples of gnatfind Usage::
14977 @node gnatxref Switches
14978 @section @code{gnatxref} Switches
14981 The command invocation for @code{gnatxref} is:
14983 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
14992 identifies the source files for which a report is to be generated. The
14993 ``with''ed units will be processed too. You must provide at least one file.
14995 These file names are considered to be regular expressions, so for instance
14996 specifying @file{source*.adb} is the same as giving every file in the current
14997 directory whose name starts with @file{source} and whose extension is
15000 You shouldn't specify any directory name, just base names. @command{gnatxref}
15001 and @command{gnatfind} will be able to locate these files by themselves using
15002 the source path. If you specify directories, no result is produced.
15007 The switches can be:
15011 @cindex @option{--version} @command{gnatxref}
15012 Display Copyright and version, then exit disregarding all other options.
15015 @cindex @option{--help} @command{gnatxref}
15016 If @option{--version} was not used, display usage, then exit disregarding
15019 @item ^-a^/ALL_FILES^
15020 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15021 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15022 the read-only files found in the library search path. Otherwise, these files
15023 will be ignored. This option can be used to protect Gnat sources or your own
15024 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15025 much faster, and their output much smaller. Read-only here refers to access
15026 or permissions status in the file system for the current user.
15029 @cindex @option{-aIDIR} (@command{gnatxref})
15030 When looking for source files also look in directory DIR. The order in which
15031 source file search is undertaken is the same as for @command{gnatmake}.
15034 @cindex @option{-aODIR} (@command{gnatxref})
15035 When searching for library and object files, look in directory
15036 DIR. The order in which library files are searched is the same as for
15037 @command{gnatmake}.
15040 @cindex @option{-nostdinc} (@command{gnatxref})
15041 Do not look for sources in the system default directory.
15044 @cindex @option{-nostdlib} (@command{gnatxref})
15045 Do not look for library files in the system default directory.
15047 @item --RTS=@var{rts-path}
15048 @cindex @option{--RTS} (@command{gnatxref})
15049 Specifies the default location of the runtime library. Same meaning as the
15050 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15052 @item ^-d^/DERIVED_TYPES^
15053 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15054 If this switch is set @code{gnatxref} will output the parent type
15055 reference for each matching derived types.
15057 @item ^-f^/FULL_PATHNAME^
15058 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15059 If this switch is set, the output file names will be preceded by their
15060 directory (if the file was found in the search path). If this switch is
15061 not set, the directory will not be printed.
15063 @item ^-g^/IGNORE_LOCALS^
15064 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15065 If this switch is set, information is output only for library-level
15066 entities, ignoring local entities. The use of this switch may accelerate
15067 @code{gnatfind} and @code{gnatxref}.
15070 @cindex @option{-IDIR} (@command{gnatxref})
15071 Equivalent to @samp{-aODIR -aIDIR}.
15074 @cindex @option{-pFILE} (@command{gnatxref})
15075 Specify a project file to use @xref{Project Files}.
15076 If you need to use the @file{.gpr}
15077 project files, you should use gnatxref through the GNAT driver
15078 (@command{gnat xref -Pproject}).
15080 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15081 project file in the current directory.
15083 If a project file is either specified or found by the tools, then the content
15084 of the source directory and object directory lines are added as if they
15085 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15086 and @samp{^-aO^OBJECT_SEARCH^}.
15088 Output only unused symbols. This may be really useful if you give your
15089 main compilation unit on the command line, as @code{gnatxref} will then
15090 display every unused entity and 'with'ed package.
15094 Instead of producing the default output, @code{gnatxref} will generate a
15095 @file{tags} file that can be used by vi. For examples how to use this
15096 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15097 to the standard output, thus you will have to redirect it to a file.
15103 All these switches may be in any order on the command line, and may even
15104 appear after the file names. They need not be separated by spaces, thus
15105 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15106 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15108 @node gnatfind Switches
15109 @section @code{gnatfind} Switches
15112 The command line for @code{gnatfind} is:
15115 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15116 @r{[}@var{file1} @var{file2} @dots{}]
15124 An entity will be output only if it matches the regular expression found
15125 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15127 Omitting the pattern is equivalent to specifying @samp{*}, which
15128 will match any entity. Note that if you do not provide a pattern, you
15129 have to provide both a sourcefile and a line.
15131 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15132 for matching purposes. At the current time there is no support for
15133 8-bit codes other than Latin-1, or for wide characters in identifiers.
15136 @code{gnatfind} will look for references, bodies or declarations
15137 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15138 and column @var{column}. See @ref{Examples of gnatfind Usage}
15139 for syntax examples.
15142 is a decimal integer identifying the line number containing
15143 the reference to the entity (or entities) to be located.
15146 is a decimal integer identifying the exact location on the
15147 line of the first character of the identifier for the
15148 entity reference. Columns are numbered from 1.
15150 @item file1 file2 @dots{}
15151 The search will be restricted to these source files. If none are given, then
15152 the search will be done for every library file in the search path.
15153 These file must appear only after the pattern or sourcefile.
15155 These file names are considered to be regular expressions, so for instance
15156 specifying @file{source*.adb} is the same as giving every file in the current
15157 directory whose name starts with @file{source} and whose extension is
15160 The location of the spec of the entity will always be displayed, even if it
15161 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
15162 occurrences of the entity in the separate units of the ones given on the
15163 command line will also be displayed.
15165 Note that if you specify at least one file in this part, @code{gnatfind} may
15166 sometimes not be able to find the body of the subprograms.
15171 At least one of 'sourcefile' or 'pattern' has to be present on
15174 The following switches are available:
15178 @cindex @option{--version} @command{gnatfind}
15179 Display Copyright and version, then exit disregarding all other options.
15182 @cindex @option{--help} @command{gnatfind}
15183 If @option{--version} was not used, display usage, then exit disregarding
15186 @item ^-a^/ALL_FILES^
15187 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15188 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15189 the read-only files found in the library search path. Otherwise, these files
15190 will be ignored. This option can be used to protect Gnat sources or your own
15191 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15192 much faster, and their output much smaller. Read-only here refers to access
15193 or permission status in the file system for the current user.
15196 @cindex @option{-aIDIR} (@command{gnatfind})
15197 When looking for source files also look in directory DIR. The order in which
15198 source file search is undertaken is the same as for @command{gnatmake}.
15201 @cindex @option{-aODIR} (@command{gnatfind})
15202 When searching for library and object files, look in directory
15203 DIR. The order in which library files are searched is the same as for
15204 @command{gnatmake}.
15207 @cindex @option{-nostdinc} (@command{gnatfind})
15208 Do not look for sources in the system default directory.
15211 @cindex @option{-nostdlib} (@command{gnatfind})
15212 Do not look for library files in the system default directory.
15214 @item --RTS=@var{rts-path}
15215 @cindex @option{--RTS} (@command{gnatfind})
15216 Specifies the default location of the runtime library. Same meaning as the
15217 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15219 @item ^-d^/DERIVED_TYPE_INFORMATION^
15220 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15221 If this switch is set, then @code{gnatfind} will output the parent type
15222 reference for each matching derived types.
15224 @item ^-e^/EXPRESSIONS^
15225 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15226 By default, @code{gnatfind} accept the simple regular expression set for
15227 @samp{pattern}. If this switch is set, then the pattern will be
15228 considered as full Unix-style regular expression.
15230 @item ^-f^/FULL_PATHNAME^
15231 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15232 If this switch is set, the output file names will be preceded by their
15233 directory (if the file was found in the search path). If this switch is
15234 not set, the directory will not be printed.
15236 @item ^-g^/IGNORE_LOCALS^
15237 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15238 If this switch is set, information is output only for library-level
15239 entities, ignoring local entities. The use of this switch may accelerate
15240 @code{gnatfind} and @code{gnatxref}.
15243 @cindex @option{-IDIR} (@command{gnatfind})
15244 Equivalent to @samp{-aODIR -aIDIR}.
15247 @cindex @option{-pFILE} (@command{gnatfind})
15248 Specify a project file (@pxref{Project Files}) to use.
15249 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15250 project file in the current directory.
15252 If a project file is either specified or found by the tools, then the content
15253 of the source directory and object directory lines are added as if they
15254 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15255 @samp{^-aO^/OBJECT_SEARCH^}.
15257 @item ^-r^/REFERENCES^
15258 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15259 By default, @code{gnatfind} will output only the information about the
15260 declaration, body or type completion of the entities. If this switch is
15261 set, the @code{gnatfind} will locate every reference to the entities in
15262 the files specified on the command line (or in every file in the search
15263 path if no file is given on the command line).
15265 @item ^-s^/PRINT_LINES^
15266 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15267 If this switch is set, then @code{gnatfind} will output the content
15268 of the Ada source file lines were the entity was found.
15270 @item ^-t^/TYPE_HIERARCHY^
15271 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15272 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15273 the specified type. It act like -d option but recursively from parent
15274 type to parent type. When this switch is set it is not possible to
15275 specify more than one file.
15280 All these switches may be in any order on the command line, and may even
15281 appear after the file names. They need not be separated by spaces, thus
15282 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15283 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15285 As stated previously, gnatfind will search in every directory in the
15286 search path. You can force it to look only in the current directory if
15287 you specify @code{*} at the end of the command line.
15289 @node Project Files for gnatxref and gnatfind
15290 @section Project Files for @command{gnatxref} and @command{gnatfind}
15293 Project files allow a programmer to specify how to compile its
15294 application, where to find sources, etc. These files are used
15296 primarily by GPS, but they can also be used
15299 @code{gnatxref} and @code{gnatfind}.
15301 A project file name must end with @file{.gpr}. If a single one is
15302 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15303 extract the information from it. If multiple project files are found, none of
15304 them is read, and you have to use the @samp{-p} switch to specify the one
15307 The following lines can be included, even though most of them have default
15308 values which can be used in most cases.
15309 The lines can be entered in any order in the file.
15310 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15311 each line. If you have multiple instances, only the last one is taken into
15316 [default: @code{"^./^[]^"}]
15317 specifies a directory where to look for source files. Multiple @code{src_dir}
15318 lines can be specified and they will be searched in the order they
15322 [default: @code{"^./^[]^"}]
15323 specifies a directory where to look for object and library files. Multiple
15324 @code{obj_dir} lines can be specified, and they will be searched in the order
15327 @item comp_opt=SWITCHES
15328 [default: @code{""}]
15329 creates a variable which can be referred to subsequently by using
15330 the @code{$@{comp_opt@}} notation. This is intended to store the default
15331 switches given to @command{gnatmake} and @command{gcc}.
15333 @item bind_opt=SWITCHES
15334 [default: @code{""}]
15335 creates a variable which can be referred to subsequently by using
15336 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15337 switches given to @command{gnatbind}.
15339 @item link_opt=SWITCHES
15340 [default: @code{""}]
15341 creates a variable which can be referred to subsequently by using
15342 the @samp{$@{link_opt@}} notation. This is intended to store the default
15343 switches given to @command{gnatlink}.
15345 @item main=EXECUTABLE
15346 [default: @code{""}]
15347 specifies the name of the executable for the application. This variable can
15348 be referred to in the following lines by using the @samp{$@{main@}} notation.
15351 @item comp_cmd=COMMAND
15352 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15355 @item comp_cmd=COMMAND
15356 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15358 specifies the command used to compile a single file in the application.
15361 @item make_cmd=COMMAND
15362 [default: @code{"GNAT MAKE $@{main@}
15363 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15364 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15365 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15368 @item make_cmd=COMMAND
15369 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15370 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15371 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15373 specifies the command used to recompile the whole application.
15375 @item run_cmd=COMMAND
15376 [default: @code{"$@{main@}"}]
15377 specifies the command used to run the application.
15379 @item debug_cmd=COMMAND
15380 [default: @code{"gdb $@{main@}"}]
15381 specifies the command used to debug the application
15386 @command{gnatxref} and @command{gnatfind} only take into account the
15387 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15389 @node Regular Expressions in gnatfind and gnatxref
15390 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
15393 As specified in the section about @command{gnatfind}, the pattern can be a
15394 regular expression. Actually, there are to set of regular expressions
15395 which are recognized by the program:
15398 @item globbing patterns
15399 These are the most usual regular expression. They are the same that you
15400 generally used in a Unix shell command line, or in a DOS session.
15402 Here is a more formal grammar:
15409 term ::= elmt -- matches elmt
15410 term ::= elmt elmt -- concatenation (elmt then elmt)
15411 term ::= * -- any string of 0 or more characters
15412 term ::= ? -- matches any character
15413 term ::= [char @{char@}] -- matches any character listed
15414 term ::= [char - char] -- matches any character in range
15418 @item full regular expression
15419 The second set of regular expressions is much more powerful. This is the
15420 type of regular expressions recognized by utilities such a @file{grep}.
15422 The following is the form of a regular expression, expressed in Ada
15423 reference manual style BNF is as follows
15430 regexp ::= term @{| term@} -- alternation (term or term @dots{})
15432 term ::= item @{item@} -- concatenation (item then item)
15434 item ::= elmt -- match elmt
15435 item ::= elmt * -- zero or more elmt's
15436 item ::= elmt + -- one or more elmt's
15437 item ::= elmt ? -- matches elmt or nothing
15440 elmt ::= nschar -- matches given character
15441 elmt ::= [nschar @{nschar@}] -- matches any character listed
15442 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15443 elmt ::= [char - char] -- matches chars in given range
15444 elmt ::= \ char -- matches given character
15445 elmt ::= . -- matches any single character
15446 elmt ::= ( regexp ) -- parens used for grouping
15448 char ::= any character, including special characters
15449 nschar ::= any character except ()[].*+?^^^
15453 Following are a few examples:
15457 will match any of the two strings @samp{abcde} and @samp{fghi},
15460 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15461 @samp{abcccd}, and so on,
15464 will match any string which has only lowercase characters in it (and at
15465 least one character.
15470 @node Examples of gnatxref Usage
15471 @section Examples of @code{gnatxref} Usage
15473 @subsection General Usage
15476 For the following examples, we will consider the following units:
15478 @smallexample @c ada
15484 3: procedure Foo (B : in Integer);
15491 1: package body Main is
15492 2: procedure Foo (B : in Integer) is
15503 2: procedure Print (B : Integer);
15512 The first thing to do is to recompile your application (for instance, in
15513 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15514 the cross-referencing information.
15515 You can then issue any of the following commands:
15517 @item gnatxref main.adb
15518 @code{gnatxref} generates cross-reference information for main.adb
15519 and every unit 'with'ed by main.adb.
15521 The output would be:
15529 Decl: main.ads 3:20
15530 Body: main.adb 2:20
15531 Ref: main.adb 4:13 5:13 6:19
15534 Ref: main.adb 6:8 7:8
15544 Decl: main.ads 3:15
15545 Body: main.adb 2:15
15548 Body: main.adb 1:14
15551 Ref: main.adb 6:12 7:12
15555 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15556 its body is in main.adb, line 1, column 14 and is not referenced any where.
15558 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15559 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15561 @item gnatxref package1.adb package2.ads
15562 @code{gnatxref} will generates cross-reference information for
15563 package1.adb, package2.ads and any other package 'with'ed by any
15569 @subsection Using gnatxref with vi
15571 @code{gnatxref} can generate a tags file output, which can be used
15572 directly from @command{vi}. Note that the standard version of @command{vi}
15573 will not work properly with overloaded symbols. Consider using another
15574 free implementation of @command{vi}, such as @command{vim}.
15577 $ gnatxref -v gnatfind.adb > tags
15581 will generate the tags file for @code{gnatfind} itself (if the sources
15582 are in the search path!).
15584 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15585 (replacing @var{entity} by whatever you are looking for), and vi will
15586 display a new file with the corresponding declaration of entity.
15589 @node Examples of gnatfind Usage
15590 @section Examples of @code{gnatfind} Usage
15594 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15595 Find declarations for all entities xyz referenced at least once in
15596 main.adb. The references are search in every library file in the search
15599 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15602 The output will look like:
15604 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15605 ^directory/^[directory]^main.adb:24:10: xyz <= body
15606 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15610 that is to say, one of the entities xyz found in main.adb is declared at
15611 line 12 of main.ads (and its body is in main.adb), and another one is
15612 declared at line 45 of foo.ads
15614 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15615 This is the same command as the previous one, instead @code{gnatfind} will
15616 display the content of the Ada source file lines.
15618 The output will look like:
15621 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15623 ^directory/^[directory]^main.adb:24:10: xyz <= body
15625 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15630 This can make it easier to find exactly the location your are looking
15633 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15634 Find references to all entities containing an x that are
15635 referenced on line 123 of main.ads.
15636 The references will be searched only in main.ads and foo.adb.
15638 @item gnatfind main.ads:123
15639 Find declarations and bodies for all entities that are referenced on
15640 line 123 of main.ads.
15642 This is the same as @code{gnatfind "*":main.adb:123}.
15644 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15645 Find the declaration for the entity referenced at column 45 in
15646 line 123 of file main.adb in directory mydir. Note that it
15647 is usual to omit the identifier name when the column is given,
15648 since the column position identifies a unique reference.
15650 The column has to be the beginning of the identifier, and should not
15651 point to any character in the middle of the identifier.
15655 @c *********************************
15656 @node The GNAT Pretty-Printer gnatpp
15657 @chapter The GNAT Pretty-Printer @command{gnatpp}
15659 @cindex Pretty-Printer
15662 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15663 for source reformatting / pretty-printing.
15664 It takes an Ada source file as input and generates a reformatted
15666 You can specify various style directives via switches; e.g.,
15667 identifier case conventions, rules of indentation, and comment layout.
15669 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15670 tree for the input source and thus requires the input to be syntactically and
15671 semantically legal.
15672 If this condition is not met, @command{gnatpp} will terminate with an
15673 error message; no output file will be generated.
15675 If the source files presented to @command{gnatpp} contain
15676 preprocessing directives, then the output file will
15677 correspond to the generated source after all
15678 preprocessing is carried out. There is no way
15679 using @command{gnatpp} to obtain pretty printed files that
15680 include the preprocessing directives.
15682 If the compilation unit
15683 contained in the input source depends semantically upon units located
15684 outside the current directory, you have to provide the source search path
15685 when invoking @command{gnatpp}, if these units are contained in files with
15686 names that do not follow the GNAT file naming rules, you have to provide
15687 the configuration file describing the corresponding naming scheme;
15688 see the description of the @command{gnatpp}
15689 switches below. Another possibility is to use a project file and to
15690 call @command{gnatpp} through the @command{gnat} driver
15692 The @command{gnatpp} command has the form
15695 $ gnatpp @ovar{switches} @var{filename}
15702 @var{switches} is an optional sequence of switches defining such properties as
15703 the formatting rules, the source search path, and the destination for the
15707 @var{filename} is the name (including the extension) of the source file to
15708 reformat; ``wildcards'' or several file names on the same gnatpp command are
15709 allowed. The file name may contain path information; it does not have to
15710 follow the GNAT file naming rules
15714 * Switches for gnatpp::
15715 * Formatting Rules::
15718 @node Switches for gnatpp
15719 @section Switches for @command{gnatpp}
15722 The following subsections describe the various switches accepted by
15723 @command{gnatpp}, organized by category.
15726 You specify a switch by supplying a name and generally also a value.
15727 In many cases the values for a switch with a given name are incompatible with
15729 (for example the switch that controls the casing of a reserved word may have
15730 exactly one value: upper case, lower case, or
15731 mixed case) and thus exactly one such switch can be in effect for an
15732 invocation of @command{gnatpp}.
15733 If more than one is supplied, the last one is used.
15734 However, some values for the same switch are mutually compatible.
15735 You may supply several such switches to @command{gnatpp}, but then
15736 each must be specified in full, with both the name and the value.
15737 Abbreviated forms (the name appearing once, followed by each value) are
15739 For example, to set
15740 the alignment of the assignment delimiter both in declarations and in
15741 assignment statements, you must write @option{-A2A3}
15742 (or @option{-A2 -A3}), but not @option{-A23}.
15746 In many cases the set of options for a given qualifier are incompatible with
15747 each other (for example the qualifier that controls the casing of a reserved
15748 word may have exactly one option, which specifies either upper case, lower
15749 case, or mixed case), and thus exactly one such option can be in effect for
15750 an invocation of @command{gnatpp}.
15751 If more than one is supplied, the last one is used.
15752 However, some qualifiers have options that are mutually compatible,
15753 and then you may then supply several such options when invoking
15757 In most cases, it is obvious whether or not the
15758 ^values for a switch with a given name^options for a given qualifier^
15759 are compatible with each other.
15760 When the semantics might not be evident, the summaries below explicitly
15761 indicate the effect.
15764 * Alignment Control::
15766 * Construct Layout Control::
15767 * General Text Layout Control::
15768 * Other Formatting Options::
15769 * Setting the Source Search Path::
15770 * Output File Control::
15771 * Other gnatpp Switches::
15774 @node Alignment Control
15775 @subsection Alignment Control
15776 @cindex Alignment control in @command{gnatpp}
15779 Programs can be easier to read if certain constructs are vertically aligned.
15780 By default all alignments are set ON.
15781 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15782 OFF, and then use one or more of the other
15783 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15784 to activate alignment for specific constructs.
15787 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15791 Set all alignments to ON
15794 @item ^-A0^/ALIGN=OFF^
15795 Set all alignments to OFF
15797 @item ^-A1^/ALIGN=COLONS^
15798 Align @code{:} in declarations
15800 @item ^-A2^/ALIGN=DECLARATIONS^
15801 Align @code{:=} in initializations in declarations
15803 @item ^-A3^/ALIGN=STATEMENTS^
15804 Align @code{:=} in assignment statements
15806 @item ^-A4^/ALIGN=ARROWS^
15807 Align @code{=>} in associations
15809 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15810 Align @code{at} keywords in the component clauses in record
15811 representation clauses
15815 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15818 @node Casing Control
15819 @subsection Casing Control
15820 @cindex Casing control in @command{gnatpp}
15823 @command{gnatpp} allows you to specify the casing for reserved words,
15824 pragma names, attribute designators and identifiers.
15825 For identifiers you may define a
15826 general rule for name casing but also override this rule
15827 via a set of dictionary files.
15829 Three types of casing are supported: lower case, upper case, and mixed case.
15830 Lower and upper case are self-explanatory (but since some letters in
15831 Latin1 and other GNAT-supported character sets
15832 exist only in lower-case form, an upper case conversion will have no
15834 ``Mixed case'' means that the first letter, and also each letter immediately
15835 following an underscore, are converted to their uppercase forms;
15836 all the other letters are converted to their lowercase forms.
15839 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15840 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15841 Attribute designators are lower case
15843 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15844 Attribute designators are upper case
15846 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15847 Attribute designators are mixed case (this is the default)
15849 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15850 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15851 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15852 lower case (this is the default)
15854 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15855 Keywords are upper case
15857 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15858 @item ^-nD^/NAME_CASING=AS_DECLARED^
15859 Name casing for defining occurrences are as they appear in the source file
15860 (this is the default)
15862 @item ^-nU^/NAME_CASING=UPPER_CASE^
15863 Names are in upper case
15865 @item ^-nL^/NAME_CASING=LOWER_CASE^
15866 Names are in lower case
15868 @item ^-nM^/NAME_CASING=MIXED_CASE^
15869 Names are in mixed case
15871 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15872 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15873 Pragma names are lower case
15875 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15876 Pragma names are upper case
15878 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15879 Pragma names are mixed case (this is the default)
15881 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15882 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15883 Use @var{file} as a @emph{dictionary file} that defines
15884 the casing for a set of specified names,
15885 thereby overriding the effect on these names by
15886 any explicit or implicit
15887 ^-n^/NAME_CASING^ switch.
15888 To supply more than one dictionary file,
15889 use ^several @option{-D} switches^a list of files as options^.
15892 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15893 to define the casing for the Ada predefined names and
15894 the names declared in the GNAT libraries.
15896 @item ^-D-^/SPECIFIC_CASING^
15897 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15898 Do not use the default dictionary file;
15899 instead, use the casing
15900 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15905 The structure of a dictionary file, and details on the conventions
15906 used in the default dictionary file, are defined in @ref{Name Casing}.
15908 The @option{^-D-^/SPECIFIC_CASING^} and
15909 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15912 @node Construct Layout Control
15913 @subsection Construct Layout Control
15914 @cindex Layout control in @command{gnatpp}
15917 This group of @command{gnatpp} switches controls the layout of comments and
15918 complex syntactic constructs. See @ref{Formatting Comments} for details
15922 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15923 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15924 All the comments remain unchanged
15926 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15927 GNAT-style comment line indentation (this is the default).
15929 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15930 Reference-manual comment line indentation.
15932 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15933 GNAT-style comment beginning
15935 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15936 Reformat comment blocks
15938 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15939 Keep unchanged special form comments
15941 Reformat comment blocks
15943 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15944 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15945 GNAT-style layout (this is the default)
15947 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15950 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15953 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15955 All the VT characters are removed from the comment text. All the HT characters
15956 are expanded with the sequences of space characters to get to the next tab
15959 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15960 @item ^--no-separate-is^/NO_SEPARATE_IS^
15961 Do not place the keyword @code{is} on a separate line in a subprogram body in
15962 case if the spec occupies more then one line.
15964 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
15965 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
15966 Place the keyword @code{loop} in FOR and WHILE loop statements and the
15967 keyword @code{then} in IF statements on a separate line.
15969 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
15970 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
15971 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
15972 keyword @code{then} in IF statements on a separate line. This option is
15973 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
15975 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
15976 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
15977 Start each USE clause in a context clause from a separate line.
15979 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
15980 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
15981 Use a separate line for a loop or block statement name, but do not use an extra
15982 indentation level for the statement itself.
15988 The @option{-c1} and @option{-c2} switches are incompatible.
15989 The @option{-c3} and @option{-c4} switches are compatible with each other and
15990 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15991 the other comment formatting switches.
15993 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15998 For the @option{/COMMENTS_LAYOUT} qualifier:
16001 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16003 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16004 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16008 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16009 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16012 @node General Text Layout Control
16013 @subsection General Text Layout Control
16016 These switches allow control over line length and indentation.
16019 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16020 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16021 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16023 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16024 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16025 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16027 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16028 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16029 Indentation level for continuation lines (relative to the line being
16030 continued), @var{nnn} from 1@dots{}9.
16032 value is one less then the (normal) indentation level, unless the
16033 indentation is set to 1 (in which case the default value for continuation
16034 line indentation is also 1)
16037 @node Other Formatting Options
16038 @subsection Other Formatting Options
16041 These switches control the inclusion of missing end/exit labels, and
16042 the indentation level in @b{case} statements.
16045 @item ^-e^/NO_MISSED_LABELS^
16046 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16047 Do not insert missing end/exit labels. An end label is the name of
16048 a construct that may optionally be repeated at the end of the
16049 construct's declaration;
16050 e.g., the names of packages, subprograms, and tasks.
16051 An exit label is the name of a loop that may appear as target
16052 of an exit statement within the loop.
16053 By default, @command{gnatpp} inserts these end/exit labels when
16054 they are absent from the original source. This option suppresses such
16055 insertion, so that the formatted source reflects the original.
16057 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16058 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16059 Insert a Form Feed character after a pragma Page.
16061 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16062 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16063 Do not use an additional indentation level for @b{case} alternatives
16064 and variants if there are @var{nnn} or more (the default
16066 If @var{nnn} is 0, an additional indentation level is
16067 used for @b{case} alternatives and variants regardless of their number.
16070 @node Setting the Source Search Path
16071 @subsection Setting the Source Search Path
16074 To define the search path for the input source file, @command{gnatpp}
16075 uses the same switches as the GNAT compiler, with the same effects.
16078 @item ^-I^/SEARCH=^@var{dir}
16079 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16080 The same as the corresponding gcc switch
16082 @item ^-I-^/NOCURRENT_DIRECTORY^
16083 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16084 The same as the corresponding gcc switch
16086 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16087 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16088 The same as the corresponding gcc switch
16090 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16091 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16092 The same as the corresponding gcc switch
16096 @node Output File Control
16097 @subsection Output File Control
16100 By default the output is sent to the file whose name is obtained by appending
16101 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16102 (if the file with this name already exists, it is unconditionally overwritten).
16103 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16104 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16106 The output may be redirected by the following switches:
16109 @item ^-pipe^/STANDARD_OUTPUT^
16110 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16111 Send the output to @code{Standard_Output}
16113 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16114 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16115 Write the output into @var{output_file}.
16116 If @var{output_file} already exists, @command{gnatpp} terminates without
16117 reading or processing the input file.
16119 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16120 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16121 Write the output into @var{output_file}, overwriting the existing file
16122 (if one is present).
16124 @item ^-r^/REPLACE^
16125 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16126 Replace the input source file with the reformatted output, and copy the
16127 original input source into the file whose name is obtained by appending the
16128 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16129 If a file with this name already exists, @command{gnatpp} terminates without
16130 reading or processing the input file.
16132 @item ^-rf^/OVERRIDING_REPLACE^
16133 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16134 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16135 already exists, it is overwritten.
16137 @item ^-rnb^/REPLACE_NO_BACKUP^
16138 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16139 Replace the input source file with the reformatted output without
16140 creating any backup copy of the input source.
16142 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16143 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16144 Specifies the format of the reformatted output file. The @var{xxx}
16145 ^string specified with the switch^option^ may be either
16147 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16148 @item ``@option{^crlf^CRLF^}''
16149 the same as @option{^crlf^CRLF^}
16150 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16151 @item ``@option{^lf^LF^}''
16152 the same as @option{^unix^UNIX^}
16155 @item ^-W^/RESULT_ENCODING=^@var{e}
16156 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16157 Specify the wide character encoding method used to write the code in the
16159 @var{e} is one of the following:
16167 Upper half encoding
16169 @item ^s^SHIFT_JIS^
16179 Brackets encoding (default value)
16185 Options @option{^-pipe^/STANDARD_OUTPUT^},
16186 @option{^-o^/OUTPUT^} and
16187 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16188 contains only one file to reformat.
16190 @option{^--eol^/END_OF_LINE^}
16192 @option{^-W^/RESULT_ENCODING^}
16193 cannot be used together
16194 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16196 @node Other gnatpp Switches
16197 @subsection Other @code{gnatpp} Switches
16200 The additional @command{gnatpp} switches are defined in this subsection.
16203 @item ^-files @var{filename}^/FILES=@var{output_file}^
16204 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16205 Take the argument source files from the specified file. This file should be an
16206 ordinary textual file containing file names separated by spaces or
16207 line breaks. You can use this switch more then once in the same call to
16208 @command{gnatpp}. You also can combine this switch with explicit list of
16211 @item ^-v^/VERBOSE^
16212 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16214 @command{gnatpp} generates version information and then
16215 a trace of the actions it takes to produce or obtain the ASIS tree.
16217 @item ^-w^/WARNINGS^
16218 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16220 @command{gnatpp} generates a warning whenever it cannot provide
16221 a required layout in the result source.
16224 @node Formatting Rules
16225 @section Formatting Rules
16228 The following subsections show how @command{gnatpp} treats ``white space'',
16229 comments, program layout, and name casing.
16230 They provide the detailed descriptions of the switches shown above.
16233 * White Space and Empty Lines::
16234 * Formatting Comments::
16235 * Construct Layout::
16239 @node White Space and Empty Lines
16240 @subsection White Space and Empty Lines
16243 @command{gnatpp} does not have an option to control space characters.
16244 It will add or remove spaces according to the style illustrated by the
16245 examples in the @cite{Ada Reference Manual}.
16247 The only format effectors
16248 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16249 that will appear in the output file are platform-specific line breaks,
16250 and also format effectors within (but not at the end of) comments.
16251 In particular, each horizontal tab character that is not inside
16252 a comment will be treated as a space and thus will appear in the
16253 output file as zero or more spaces depending on
16254 the reformatting of the line in which it appears.
16255 The only exception is a Form Feed character, which is inserted after a
16256 pragma @code{Page} when @option{-ff} is set.
16258 The output file will contain no lines with trailing ``white space'' (spaces,
16261 Empty lines in the original source are preserved
16262 only if they separate declarations or statements.
16263 In such contexts, a
16264 sequence of two or more empty lines is replaced by exactly one empty line.
16265 Note that a blank line will be removed if it separates two ``comment blocks''
16266 (a comment block is a sequence of whole-line comments).
16267 In order to preserve a visual separation between comment blocks, use an
16268 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16269 Likewise, if for some reason you wish to have a sequence of empty lines,
16270 use a sequence of empty comments instead.
16272 @node Formatting Comments
16273 @subsection Formatting Comments
16276 Comments in Ada code are of two kinds:
16279 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16280 ``white space'') on a line
16283 an @emph{end-of-line comment}, which follows some other Ada lexical element
16288 The indentation of a whole-line comment is that of either
16289 the preceding or following line in
16290 the formatted source, depending on switch settings as will be described below.
16292 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16293 between the end of the preceding Ada lexical element and the beginning
16294 of the comment as appear in the original source,
16295 unless either the comment has to be split to
16296 satisfy the line length limitation, or else the next line contains a
16297 whole line comment that is considered a continuation of this end-of-line
16298 comment (because it starts at the same position).
16300 cases, the start of the end-of-line comment is moved right to the nearest
16301 multiple of the indentation level.
16302 This may result in a ``line overflow'' (the right-shifted comment extending
16303 beyond the maximum line length), in which case the comment is split as
16306 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16307 (GNAT-style comment line indentation)
16308 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16309 (reference-manual comment line indentation).
16310 With reference-manual style, a whole-line comment is indented as if it
16311 were a declaration or statement at the same place
16312 (i.e., according to the indentation of the preceding line(s)).
16313 With GNAT style, a whole-line comment that is immediately followed by an
16314 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16315 word @b{begin}, is indented based on the construct that follows it.
16318 @smallexample @c ada
16330 Reference-manual indentation produces:
16332 @smallexample @c ada
16344 while GNAT-style indentation produces:
16346 @smallexample @c ada
16358 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16359 (GNAT style comment beginning) has the following
16364 For each whole-line comment that does not end with two hyphens,
16365 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16366 to ensure that there are at least two spaces between these hyphens and the
16367 first non-blank character of the comment.
16371 For an end-of-line comment, if in the original source the next line is a
16372 whole-line comment that starts at the same position
16373 as the end-of-line comment,
16374 then the whole-line comment (and all whole-line comments
16375 that follow it and that start at the same position)
16376 will start at this position in the output file.
16379 That is, if in the original source we have:
16381 @smallexample @c ada
16384 A := B + C; -- B must be in the range Low1..High1
16385 -- C must be in the range Low2..High2
16386 --B+C will be in the range Low1+Low2..High1+High2
16392 Then in the formatted source we get
16394 @smallexample @c ada
16397 A := B + C; -- B must be in the range Low1..High1
16398 -- C must be in the range Low2..High2
16399 -- B+C will be in the range Low1+Low2..High1+High2
16405 A comment that exceeds the line length limit will be split.
16407 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16408 the line belongs to a reformattable block, splitting the line generates a
16409 @command{gnatpp} warning.
16410 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16411 comments may be reformatted in typical
16412 word processor style (that is, moving words between lines and putting as
16413 many words in a line as possible).
16416 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16417 that has a special format (that is, a character that is neither a letter nor digit
16418 not white space nor line break immediately following the leading @code{--} of
16419 the comment) should be without any change moved from the argument source
16420 into reformatted source. This switch allows to preserve comments that are used
16421 as a special marks in the code (e.g.@: SPARK annotation).
16423 @node Construct Layout
16424 @subsection Construct Layout
16427 In several cases the suggested layout in the Ada Reference Manual includes
16428 an extra level of indentation that many programmers prefer to avoid. The
16429 affected cases include:
16433 @item Record type declaration (RM 3.8)
16435 @item Record representation clause (RM 13.5.1)
16437 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16439 @item Block statement in case if a block has a statement identifier (RM 5.6)
16443 In compact mode (when GNAT style layout or compact layout is set),
16444 the pretty printer uses one level of indentation instead
16445 of two. This is achieved in the record definition and record representation
16446 clause cases by putting the @code{record} keyword on the same line as the
16447 start of the declaration or representation clause, and in the block and loop
16448 case by putting the block or loop header on the same line as the statement
16452 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16453 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16454 layout on the one hand, and uncompact layout
16455 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16456 can be illustrated by the following examples:
16460 @multitable @columnfractions .5 .5
16461 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16464 @smallexample @c ada
16471 @smallexample @c ada
16480 @smallexample @c ada
16482 a at 0 range 0 .. 31;
16483 b at 4 range 0 .. 31;
16487 @smallexample @c ada
16490 a at 0 range 0 .. 31;
16491 b at 4 range 0 .. 31;
16496 @smallexample @c ada
16504 @smallexample @c ada
16514 @smallexample @c ada
16515 Clear : for J in 1 .. 10 loop
16520 @smallexample @c ada
16522 for J in 1 .. 10 loop
16533 GNAT style, compact layout Uncompact layout
16535 type q is record type q is
16536 a : integer; record
16537 b : integer; a : integer;
16538 end record; b : integer;
16541 for q use record for q use
16542 a at 0 range 0 .. 31; record
16543 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
16544 end record; b at 4 range 0 .. 31;
16547 Block : declare Block :
16548 A : Integer := 3; declare
16549 begin A : Integer := 3;
16551 end Block; Proc (A, A);
16554 Clear : for J in 1 .. 10 loop Clear :
16555 A (J) := 0; for J in 1 .. 10 loop
16556 end loop Clear; A (J) := 0;
16563 A further difference between GNAT style layout and compact layout is that
16564 GNAT style layout inserts empty lines as separation for
16565 compound statements, return statements and bodies.
16567 Note that the layout specified by
16568 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16569 for named block and loop statements overrides the layout defined by these
16570 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16571 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16572 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16575 @subsection Name Casing
16578 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16579 the same casing as the corresponding defining identifier.
16581 You control the casing for defining occurrences via the
16582 @option{^-n^/NAME_CASING^} switch.
16584 With @option{-nD} (``as declared'', which is the default),
16587 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16589 defining occurrences appear exactly as in the source file
16590 where they are declared.
16591 The other ^values for this switch^options for this qualifier^ ---
16592 @option{^-nU^UPPER_CASE^},
16593 @option{^-nL^LOWER_CASE^},
16594 @option{^-nM^MIXED_CASE^} ---
16596 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16597 If @command{gnatpp} changes the casing of a defining
16598 occurrence, it analogously changes the casing of all the
16599 usage occurrences of this name.
16601 If the defining occurrence of a name is not in the source compilation unit
16602 currently being processed by @command{gnatpp}, the casing of each reference to
16603 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16604 switch (subject to the dictionary file mechanism described below).
16605 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16607 casing for the defining occurrence of the name.
16609 Some names may need to be spelled with casing conventions that are not
16610 covered by the upper-, lower-, and mixed-case transformations.
16611 You can arrange correct casing by placing such names in a
16612 @emph{dictionary file},
16613 and then supplying a @option{^-D^/DICTIONARY^} switch.
16614 The casing of names from dictionary files overrides
16615 any @option{^-n^/NAME_CASING^} switch.
16617 To handle the casing of Ada predefined names and the names from GNAT libraries,
16618 @command{gnatpp} assumes a default dictionary file.
16619 The name of each predefined entity is spelled with the same casing as is used
16620 for the entity in the @cite{Ada Reference Manual}.
16621 The name of each entity in the GNAT libraries is spelled with the same casing
16622 as is used in the declaration of that entity.
16624 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16625 default dictionary file.
16626 Instead, the casing for predefined and GNAT-defined names will be established
16627 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16628 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16629 will appear as just shown,
16630 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16631 To ensure that even such names are rendered in uppercase,
16632 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16633 (or else, less conveniently, place these names in upper case in a dictionary
16636 A dictionary file is
16637 a plain text file; each line in this file can be either a blank line
16638 (containing only space characters and ASCII.HT characters), an Ada comment
16639 line, or the specification of exactly one @emph{casing schema}.
16641 A casing schema is a string that has the following syntax:
16645 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16647 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16652 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16653 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16655 The casing schema string can be followed by white space and/or an Ada-style
16656 comment; any amount of white space is allowed before the string.
16658 If a dictionary file is passed as
16660 the value of a @option{-D@var{file}} switch
16663 an option to the @option{/DICTIONARY} qualifier
16666 simple name and every identifier, @command{gnatpp} checks if the dictionary
16667 defines the casing for the name or for some of its parts (the term ``subword''
16668 is used below to denote the part of a name which is delimited by ``_'' or by
16669 the beginning or end of the word and which does not contain any ``_'' inside):
16673 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16674 the casing defined by the dictionary; no subwords are checked for this word
16677 for every subword @command{gnatpp} checks if the dictionary contains the
16678 corresponding string of the form @code{*@var{simple_identifier}*},
16679 and if it does, the casing of this @var{simple_identifier} is used
16683 if the whole name does not contain any ``_'' inside, and if for this name
16684 the dictionary contains two entries - one of the form @var{identifier},
16685 and another - of the form *@var{simple_identifier}*, then the first one
16686 is applied to define the casing of this name
16689 if more than one dictionary file is passed as @command{gnatpp} switches, each
16690 dictionary adds new casing exceptions and overrides all the existing casing
16691 exceptions set by the previous dictionaries
16694 when @command{gnatpp} checks if the word or subword is in the dictionary,
16695 this check is not case sensitive
16699 For example, suppose we have the following source to reformat:
16701 @smallexample @c ada
16704 name1 : integer := 1;
16705 name4_name3_name2 : integer := 2;
16706 name2_name3_name4 : Boolean;
16709 name2_name3_name4 := name4_name3_name2 > name1;
16715 And suppose we have two dictionaries:
16732 If @command{gnatpp} is called with the following switches:
16736 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16739 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16744 then we will get the following name casing in the @command{gnatpp} output:
16746 @smallexample @c ada
16749 NAME1 : Integer := 1;
16750 Name4_NAME3_Name2 : Integer := 2;
16751 Name2_NAME3_Name4 : Boolean;
16754 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16759 @c *********************************
16760 @node The GNAT Metric Tool gnatmetric
16761 @chapter The GNAT Metric Tool @command{gnatmetric}
16763 @cindex Metric tool
16766 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16767 for computing various program metrics.
16768 It takes an Ada source file as input and generates a file containing the
16769 metrics data as output. Various switches control which
16770 metrics are computed and output.
16772 @command{gnatmetric} generates and uses the ASIS
16773 tree for the input source and thus requires the input to be syntactically and
16774 semantically legal.
16775 If this condition is not met, @command{gnatmetric} will generate
16776 an error message; no metric information for this file will be
16777 computed and reported.
16779 If the compilation unit contained in the input source depends semantically
16780 upon units in files located outside the current directory, you have to provide
16781 the source search path when invoking @command{gnatmetric}.
16782 If it depends semantically upon units that are contained
16783 in files with names that do not follow the GNAT file naming rules, you have to
16784 provide the configuration file describing the corresponding naming scheme (see
16785 the description of the @command{gnatmetric} switches below.)
16786 Alternatively, you may use a project file and invoke @command{gnatmetric}
16787 through the @command{gnat} driver.
16789 The @command{gnatmetric} command has the form
16792 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
16799 @var{switches} specify the metrics to compute and define the destination for
16803 Each @var{filename} is the name (including the extension) of a source
16804 file to process. ``Wildcards'' are allowed, and
16805 the file name may contain path information.
16806 If no @var{filename} is supplied, then the @var{switches} list must contain
16808 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16809 Including both a @option{-files} switch and one or more
16810 @var{filename} arguments is permitted.
16813 @samp{-cargs @var{gcc_switches}} is a list of switches for
16814 @command{gcc}. They will be passed on to all compiler invocations made by
16815 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16816 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16817 and use the @option{-gnatec} switch to set the configuration file.
16821 * Switches for gnatmetric::
16824 @node Switches for gnatmetric
16825 @section Switches for @command{gnatmetric}
16828 The following subsections describe the various switches accepted by
16829 @command{gnatmetric}, organized by category.
16832 * Output Files Control::
16833 * Disable Metrics For Local Units::
16834 * Specifying a set of metrics to compute::
16835 * Other gnatmetric Switches::
16836 * Generate project-wide metrics::
16839 @node Output Files Control
16840 @subsection Output File Control
16841 @cindex Output file control in @command{gnatmetric}
16844 @command{gnatmetric} has two output formats. It can generate a
16845 textual (human-readable) form, and also XML. By default only textual
16846 output is generated.
16848 When generating the output in textual form, @command{gnatmetric} creates
16849 for each Ada source file a corresponding text file
16850 containing the computed metrics, except for the case when the set of metrics
16851 specified by gnatmetric parameters consists only of metrics that are computed
16852 for the whole set of analyzed sources, but not for each Ada source.
16853 By default, this file is placed in the same directory as where the source
16854 file is located, and its name is obtained
16855 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16858 All the output information generated in XML format is placed in a single
16859 file. By default this file is placed in the current directory and has the
16860 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16862 Some of the computed metrics are summed over the units passed to
16863 @command{gnatmetric}; for example, the total number of lines of code.
16864 By default this information is sent to @file{stdout}, but a file
16865 can be specified with the @option{-og} switch.
16867 The following switches control the @command{gnatmetric} output:
16870 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16872 Generate the XML output
16874 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16875 @item ^-nt^/NO_TEXT^
16876 Do not generate the output in text form (implies @option{^-x^/XML^})
16878 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16879 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16880 Put textual files with detailed metrics into @var{output_dir}
16882 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16883 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16884 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16885 in the name of the output file.
16887 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16888 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16889 Put global metrics into @var{file_name}
16891 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16892 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16893 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16895 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16896 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16897 Use ``short'' source file names in the output. (The @command{gnatmetric}
16898 output includes the name(s) of the Ada source file(s) from which the metrics
16899 are computed. By default each name includes the absolute path. The
16900 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16901 to exclude all directory information from the file names that are output.)
16905 @node Disable Metrics For Local Units
16906 @subsection Disable Metrics For Local Units
16907 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16910 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16912 unit per one source file. It computes line metrics for the whole source
16913 file, and it also computes syntax
16914 and complexity metrics for the file's outermost unit.
16916 By default, @command{gnatmetric} will also compute all metrics for certain
16917 kinds of locally declared program units:
16921 subprogram (and generic subprogram) bodies;
16924 package (and generic package) specs and bodies;
16927 task object and type specifications and bodies;
16930 protected object and type specifications and bodies.
16934 These kinds of entities will be referred to as
16935 @emph{eligible local program units}, or simply @emph{eligible local units},
16936 @cindex Eligible local unit (for @command{gnatmetric})
16937 in the discussion below.
16939 Note that a subprogram declaration, generic instantiation,
16940 or renaming declaration only receives metrics
16941 computation when it appear as the outermost entity
16944 Suppression of metrics computation for eligible local units can be
16945 obtained via the following switch:
16948 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16949 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16950 Do not compute detailed metrics for eligible local program units
16954 @node Specifying a set of metrics to compute
16955 @subsection Specifying a set of metrics to compute
16958 By default all the metrics are computed and reported. The switches
16959 described in this subsection allow you to control, on an individual
16960 basis, whether metrics are computed and
16961 reported. If at least one positive metric
16962 switch is specified (that is, a switch that defines that a given
16963 metric or set of metrics is to be computed), then only
16964 explicitly specified metrics are reported.
16967 * Line Metrics Control::
16968 * Syntax Metrics Control::
16969 * Complexity Metrics Control::
16970 * Object-Oriented Metrics Control::
16973 @node Line Metrics Control
16974 @subsubsection Line Metrics Control
16975 @cindex Line metrics control in @command{gnatmetric}
16978 For any (legal) source file, and for each of its
16979 eligible local program units, @command{gnatmetric} computes the following
16984 the total number of lines;
16987 the total number of code lines (i.e., non-blank lines that are not comments)
16990 the number of comment lines
16993 the number of code lines containing end-of-line comments;
16996 the comment percentage: the ratio between the number of lines that contain
16997 comments and the number of all non-blank lines, expressed as a percentage;
17000 the number of empty lines and lines containing only space characters and/or
17001 format effectors (blank lines)
17004 the average number of code lines in subprogram bodies, task bodies, entry
17005 bodies and statement sequences in package bodies (this metric is only computed
17006 across the whole set of the analyzed units)
17011 @command{gnatmetric} sums the values of the line metrics for all the
17012 files being processed and then generates the cumulative results. The tool
17013 also computes for all the files being processed the average number of code
17016 You can use the following switches to select the specific line metrics
17017 to be computed and reported.
17020 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17023 @cindex @option{--no-lines@var{x}}
17026 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
17027 Report all the line metrics
17029 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
17030 Do not report any of line metrics
17032 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
17033 Report the number of all lines
17035 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
17036 Do not report the number of all lines
17038 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
17039 Report the number of code lines
17041 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
17042 Do not report the number of code lines
17044 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
17045 Report the number of comment lines
17047 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
17048 Do not report the number of comment lines
17050 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
17051 Report the number of code lines containing
17052 end-of-line comments
17054 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
17055 Do not report the number of code lines containing
17056 end-of-line comments
17058 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
17059 Report the comment percentage in the program text
17061 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
17062 Do not report the comment percentage in the program text
17064 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
17065 Report the number of blank lines
17067 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
17068 Do not report the number of blank lines
17070 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
17071 Report the average number of code lines in subprogram bodies, task bodies,
17072 entry bodies and statement sequences in package bodies. The metric is computed
17073 and reported for the whole set of processed Ada sources only.
17075 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
17076 Do not report the average number of code lines in subprogram bodies,
17077 task bodies, entry bodies and statement sequences in package bodies.
17081 @node Syntax Metrics Control
17082 @subsubsection Syntax Metrics Control
17083 @cindex Syntax metrics control in @command{gnatmetric}
17086 @command{gnatmetric} computes various syntactic metrics for the
17087 outermost unit and for each eligible local unit:
17090 @item LSLOC (``Logical Source Lines Of Code'')
17091 The total number of declarations and the total number of statements
17093 @item Maximal static nesting level of inner program units
17095 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17096 package, a task unit, a protected unit, a
17097 protected entry, a generic unit, or an explicitly declared subprogram other
17098 than an enumeration literal.''
17100 @item Maximal nesting level of composite syntactic constructs
17101 This corresponds to the notion of the
17102 maximum nesting level in the GNAT built-in style checks
17103 (@pxref{Style Checking})
17107 For the outermost unit in the file, @command{gnatmetric} additionally computes
17108 the following metrics:
17111 @item Public subprograms
17112 This metric is computed for package specs. It is the
17113 number of subprograms and generic subprograms declared in the visible
17114 part (including the visible part of nested packages, protected objects, and
17117 @item All subprograms
17118 This metric is computed for bodies and subunits. The
17119 metric is equal to a total number of subprogram bodies in the compilation
17121 Neither generic instantiations nor renamings-as-a-body nor body stubs
17122 are counted. Any subprogram body is counted, independently of its nesting
17123 level and enclosing constructs. Generic bodies and bodies of protected
17124 subprograms are counted in the same way as ``usual'' subprogram bodies.
17127 This metric is computed for package specs and
17128 generic package declarations. It is the total number of types
17129 that can be referenced from outside this compilation unit, plus the
17130 number of types from all the visible parts of all the visible generic
17131 packages. Generic formal types are not counted. Only types, not subtypes,
17135 Along with the total number of public types, the following
17136 types are counted and reported separately:
17143 Root tagged types (abstract, non-abstract, private, non-private). Type
17144 extensions are @emph{not} counted
17147 Private types (including private extensions)
17158 This metric is computed for any compilation unit. It is equal to the total
17159 number of the declarations of different types given in the compilation unit.
17160 The private and the corresponding full type declaration are counted as one
17161 type declaration. Incomplete type declarations and generic formal types
17163 No distinction is made among different kinds of types (abstract,
17164 private etc.); the total number of types is computed and reported.
17169 By default, all the syntax metrics are computed and reported. You can use the
17170 following switches to select specific syntax metrics.
17174 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17177 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17180 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
17181 Report all the syntax metrics
17183 @item ^--no-syntax-all^/ALL_OFF^
17184 Do not report any of syntax metrics
17186 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
17187 Report the total number of declarations
17189 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
17190 Do not report the total number of declarations
17192 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
17193 Report the total number of statements
17195 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
17196 Do not report the total number of statements
17198 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
17199 Report the number of public subprograms in a compilation unit
17201 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
17202 Do not report the number of public subprograms in a compilation unit
17204 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
17205 Report the number of all the subprograms in a compilation unit
17207 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
17208 Do not report the number of all the subprograms in a compilation unit
17210 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
17211 Report the number of public types in a compilation unit
17213 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
17214 Do not report the number of public types in a compilation unit
17216 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
17217 Report the number of all the types in a compilation unit
17219 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
17220 Do not report the number of all the types in a compilation unit
17222 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
17223 Report the maximal program unit nesting level
17225 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17226 Do not report the maximal program unit nesting level
17228 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
17229 Report the maximal construct nesting level
17231 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
17232 Do not report the maximal construct nesting level
17236 @node Complexity Metrics Control
17237 @subsubsection Complexity Metrics Control
17238 @cindex Complexity metrics control in @command{gnatmetric}
17241 For a program unit that is an executable body (a subprogram body (including
17242 generic bodies), task body, entry body or a package body containing
17243 its own statement sequence) @command{gnatmetric} computes the following
17244 complexity metrics:
17248 McCabe cyclomatic complexity;
17251 McCabe essential complexity;
17254 maximal loop nesting level
17259 The McCabe complexity metrics are defined
17260 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17262 According to McCabe, both control statements and short-circuit control forms
17263 should be taken into account when computing cyclomatic complexity. For each
17264 body, we compute three metric values:
17268 the complexity introduced by control
17269 statements only, without taking into account short-circuit forms,
17272 the complexity introduced by short-circuit control forms only, and
17276 cyclomatic complexity, which is the sum of these two values.
17280 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17281 the code in the exception handlers and in all the nested program units.
17283 By default, all the complexity metrics are computed and reported.
17284 For more fine-grained control you can use
17285 the following switches:
17288 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17291 @cindex @option{--no-complexity@var{x}}
17294 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
17295 Report all the complexity metrics
17297 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
17298 Do not report any of complexity metrics
17300 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
17301 Report the McCabe Cyclomatic Complexity
17303 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
17304 Do not report the McCabe Cyclomatic Complexity
17306 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
17307 Report the Essential Complexity
17309 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
17310 Do not report the Essential Complexity
17312 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17313 Report maximal loop nesting level
17315 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
17316 Do not report maximal loop nesting level
17318 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
17319 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17320 task bodies, entry bodies and statement sequences in package bodies.
17321 The metric is computed and reported for whole set of processed Ada sources
17324 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
17325 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17326 bodies, task bodies, entry bodies and statement sequences in package bodies
17328 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17329 @item ^-ne^/NO_EXITS_AS_GOTOS^
17330 Do not consider @code{exit} statements as @code{goto}s when
17331 computing Essential Complexity
17336 @node Object-Oriented Metrics Control
17337 @subsubsection Object-Oriented Metrics Control
17338 @cindex Object-Oriented metrics control in @command{gnatmetric}
17341 @cindex Coupling metrics (in in @command{gnatmetric})
17342 Coupling metrics are object-oriented metrics that measure the
17343 dependencies between a given class (or a group of classes) and the
17344 ``external world'' (that is, the other classes in the program). In this
17345 subsection the term ``class'' is used in its
17346 traditional object-oriented programming sense
17347 (an instantiable module that contains data and/or method members).
17348 A @emph{category} (of classes)
17349 is a group of closely related classes that are reused and/or
17352 A class @code{K}'s @emph{efferent coupling} is the number of classes
17353 that @code{K} depends upon.
17354 A category's efferent coupling is the number of classes outside the
17355 category that the classes inside the category depend upon.
17357 A class @code{K}'s @emph{afferent coupling} is the number of classes
17358 that depend upon @code{K}.
17359 A category's afferent coupling is the number of classes outside the
17360 category that depend on classes belonging to the category.
17362 Ada's implementation of the object-oriented paradigm does not use the
17363 traditional class notion, so the definition of the coupling
17364 metrics for Ada maps the class and class category notions
17365 onto Ada constructs.
17367 For the coupling metrics, several kinds of modules -- a library package,
17368 a library generic package, and a library generic package instantiation --
17369 that define a tagged type or an interface type are
17370 considered to be a class. A category consists of a library package (or
17371 a library generic package) that defines a tagged or an interface type,
17372 together with all its descendant (generic) packages that define tagged
17373 or interface types. For any package counted as a class,
17374 its body (if any) is considered
17375 together with its spec when counting the dependencies. For dependencies
17376 between classes, the Ada semantic dependencies are considered.
17377 For coupling metrics, only dependencies on units that are considered as
17378 classes, are considered.
17380 When computing coupling metrics, @command{gnatmetric} counts only
17381 dependencies between units that are arguments of the gnatmetric call.
17382 Coupling metrics are program-wide (or project-wide) metrics, so to
17383 get a valid result, you should call @command{gnatmetric} for
17384 the whole set of sources that make up your program. It can be done
17385 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17386 option (see See @ref{The GNAT Driver and Project Files} for details.
17388 By default, all the coupling metrics are disabled. You can use the following
17389 switches to specify the coupling metrics to be computed and reported:
17394 @cindex @option{--package@var{x}} (@command{gnatmetric})
17395 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17396 @cindex @option{--category@var{x}} (@command{gnatmetric})
17397 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17401 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17404 @item ^--coupling-all^/COUPLING_METRICS=ALL_ON^
17405 Report all the coupling metrics
17407 @item ^--no-coupling-all^/COUPLING_METRICS=ALL_OFF^
17408 Do not report any of metrics
17410 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_ON^
17411 Report package efferent coupling
17413 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_OFF^
17414 Do not report package efferent coupling
17416 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_ON^
17417 Report package afferent coupling
17419 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_OFF^
17420 Do not report package afferent coupling
17422 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_ON^
17423 Report category efferent coupling
17425 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_OFF^
17426 Do not report category efferent coupling
17428 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_ON^
17429 Report category afferent coupling
17431 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_OFF^
17432 Do not report category afferent coupling
17436 @node Other gnatmetric Switches
17437 @subsection Other @code{gnatmetric} Switches
17440 Additional @command{gnatmetric} switches are as follows:
17443 @item ^-files @var{filename}^/FILES=@var{filename}^
17444 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17445 Take the argument source files from the specified file. This file should be an
17446 ordinary text file containing file names separated by spaces or
17447 line breaks. You can use this switch more then once in the same call to
17448 @command{gnatmetric}. You also can combine this switch with
17449 an explicit list of files.
17451 @item ^-v^/VERBOSE^
17452 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17454 @command{gnatmetric} generates version information and then
17455 a trace of sources being processed.
17457 @item ^-dv^/DEBUG_OUTPUT^
17458 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17460 @command{gnatmetric} generates various messages useful to understand what
17461 happens during the metrics computation
17464 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17468 @node Generate project-wide metrics
17469 @subsection Generate project-wide metrics
17471 In order to compute metrics on all units of a given project, you can use
17472 the @command{gnat} driver along with the @option{-P} option:
17478 If the project @code{proj} depends upon other projects, you can compute
17479 the metrics on the project closure using the @option{-U} option:
17481 gnat metric -Pproj -U
17485 Finally, if not all the units are relevant to a particular main
17486 program in the project closure, you can generate metrics for the set
17487 of units needed to create a given main program (unit closure) using
17488 the @option{-U} option followed by the name of the main unit:
17490 gnat metric -Pproj -U main
17494 @c ***********************************
17495 @node File Name Krunching Using gnatkr
17496 @chapter File Name Krunching Using @code{gnatkr}
17500 This chapter discusses the method used by the compiler to shorten
17501 the default file names chosen for Ada units so that they do not
17502 exceed the maximum length permitted. It also describes the
17503 @code{gnatkr} utility that can be used to determine the result of
17504 applying this shortening.
17508 * Krunching Method::
17509 * Examples of gnatkr Usage::
17513 @section About @code{gnatkr}
17516 The default file naming rule in GNAT
17517 is that the file name must be derived from
17518 the unit name. The exact default rule is as follows:
17521 Take the unit name and replace all dots by hyphens.
17523 If such a replacement occurs in the
17524 second character position of a name, and the first character is
17525 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17526 then replace the dot by the character
17527 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17528 instead of a minus.
17530 The reason for this exception is to avoid clashes
17531 with the standard names for children of System, Ada, Interfaces,
17532 and GNAT, which use the prefixes
17533 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17536 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17537 switch of the compiler activates a ``krunching''
17538 circuit that limits file names to nn characters (where nn is a decimal
17539 integer). For example, using OpenVMS,
17540 where the maximum file name length is
17541 39, the value of nn is usually set to 39, but if you want to generate
17542 a set of files that would be usable if ported to a system with some
17543 different maximum file length, then a different value can be specified.
17544 The default value of 39 for OpenVMS need not be specified.
17546 The @code{gnatkr} utility can be used to determine the krunched name for
17547 a given file, when krunched to a specified maximum length.
17550 @section Using @code{gnatkr}
17553 The @code{gnatkr} command has the form
17557 $ gnatkr @var{name} @ovar{length}
17563 $ gnatkr @var{name} /COUNT=nn
17568 @var{name} is the uncrunched file name, derived from the name of the unit
17569 in the standard manner described in the previous section (i.e., in particular
17570 all dots are replaced by hyphens). The file name may or may not have an
17571 extension (defined as a suffix of the form period followed by arbitrary
17572 characters other than period). If an extension is present then it will
17573 be preserved in the output. For example, when krunching @file{hellofile.ads}
17574 to eight characters, the result will be hellofil.ads.
17576 Note: for compatibility with previous versions of @code{gnatkr} dots may
17577 appear in the name instead of hyphens, but the last dot will always be
17578 taken as the start of an extension. So if @code{gnatkr} is given an argument
17579 such as @file{Hello.World.adb} it will be treated exactly as if the first
17580 period had been a hyphen, and for example krunching to eight characters
17581 gives the result @file{hellworl.adb}.
17583 Note that the result is always all lower case (except on OpenVMS where it is
17584 all upper case). Characters of the other case are folded as required.
17586 @var{length} represents the length of the krunched name. The default
17587 when no argument is given is ^8^39^ characters. A length of zero stands for
17588 unlimited, in other words do not chop except for system files where the
17589 implied crunching length is always eight characters.
17592 The output is the krunched name. The output has an extension only if the
17593 original argument was a file name with an extension.
17595 @node Krunching Method
17596 @section Krunching Method
17599 The initial file name is determined by the name of the unit that the file
17600 contains. The name is formed by taking the full expanded name of the
17601 unit and replacing the separating dots with hyphens and
17602 using ^lowercase^uppercase^
17603 for all letters, except that a hyphen in the second character position is
17604 replaced by a ^tilde^dollar sign^ if the first character is
17605 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17606 The extension is @code{.ads} for a
17607 spec and @code{.adb} for a body.
17608 Krunching does not affect the extension, but the file name is shortened to
17609 the specified length by following these rules:
17613 The name is divided into segments separated by hyphens, tildes or
17614 underscores and all hyphens, tildes, and underscores are
17615 eliminated. If this leaves the name short enough, we are done.
17618 If the name is too long, the longest segment is located (left-most
17619 if there are two of equal length), and shortened by dropping
17620 its last character. This is repeated until the name is short enough.
17622 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17623 to fit the name into 8 characters as required by some operating systems.
17626 our-strings-wide_fixed 22
17627 our strings wide fixed 19
17628 our string wide fixed 18
17629 our strin wide fixed 17
17630 our stri wide fixed 16
17631 our stri wide fixe 15
17632 our str wide fixe 14
17633 our str wid fixe 13
17639 Final file name: oustwifi.adb
17643 The file names for all predefined units are always krunched to eight
17644 characters. The krunching of these predefined units uses the following
17645 special prefix replacements:
17649 replaced by @file{^a^A^-}
17652 replaced by @file{^g^G^-}
17655 replaced by @file{^i^I^-}
17658 replaced by @file{^s^S^-}
17661 These system files have a hyphen in the second character position. That
17662 is why normal user files replace such a character with a
17663 ^tilde^dollar sign^, to
17664 avoid confusion with system file names.
17666 As an example of this special rule, consider
17667 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17670 ada-strings-wide_fixed 22
17671 a- strings wide fixed 18
17672 a- string wide fixed 17
17673 a- strin wide fixed 16
17674 a- stri wide fixed 15
17675 a- stri wide fixe 14
17676 a- str wide fixe 13
17682 Final file name: a-stwifi.adb
17686 Of course no file shortening algorithm can guarantee uniqueness over all
17687 possible unit names, and if file name krunching is used then it is your
17688 responsibility to ensure that no name clashes occur. The utility
17689 program @code{gnatkr} is supplied for conveniently determining the
17690 krunched name of a file.
17692 @node Examples of gnatkr Usage
17693 @section Examples of @code{gnatkr} Usage
17700 $ gnatkr very_long_unit_name.ads --> velounna.ads
17701 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17702 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17703 $ gnatkr grandparent-parent-child --> grparchi
17705 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17706 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17709 @node Preprocessing Using gnatprep
17710 @chapter Preprocessing Using @code{gnatprep}
17714 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17716 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17717 special GNAT features.
17718 For further discussion of conditional compilation in general, see
17719 @ref{Conditional Compilation}.
17722 * Preprocessing Symbols::
17724 * Switches for gnatprep::
17725 * Form of Definitions File::
17726 * Form of Input Text for gnatprep::
17729 @node Preprocessing Symbols
17730 @section Preprocessing Symbols
17733 Preprocessing symbols are defined in definition files and referred to in
17734 sources to be preprocessed. A Preprocessing symbol is an identifier, following
17735 normal Ada (case-insensitive) rules for its syntax, with the restriction that
17736 all characters need to be in the ASCII set (no accented letters).
17738 @node Using gnatprep
17739 @section Using @code{gnatprep}
17742 To call @code{gnatprep} use
17745 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
17752 is an optional sequence of switches as described in the next section.
17755 is the full name of the input file, which is an Ada source
17756 file containing preprocessor directives.
17759 is the full name of the output file, which is an Ada source
17760 in standard Ada form. When used with GNAT, this file name will
17761 normally have an ads or adb suffix.
17764 is the full name of a text file containing definitions of
17765 preprocessing symbols to be referenced by the preprocessor. This argument is
17766 optional, and can be replaced by the use of the @option{-D} switch.
17770 @node Switches for gnatprep
17771 @section Switches for @code{gnatprep}
17776 @item ^-b^/BLANK_LINES^
17777 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17778 Causes both preprocessor lines and the lines deleted by
17779 preprocessing to be replaced by blank lines in the output source file,
17780 preserving line numbers in the output file.
17782 @item ^-c^/COMMENTS^
17783 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17784 Causes both preprocessor lines and the lines deleted
17785 by preprocessing to be retained in the output source as comments marked
17786 with the special string @code{"--! "}. This option will result in line numbers
17787 being preserved in the output file.
17789 @item ^-C^/REPLACE_IN_COMMENTS^
17790 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17791 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17792 If this option is specified, then comments are scanned and any $symbol
17793 substitutions performed as in program text. This is particularly useful
17794 when structured comments are used (e.g., when writing programs in the
17795 SPARK dialect of Ada). Note that this switch is not available when
17796 doing integrated preprocessing (it would be useless in this context
17797 since comments are ignored by the compiler in any case).
17799 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17800 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17801 Defines a new preprocessing symbol, associated with value. If no value is given
17802 on the command line, then symbol is considered to be @code{True}. This switch
17803 can be used in place of a definition file.
17807 @cindex @option{/REMOVE} (@command{gnatprep})
17808 This is the default setting which causes lines deleted by preprocessing
17809 to be entirely removed from the output file.
17812 @item ^-r^/REFERENCE^
17813 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17814 Causes a @code{Source_Reference} pragma to be generated that
17815 references the original input file, so that error messages will use
17816 the file name of this original file. The use of this switch implies
17817 that preprocessor lines are not to be removed from the file, so its
17818 use will force @option{^-b^/BLANK_LINES^} mode if
17819 @option{^-c^/COMMENTS^}
17820 has not been specified explicitly.
17822 Note that if the file to be preprocessed contains multiple units, then
17823 it will be necessary to @code{gnatchop} the output file from
17824 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17825 in the preprocessed file, it will be respected by
17826 @code{gnatchop ^-r^/REFERENCE^}
17827 so that the final chopped files will correctly refer to the original
17828 input source file for @code{gnatprep}.
17830 @item ^-s^/SYMBOLS^
17831 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17832 Causes a sorted list of symbol names and values to be
17833 listed on the standard output file.
17835 @item ^-u^/UNDEFINED^
17836 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17837 Causes undefined symbols to be treated as having the value FALSE in the context
17838 of a preprocessor test. In the absence of this option, an undefined symbol in
17839 a @code{#if} or @code{#elsif} test will be treated as an error.
17845 Note: if neither @option{-b} nor @option{-c} is present,
17846 then preprocessor lines and
17847 deleted lines are completely removed from the output, unless -r is
17848 specified, in which case -b is assumed.
17851 @node Form of Definitions File
17852 @section Form of Definitions File
17855 The definitions file contains lines of the form
17862 where symbol is a preprocessing symbol, and value is one of the following:
17866 Empty, corresponding to a null substitution
17868 A string literal using normal Ada syntax
17870 Any sequence of characters from the set
17871 (letters, digits, period, underline).
17875 Comment lines may also appear in the definitions file, starting with
17876 the usual @code{--},
17877 and comments may be added to the definitions lines.
17879 @node Form of Input Text for gnatprep
17880 @section Form of Input Text for @code{gnatprep}
17883 The input text may contain preprocessor conditional inclusion lines,
17884 as well as general symbol substitution sequences.
17886 The preprocessor conditional inclusion commands have the form
17891 #if @i{expression} @r{[}then@r{]}
17893 #elsif @i{expression} @r{[}then@r{]}
17895 #elsif @i{expression} @r{[}then@r{]}
17906 In this example, @i{expression} is defined by the following grammar:
17908 @i{expression} ::= <symbol>
17909 @i{expression} ::= <symbol> = "<value>"
17910 @i{expression} ::= <symbol> = <symbol>
17911 @i{expression} ::= <symbol> 'Defined
17912 @i{expression} ::= not @i{expression}
17913 @i{expression} ::= @i{expression} and @i{expression}
17914 @i{expression} ::= @i{expression} or @i{expression}
17915 @i{expression} ::= @i{expression} and then @i{expression}
17916 @i{expression} ::= @i{expression} or else @i{expression}
17917 @i{expression} ::= ( @i{expression} )
17920 The following restriction exists: it is not allowed to have "and" or "or"
17921 following "not" in the same expression without parentheses. For example, this
17928 This should be one of the following:
17936 For the first test (@i{expression} ::= <symbol>) the symbol must have
17937 either the value true or false, that is to say the right-hand of the
17938 symbol definition must be one of the (case-insensitive) literals
17939 @code{True} or @code{False}. If the value is true, then the
17940 corresponding lines are included, and if the value is false, they are
17943 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17944 the symbol has been defined in the definition file or by a @option{-D}
17945 switch on the command line. Otherwise, the test is false.
17947 The equality tests are case insensitive, as are all the preprocessor lines.
17949 If the symbol referenced is not defined in the symbol definitions file,
17950 then the effect depends on whether or not switch @option{-u}
17951 is specified. If so, then the symbol is treated as if it had the value
17952 false and the test fails. If this switch is not specified, then
17953 it is an error to reference an undefined symbol. It is also an error to
17954 reference a symbol that is defined with a value other than @code{True}
17957 The use of the @code{not} operator inverts the sense of this logical test.
17958 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17959 operators, without parentheses. For example, "if not X or Y then" is not
17960 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17962 The @code{then} keyword is optional as shown
17964 The @code{#} must be the first non-blank character on a line, but
17965 otherwise the format is free form. Spaces or tabs may appear between
17966 the @code{#} and the keyword. The keywords and the symbols are case
17967 insensitive as in normal Ada code. Comments may be used on a
17968 preprocessor line, but other than that, no other tokens may appear on a
17969 preprocessor line. Any number of @code{elsif} clauses can be present,
17970 including none at all. The @code{else} is optional, as in Ada.
17972 The @code{#} marking the start of a preprocessor line must be the first
17973 non-blank character on the line, i.e., it must be preceded only by
17974 spaces or horizontal tabs.
17976 Symbol substitution outside of preprocessor lines is obtained by using
17984 anywhere within a source line, except in a comment or within a
17985 string literal. The identifier
17986 following the @code{$} must match one of the symbols defined in the symbol
17987 definition file, and the result is to substitute the value of the
17988 symbol in place of @code{$symbol} in the output file.
17990 Note that although the substitution of strings within a string literal
17991 is not possible, it is possible to have a symbol whose defined value is
17992 a string literal. So instead of setting XYZ to @code{hello} and writing:
17995 Header : String := "$XYZ";
17999 you should set XYZ to @code{"hello"} and write:
18002 Header : String := $XYZ;
18006 and then the substitution will occur as desired.
18009 @node The GNAT Run-Time Library Builder gnatlbr
18010 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18012 @cindex Library builder
18015 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18016 supplied configuration pragmas.
18019 * Running gnatlbr::
18020 * Switches for gnatlbr::
18021 * Examples of gnatlbr Usage::
18024 @node Running gnatlbr
18025 @section Running @code{gnatlbr}
18028 The @code{gnatlbr} command has the form
18031 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18034 @node Switches for gnatlbr
18035 @section Switches for @code{gnatlbr}
18038 @code{gnatlbr} recognizes the following switches:
18042 @item /CREATE=directory
18043 @cindex @code{/CREATE} (@code{gnatlbr})
18044 Create the new run-time library in the specified directory.
18046 @item /SET=directory
18047 @cindex @code{/SET} (@code{gnatlbr})
18048 Make the library in the specified directory the current run-time library.
18050 @item /DELETE=directory
18051 @cindex @code{/DELETE} (@code{gnatlbr})
18052 Delete the run-time library in the specified directory.
18055 @cindex @code{/CONFIG} (@code{gnatlbr})
18056 With /CREATE: Use the configuration pragmas in the specified file when
18057 building the library.
18059 With /SET: Use the configuration pragmas in the specified file when
18064 @node Examples of gnatlbr Usage
18065 @section Example of @code{gnatlbr} Usage
18068 Contents of VAXFLOAT.ADC:
18069 pragma Float_Representation (VAX_Float);
18071 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18073 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18078 @node The GNAT Library Browser gnatls
18079 @chapter The GNAT Library Browser @code{gnatls}
18081 @cindex Library browser
18084 @code{gnatls} is a tool that outputs information about compiled
18085 units. It gives the relationship between objects, unit names and source
18086 files. It can also be used to check the source dependencies of a unit
18087 as well as various characteristics.
18089 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18090 driver (see @ref{The GNAT Driver and Project Files}).
18094 * Switches for gnatls::
18095 * Examples of gnatls Usage::
18098 @node Running gnatls
18099 @section Running @code{gnatls}
18102 The @code{gnatls} command has the form
18105 $ gnatls switches @var{object_or_ali_file}
18109 The main argument is the list of object or @file{ali} files
18110 (@pxref{The Ada Library Information Files})
18111 for which information is requested.
18113 In normal mode, without additional option, @code{gnatls} produces a
18114 four-column listing. Each line represents information for a specific
18115 object. The first column gives the full path of the object, the second
18116 column gives the name of the principal unit in this object, the third
18117 column gives the status of the source and the fourth column gives the
18118 full path of the source representing this unit.
18119 Here is a simple example of use:
18123 ^./^[]^demo1.o demo1 DIF demo1.adb
18124 ^./^[]^demo2.o demo2 OK demo2.adb
18125 ^./^[]^hello.o h1 OK hello.adb
18126 ^./^[]^instr-child.o instr.child MOK instr-child.adb
18127 ^./^[]^instr.o instr OK instr.adb
18128 ^./^[]^tef.o tef DIF tef.adb
18129 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
18130 ^./^[]^tgef.o tgef DIF tgef.adb
18134 The first line can be interpreted as follows: the main unit which is
18136 object file @file{demo1.o} is demo1, whose main source is in
18137 @file{demo1.adb}. Furthermore, the version of the source used for the
18138 compilation of demo1 has been modified (DIF). Each source file has a status
18139 qualifier which can be:
18142 @item OK (unchanged)
18143 The version of the source file used for the compilation of the
18144 specified unit corresponds exactly to the actual source file.
18146 @item MOK (slightly modified)
18147 The version of the source file used for the compilation of the
18148 specified unit differs from the actual source file but not enough to
18149 require recompilation. If you use gnatmake with the qualifier
18150 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18151 MOK will not be recompiled.
18153 @item DIF (modified)
18154 No version of the source found on the path corresponds to the source
18155 used to build this object.
18157 @item ??? (file not found)
18158 No source file was found for this unit.
18160 @item HID (hidden, unchanged version not first on PATH)
18161 The version of the source that corresponds exactly to the source used
18162 for compilation has been found on the path but it is hidden by another
18163 version of the same source that has been modified.
18167 @node Switches for gnatls
18168 @section Switches for @code{gnatls}
18171 @code{gnatls} recognizes the following switches:
18175 @cindex @option{--version} @command{gnatls}
18176 Display Copyright and version, then exit disregarding all other options.
18179 @cindex @option{--help} @command{gnatls}
18180 If @option{--version} was not used, display usage, then exit disregarding
18183 @item ^-a^/ALL_UNITS^
18184 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18185 Consider all units, including those of the predefined Ada library.
18186 Especially useful with @option{^-d^/DEPENDENCIES^}.
18188 @item ^-d^/DEPENDENCIES^
18189 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18190 List sources from which specified units depend on.
18192 @item ^-h^/OUTPUT=OPTIONS^
18193 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18194 Output the list of options.
18196 @item ^-o^/OUTPUT=OBJECTS^
18197 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18198 Only output information about object files.
18200 @item ^-s^/OUTPUT=SOURCES^
18201 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18202 Only output information about source files.
18204 @item ^-u^/OUTPUT=UNITS^
18205 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18206 Only output information about compilation units.
18208 @item ^-files^/FILES^=@var{file}
18209 @cindex @option{^-files^/FILES^} (@code{gnatls})
18210 Take as arguments the files listed in text file @var{file}.
18211 Text file @var{file} may contain empty lines that are ignored.
18212 Each nonempty line should contain the name of an existing file.
18213 Several such switches may be specified simultaneously.
18215 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18216 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18217 @itemx ^-I^/SEARCH=^@var{dir}
18218 @itemx ^-I-^/NOCURRENT_DIRECTORY^
18220 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18221 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18222 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18223 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18224 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18225 flags (@pxref{Switches for gnatmake}).
18227 @item --RTS=@var{rts-path}
18228 @cindex @option{--RTS} (@code{gnatls})
18229 Specifies the default location of the runtime library. Same meaning as the
18230 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18232 @item ^-v^/OUTPUT=VERBOSE^
18233 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18234 Verbose mode. Output the complete source, object and project paths. Do not use
18235 the default column layout but instead use long format giving as much as
18236 information possible on each requested units, including special
18237 characteristics such as:
18240 @item Preelaborable
18241 The unit is preelaborable in the Ada sense.
18244 No elaboration code has been produced by the compiler for this unit.
18247 The unit is pure in the Ada sense.
18249 @item Elaborate_Body
18250 The unit contains a pragma Elaborate_Body.
18253 The unit contains a pragma Remote_Types.
18255 @item Shared_Passive
18256 The unit contains a pragma Shared_Passive.
18259 This unit is part of the predefined environment and cannot be modified
18262 @item Remote_Call_Interface
18263 The unit contains a pragma Remote_Call_Interface.
18269 @node Examples of gnatls Usage
18270 @section Example of @code{gnatls} Usage
18274 Example of using the verbose switch. Note how the source and
18275 object paths are affected by the -I switch.
18278 $ gnatls -v -I.. demo1.o
18280 GNATLS 5.03w (20041123-34)
18281 Copyright 1997-2004 Free Software Foundation, Inc.
18283 Source Search Path:
18284 <Current_Directory>
18286 /home/comar/local/adainclude/
18288 Object Search Path:
18289 <Current_Directory>
18291 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18293 Project Search Path:
18294 <Current_Directory>
18295 /home/comar/local/lib/gnat/
18300 Kind => subprogram body
18301 Flags => No_Elab_Code
18302 Source => demo1.adb modified
18306 The following is an example of use of the dependency list.
18307 Note the use of the -s switch
18308 which gives a straight list of source files. This can be useful for
18309 building specialized scripts.
18312 $ gnatls -d demo2.o
18313 ./demo2.o demo2 OK demo2.adb
18319 $ gnatls -d -s -a demo1.o
18321 /home/comar/local/adainclude/ada.ads
18322 /home/comar/local/adainclude/a-finali.ads
18323 /home/comar/local/adainclude/a-filico.ads
18324 /home/comar/local/adainclude/a-stream.ads
18325 /home/comar/local/adainclude/a-tags.ads
18328 /home/comar/local/adainclude/gnat.ads
18329 /home/comar/local/adainclude/g-io.ads
18331 /home/comar/local/adainclude/system.ads
18332 /home/comar/local/adainclude/s-exctab.ads
18333 /home/comar/local/adainclude/s-finimp.ads
18334 /home/comar/local/adainclude/s-finroo.ads
18335 /home/comar/local/adainclude/s-secsta.ads
18336 /home/comar/local/adainclude/s-stalib.ads
18337 /home/comar/local/adainclude/s-stoele.ads
18338 /home/comar/local/adainclude/s-stratt.ads
18339 /home/comar/local/adainclude/s-tasoli.ads
18340 /home/comar/local/adainclude/s-unstyp.ads
18341 /home/comar/local/adainclude/unchconv.ads
18347 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18349 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18350 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18351 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18352 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18353 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18357 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18358 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18360 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18361 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18362 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18363 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18364 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18365 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18366 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18367 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18368 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18369 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18370 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18374 @node Cleaning Up Using gnatclean
18375 @chapter Cleaning Up Using @code{gnatclean}
18377 @cindex Cleaning tool
18380 @code{gnatclean} is a tool that allows the deletion of files produced by the
18381 compiler, binder and linker, including ALI files, object files, tree files,
18382 expanded source files, library files, interface copy source files, binder
18383 generated files and executable files.
18386 * Running gnatclean::
18387 * Switches for gnatclean::
18388 @c * Examples of gnatclean Usage::
18391 @node Running gnatclean
18392 @section Running @code{gnatclean}
18395 The @code{gnatclean} command has the form:
18398 $ gnatclean switches @var{names}
18402 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18403 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18404 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18407 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18408 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18409 the linker. In informative-only mode, specified by switch
18410 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18411 normal mode is listed, but no file is actually deleted.
18413 @node Switches for gnatclean
18414 @section Switches for @code{gnatclean}
18417 @code{gnatclean} recognizes the following switches:
18421 @cindex @option{--version} @command{gnatclean}
18422 Display Copyright and version, then exit disregarding all other options.
18425 @cindex @option{--help} @command{gnatclean}
18426 If @option{--version} was not used, display usage, then exit disregarding
18429 @item ^-c^/COMPILER_FILES_ONLY^
18430 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18431 Only attempt to delete the files produced by the compiler, not those produced
18432 by the binder or the linker. The files that are not to be deleted are library
18433 files, interface copy files, binder generated files and executable files.
18435 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18436 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18437 Indicate that ALI and object files should normally be found in directory
18440 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18441 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18442 When using project files, if some errors or warnings are detected during
18443 parsing and verbose mode is not in effect (no use of switch
18444 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18445 file, rather than its simple file name.
18448 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18449 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18451 @item ^-n^/NODELETE^
18452 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18453 Informative-only mode. Do not delete any files. Output the list of the files
18454 that would have been deleted if this switch was not specified.
18456 @item ^-P^/PROJECT_FILE=^@var{project}
18457 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18458 Use project file @var{project}. Only one such switch can be used.
18459 When cleaning a project file, the files produced by the compilation of the
18460 immediate sources or inherited sources of the project files are to be
18461 deleted. This is not depending on the presence or not of executable names
18462 on the command line.
18465 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18466 Quiet output. If there are no errors, do not output anything, except in
18467 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18468 (switch ^-n^/NODELETE^).
18470 @item ^-r^/RECURSIVE^
18471 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18472 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18473 clean all imported and extended project files, recursively. If this switch
18474 is not specified, only the files related to the main project file are to be
18475 deleted. This switch has no effect if no project file is specified.
18477 @item ^-v^/VERBOSE^
18478 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18481 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18482 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18483 Indicates the verbosity of the parsing of GNAT project files.
18484 @xref{Switches Related to Project Files}.
18486 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18487 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18488 Indicates that external variable @var{name} has the value @var{value}.
18489 The Project Manager will use this value for occurrences of
18490 @code{external(name)} when parsing the project file.
18491 @xref{Switches Related to Project Files}.
18493 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18494 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18495 When searching for ALI and object files, look in directory
18498 @item ^-I^/SEARCH=^@var{dir}
18499 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18500 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18502 @item ^-I-^/NOCURRENT_DIRECTORY^
18503 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18504 @cindex Source files, suppressing search
18505 Do not look for ALI or object files in the directory
18506 where @code{gnatclean} was invoked.
18510 @c @node Examples of gnatclean Usage
18511 @c @section Examples of @code{gnatclean} Usage
18514 @node GNAT and Libraries
18515 @chapter GNAT and Libraries
18516 @cindex Library, building, installing, using
18519 This chapter describes how to build and use libraries with GNAT, and also shows
18520 how to recompile the GNAT run-time library. You should be familiar with the
18521 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18525 * Introduction to Libraries in GNAT::
18526 * General Ada Libraries::
18527 * Stand-alone Ada Libraries::
18528 * Rebuilding the GNAT Run-Time Library::
18531 @node Introduction to Libraries in GNAT
18532 @section Introduction to Libraries in GNAT
18535 A library is, conceptually, a collection of objects which does not have its
18536 own main thread of execution, but rather provides certain services to the
18537 applications that use it. A library can be either statically linked with the
18538 application, in which case its code is directly included in the application,
18539 or, on platforms that support it, be dynamically linked, in which case
18540 its code is shared by all applications making use of this library.
18542 GNAT supports both types of libraries.
18543 In the static case, the compiled code can be provided in different ways. The
18544 simplest approach is to provide directly the set of objects resulting from
18545 compilation of the library source files. Alternatively, you can group the
18546 objects into an archive using whatever commands are provided by the operating
18547 system. For the latter case, the objects are grouped into a shared library.
18549 In the GNAT environment, a library has three types of components:
18555 @xref{The Ada Library Information Files}.
18557 Object files, an archive or a shared library.
18561 A GNAT library may expose all its source files, which is useful for
18562 documentation purposes. Alternatively, it may expose only the units needed by
18563 an external user to make use of the library. That is to say, the specs
18564 reflecting the library services along with all the units needed to compile
18565 those specs, which can include generic bodies or any body implementing an
18566 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18567 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18569 All compilation units comprising an application, including those in a library,
18570 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18571 computes the elaboration order from the @file{ALI} files and this is why they
18572 constitute a mandatory part of GNAT libraries. Except in the case of
18573 @emph{stand-alone libraries}, where a specific library elaboration routine is
18574 produced independently of the application(s) using the library.
18576 @node General Ada Libraries
18577 @section General Ada Libraries
18580 * Building a library::
18581 * Installing a library::
18582 * Using a library::
18585 @node Building a library
18586 @subsection Building a library
18589 The easiest way to build a library is to use the Project Manager,
18590 which supports a special type of project called a @emph{Library Project}
18591 (@pxref{Library Projects}).
18593 A project is considered a library project, when two project-level attributes
18594 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18595 control different aspects of library configuration, additional optional
18596 project-level attributes can be specified:
18599 This attribute controls whether the library is to be static or dynamic
18601 @item Library_Version
18602 This attribute specifies the library version; this value is used
18603 during dynamic linking of shared libraries to determine if the currently
18604 installed versions of the binaries are compatible.
18606 @item Library_Options
18608 These attributes specify additional low-level options to be used during
18609 library generation, and redefine the actual application used to generate
18614 The GNAT Project Manager takes full care of the library maintenance task,
18615 including recompilation of the source files for which objects do not exist
18616 or are not up to date, assembly of the library archive, and installation of
18617 the library (i.e., copying associated source, object and @file{ALI} files
18618 to the specified location).
18620 Here is a simple library project file:
18621 @smallexample @c ada
18623 for Source_Dirs use ("src1", "src2");
18624 for Object_Dir use "obj";
18625 for Library_Name use "mylib";
18626 for Library_Dir use "lib";
18627 for Library_Kind use "dynamic";
18632 and the compilation command to build and install the library:
18634 @smallexample @c ada
18635 $ gnatmake -Pmy_lib
18639 It is not entirely trivial to perform manually all the steps required to
18640 produce a library. We recommend that you use the GNAT Project Manager
18641 for this task. In special cases where this is not desired, the necessary
18642 steps are discussed below.
18644 There are various possibilities for compiling the units that make up the
18645 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18646 with a conventional script. For simple libraries, it is also possible to create
18647 a dummy main program which depends upon all the packages that comprise the
18648 interface of the library. This dummy main program can then be given to
18649 @command{gnatmake}, which will ensure that all necessary objects are built.
18651 After this task is accomplished, you should follow the standard procedure
18652 of the underlying operating system to produce the static or shared library.
18654 Here is an example of such a dummy program:
18655 @smallexample @c ada
18657 with My_Lib.Service1;
18658 with My_Lib.Service2;
18659 with My_Lib.Service3;
18660 procedure My_Lib_Dummy is
18668 Here are the generic commands that will build an archive or a shared library.
18671 # compiling the library
18672 $ gnatmake -c my_lib_dummy.adb
18674 # we don't need the dummy object itself
18675 $ rm my_lib_dummy.o my_lib_dummy.ali
18677 # create an archive with the remaining objects
18678 $ ar rc libmy_lib.a *.o
18679 # some systems may require "ranlib" to be run as well
18681 # or create a shared library
18682 $ gcc -shared -o libmy_lib.so *.o
18683 # some systems may require the code to have been compiled with -fPIC
18685 # remove the object files that are now in the library
18688 # Make the ALI files read-only so that gnatmake will not try to
18689 # regenerate the objects that are in the library
18694 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
18695 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
18696 be accessed by the directive @option{-l@var{xxx}} at link time.
18698 @node Installing a library
18699 @subsection Installing a library
18700 @cindex @code{ADA_PROJECT_PATH}
18703 If you use project files, library installation is part of the library build
18704 process. Thus no further action is needed in order to make use of the
18705 libraries that are built as part of the general application build. A usable
18706 version of the library is installed in the directory specified by the
18707 @code{Library_Dir} attribute of the library project file.
18709 You may want to install a library in a context different from where the library
18710 is built. This situation arises with third party suppliers, who may want
18711 to distribute a library in binary form where the user is not expected to be
18712 able to recompile the library. The simplest option in this case is to provide
18713 a project file slightly different from the one used to build the library, by
18714 using the @code{externally_built} attribute. For instance, the project
18715 file used to build the library in the previous section can be changed into the
18716 following one when the library is installed:
18718 @smallexample @c projectfile
18720 for Source_Dirs use ("src1", "src2");
18721 for Library_Name use "mylib";
18722 for Library_Dir use "lib";
18723 for Library_Kind use "dynamic";
18724 for Externally_Built use "true";
18729 This project file assumes that the directories @file{src1},
18730 @file{src2}, and @file{lib} exist in
18731 the directory containing the project file. The @code{externally_built}
18732 attribute makes it clear to the GNAT builder that it should not attempt to
18733 recompile any of the units from this library. It allows the library provider to
18734 restrict the source set to the minimum necessary for clients to make use of the
18735 library as described in the first section of this chapter. It is the
18736 responsibility of the library provider to install the necessary sources, ALI
18737 files and libraries in the directories mentioned in the project file. For
18738 convenience, the user's library project file should be installed in a location
18739 that will be searched automatically by the GNAT
18740 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
18741 environment variable (@pxref{Importing Projects}), and also the default GNAT
18742 library location that can be queried with @command{gnatls -v} and is usually of
18743 the form $gnat_install_root/lib/gnat.
18745 When project files are not an option, it is also possible, but not recommended,
18746 to install the library so that the sources needed to use the library are on the
18747 Ada source path and the ALI files & libraries be on the Ada Object path (see
18748 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18749 administrator can place general-purpose libraries in the default compiler
18750 paths, by specifying the libraries' location in the configuration files
18751 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18752 must be located in the GNAT installation tree at the same place as the gcc spec
18753 file. The location of the gcc spec file can be determined as follows:
18759 The configuration files mentioned above have a simple format: each line
18760 must contain one unique directory name.
18761 Those names are added to the corresponding path
18762 in their order of appearance in the file. The names can be either absolute
18763 or relative; in the latter case, they are relative to where theses files
18766 The files @file{ada_source_path} and @file{ada_object_path} might not be
18768 GNAT installation, in which case, GNAT will look for its run-time library in
18769 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18770 objects and @file{ALI} files). When the files exist, the compiler does not
18771 look in @file{adainclude} and @file{adalib}, and thus the
18772 @file{ada_source_path} file
18773 must contain the location for the GNAT run-time sources (which can simply
18774 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18775 contain the location for the GNAT run-time objects (which can simply
18778 You can also specify a new default path to the run-time library at compilation
18779 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18780 the run-time library you want your program to be compiled with. This switch is
18781 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18782 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18784 It is possible to install a library before or after the standard GNAT
18785 library, by reordering the lines in the configuration files. In general, a
18786 library must be installed before the GNAT library if it redefines
18789 @node Using a library
18790 @subsection Using a library
18792 @noindent Once again, the project facility greatly simplifies the use of
18793 libraries. In this context, using a library is just a matter of adding a
18794 @code{with} clause in the user project. For instance, to make use of the
18795 library @code{My_Lib} shown in examples in earlier sections, you can
18798 @smallexample @c projectfile
18805 Even if you have a third-party, non-Ada library, you can still use GNAT's
18806 Project Manager facility to provide a wrapper for it. For example, the
18807 following project, when @code{with}ed by your main project, will link with the
18808 third-party library @file{liba.a}:
18810 @smallexample @c projectfile
18813 for Externally_Built use "true";
18814 for Source_Files use ();
18815 for Library_Dir use "lib";
18816 for Library_Name use "a";
18817 for Library_Kind use "static";
18821 This is an alternative to the use of @code{pragma Linker_Options}. It is
18822 especially interesting in the context of systems with several interdependent
18823 static libraries where finding a proper linker order is not easy and best be
18824 left to the tools having visibility over project dependence information.
18827 In order to use an Ada library manually, you need to make sure that this
18828 library is on both your source and object path
18829 (see @ref{Search Paths and the Run-Time Library (RTL)}
18830 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18831 in an archive or a shared library, you need to specify the desired
18832 library at link time.
18834 For example, you can use the library @file{mylib} installed in
18835 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18838 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18843 This can be expressed more simply:
18848 when the following conditions are met:
18851 @file{/dir/my_lib_src} has been added by the user to the environment
18852 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
18853 @file{ada_source_path}
18855 @file{/dir/my_lib_obj} has been added by the user to the environment
18856 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
18857 @file{ada_object_path}
18859 a pragma @code{Linker_Options} has been added to one of the sources.
18862 @smallexample @c ada
18863 pragma Linker_Options ("-lmy_lib");
18867 @node Stand-alone Ada Libraries
18868 @section Stand-alone Ada Libraries
18869 @cindex Stand-alone library, building, using
18872 * Introduction to Stand-alone Libraries::
18873 * Building a Stand-alone Library::
18874 * Creating a Stand-alone Library to be used in a non-Ada context::
18875 * Restrictions in Stand-alone Libraries::
18878 @node Introduction to Stand-alone Libraries
18879 @subsection Introduction to Stand-alone Libraries
18882 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18884 elaborate the Ada units that are included in the library. In contrast with
18885 an ordinary library, which consists of all sources, objects and @file{ALI}
18887 library, a SAL may specify a restricted subset of compilation units
18888 to serve as a library interface. In this case, the fully
18889 self-sufficient set of files will normally consist of an objects
18890 archive, the sources of interface units' specs, and the @file{ALI}
18891 files of interface units.
18892 If an interface spec contains a generic unit or an inlined subprogram,
18894 source must also be provided; if the units that must be provided in the source
18895 form depend on other units, the source and @file{ALI} files of those must
18898 The main purpose of a SAL is to minimize the recompilation overhead of client
18899 applications when a new version of the library is installed. Specifically,
18900 if the interface sources have not changed, client applications do not need to
18901 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18902 version, controlled by @code{Library_Version} attribute, is not changed,
18903 then the clients do not need to be relinked.
18905 SALs also allow the library providers to minimize the amount of library source
18906 text exposed to the clients. Such ``information hiding'' might be useful or
18907 necessary for various reasons.
18909 Stand-alone libraries are also well suited to be used in an executable whose
18910 main routine is not written in Ada.
18912 @node Building a Stand-alone Library
18913 @subsection Building a Stand-alone Library
18916 GNAT's Project facility provides a simple way of building and installing
18917 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18918 To be a Stand-alone Library Project, in addition to the two attributes
18919 that make a project a Library Project (@code{Library_Name} and
18920 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18921 @code{Library_Interface} must be defined. For example:
18923 @smallexample @c projectfile
18925 for Library_Dir use "lib_dir";
18926 for Library_Name use "dummy";
18927 for Library_Interface use ("int1", "int1.child");
18932 Attribute @code{Library_Interface} has a non-empty string list value,
18933 each string in the list designating a unit contained in an immediate source
18934 of the project file.
18936 When a Stand-alone Library is built, first the binder is invoked to build
18937 a package whose name depends on the library name
18938 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18939 This binder-generated package includes initialization and
18940 finalization procedures whose
18941 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18943 above). The object corresponding to this package is included in the library.
18945 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18946 calling of these procedures if a static SAL is built, or if a shared SAL
18948 with the project-level attribute @code{Library_Auto_Init} set to
18951 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18952 (those that are listed in attribute @code{Library_Interface}) are copied to
18953 the Library Directory. As a consequence, only the Interface Units may be
18954 imported from Ada units outside of the library. If other units are imported,
18955 the binding phase will fail.
18957 The attribute @code{Library_Src_Dir} may be specified for a
18958 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18959 single string value. Its value must be the path (absolute or relative to the
18960 project directory) of an existing directory. This directory cannot be the
18961 object directory or one of the source directories, but it can be the same as
18962 the library directory. The sources of the Interface
18963 Units of the library that are needed by an Ada client of the library will be
18964 copied to the designated directory, called the Interface Copy directory.
18965 These sources include the specs of the Interface Units, but they may also
18966 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18967 are used, or when there is a generic unit in the spec. Before the sources
18968 are copied to the Interface Copy directory, an attempt is made to delete all
18969 files in the Interface Copy directory.
18971 Building stand-alone libraries by hand is somewhat tedious, but for those
18972 occasions when it is necessary here are the steps that you need to perform:
18975 Compile all library sources.
18978 Invoke the binder with the switch @option{-n} (No Ada main program),
18979 with all the @file{ALI} files of the interfaces, and
18980 with the switch @option{-L} to give specific names to the @code{init}
18981 and @code{final} procedures. For example:
18983 gnatbind -n int1.ali int2.ali -Lsal1
18987 Compile the binder generated file:
18993 Link the dynamic library with all the necessary object files,
18994 indicating to the linker the names of the @code{init} (and possibly
18995 @code{final}) procedures for automatic initialization (and finalization).
18996 The built library should be placed in a directory different from
18997 the object directory.
19000 Copy the @code{ALI} files of the interface to the library directory,
19001 add in this copy an indication that it is an interface to a SAL
19002 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19003 with letter ``P'') and make the modified copy of the @file{ALI} file
19008 Using SALs is not different from using other libraries
19009 (see @ref{Using a library}).
19011 @node Creating a Stand-alone Library to be used in a non-Ada context
19012 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19015 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19018 The only extra step required is to ensure that library interface subprograms
19019 are compatible with the main program, by means of @code{pragma Export}
19020 or @code{pragma Convention}.
19022 Here is an example of simple library interface for use with C main program:
19024 @smallexample @c ada
19025 package Interface is
19027 procedure Do_Something;
19028 pragma Export (C, Do_Something, "do_something");
19030 procedure Do_Something_Else;
19031 pragma Export (C, Do_Something_Else, "do_something_else");
19037 On the foreign language side, you must provide a ``foreign'' view of the
19038 library interface; remember that it should contain elaboration routines in
19039 addition to interface subprograms.
19041 The example below shows the content of @code{mylib_interface.h} (note
19042 that there is no rule for the naming of this file, any name can be used)
19044 /* the library elaboration procedure */
19045 extern void mylibinit (void);
19047 /* the library finalization procedure */
19048 extern void mylibfinal (void);
19050 /* the interface exported by the library */
19051 extern void do_something (void);
19052 extern void do_something_else (void);
19056 Libraries built as explained above can be used from any program, provided
19057 that the elaboration procedures (named @code{mylibinit} in the previous
19058 example) are called before the library services are used. Any number of
19059 libraries can be used simultaneously, as long as the elaboration
19060 procedure of each library is called.
19062 Below is an example of a C program that uses the @code{mylib} library.
19065 #include "mylib_interface.h"
19070 /* First, elaborate the library before using it */
19073 /* Main program, using the library exported entities */
19075 do_something_else ();
19077 /* Library finalization at the end of the program */
19084 Note that invoking any library finalization procedure generated by
19085 @code{gnatbind} shuts down the Ada run-time environment.
19087 finalization of all Ada libraries must be performed at the end of the program.
19088 No call to these libraries or to the Ada run-time library should be made
19089 after the finalization phase.
19091 @node Restrictions in Stand-alone Libraries
19092 @subsection Restrictions in Stand-alone Libraries
19095 The pragmas listed below should be used with caution inside libraries,
19096 as they can create incompatibilities with other Ada libraries:
19098 @item pragma @code{Locking_Policy}
19099 @item pragma @code{Queuing_Policy}
19100 @item pragma @code{Task_Dispatching_Policy}
19101 @item pragma @code{Unreserve_All_Interrupts}
19105 When using a library that contains such pragmas, the user must make sure
19106 that all libraries use the same pragmas with the same values. Otherwise,
19107 @code{Program_Error} will
19108 be raised during the elaboration of the conflicting
19109 libraries. The usage of these pragmas and its consequences for the user
19110 should therefore be well documented.
19112 Similarly, the traceback in the exception occurrence mechanism should be
19113 enabled or disabled in a consistent manner across all libraries.
19114 Otherwise, Program_Error will be raised during the elaboration of the
19115 conflicting libraries.
19117 If the @code{Version} or @code{Body_Version}
19118 attributes are used inside a library, then you need to
19119 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19120 libraries, so that version identifiers can be properly computed.
19121 In practice these attributes are rarely used, so this is unlikely
19122 to be a consideration.
19124 @node Rebuilding the GNAT Run-Time Library
19125 @section Rebuilding the GNAT Run-Time Library
19126 @cindex GNAT Run-Time Library, rebuilding
19127 @cindex Building the GNAT Run-Time Library
19128 @cindex Rebuilding the GNAT Run-Time Library
19129 @cindex Run-Time Library, rebuilding
19132 It may be useful to recompile the GNAT library in various contexts, the
19133 most important one being the use of partition-wide configuration pragmas
19134 such as @code{Normalize_Scalars}. A special Makefile called
19135 @code{Makefile.adalib} is provided to that effect and can be found in
19136 the directory containing the GNAT library. The location of this
19137 directory depends on the way the GNAT environment has been installed and can
19138 be determined by means of the command:
19145 The last entry in the object search path usually contains the
19146 gnat library. This Makefile contains its own documentation and in
19147 particular the set of instructions needed to rebuild a new library and
19150 @node Using the GNU make Utility
19151 @chapter Using the GNU @code{make} Utility
19155 This chapter offers some examples of makefiles that solve specific
19156 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19157 make, make, GNU @code{make}}), nor does it try to replace the
19158 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19160 All the examples in this section are specific to the GNU version of
19161 make. Although @command{make} is a standard utility, and the basic language
19162 is the same, these examples use some advanced features found only in
19166 * Using gnatmake in a Makefile::
19167 * Automatically Creating a List of Directories::
19168 * Generating the Command Line Switches::
19169 * Overcoming Command Line Length Limits::
19172 @node Using gnatmake in a Makefile
19173 @section Using gnatmake in a Makefile
19178 Complex project organizations can be handled in a very powerful way by
19179 using GNU make combined with gnatmake. For instance, here is a Makefile
19180 which allows you to build each subsystem of a big project into a separate
19181 shared library. Such a makefile allows you to significantly reduce the link
19182 time of very big applications while maintaining full coherence at
19183 each step of the build process.
19185 The list of dependencies are handled automatically by
19186 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19187 the appropriate directories.
19189 Note that you should also read the example on how to automatically
19190 create the list of directories
19191 (@pxref{Automatically Creating a List of Directories})
19192 which might help you in case your project has a lot of subdirectories.
19197 @font@heightrm=cmr8
19200 ## This Makefile is intended to be used with the following directory
19202 ## - The sources are split into a series of csc (computer software components)
19203 ## Each of these csc is put in its own directory.
19204 ## Their name are referenced by the directory names.
19205 ## They will be compiled into shared library (although this would also work
19206 ## with static libraries
19207 ## - The main program (and possibly other packages that do not belong to any
19208 ## csc is put in the top level directory (where the Makefile is).
19209 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
19210 ## \_ second_csc (sources) __ lib (will contain the library)
19212 ## Although this Makefile is build for shared library, it is easy to modify
19213 ## to build partial link objects instead (modify the lines with -shared and
19216 ## With this makefile, you can change any file in the system or add any new
19217 ## file, and everything will be recompiled correctly (only the relevant shared
19218 ## objects will be recompiled, and the main program will be re-linked).
19220 # The list of computer software component for your project. This might be
19221 # generated automatically.
19224 # Name of the main program (no extension)
19227 # If we need to build objects with -fPIC, uncomment the following line
19230 # The following variable should give the directory containing libgnat.so
19231 # You can get this directory through 'gnatls -v'. This is usually the last
19232 # directory in the Object_Path.
19235 # The directories for the libraries
19236 # (This macro expands the list of CSC to the list of shared libraries, you
19237 # could simply use the expanded form:
19238 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19239 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19241 $@{MAIN@}: objects $@{LIB_DIR@}
19242 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19243 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19246 # recompile the sources
19247 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19249 # Note: In a future version of GNAT, the following commands will be simplified
19250 # by a new tool, gnatmlib
19252 mkdir -p $@{dir $@@ @}
19253 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19254 cd $@{dir $@@ @} && cp -f ../*.ali .
19256 # The dependencies for the modules
19257 # Note that we have to force the expansion of *.o, since in some cases
19258 # make won't be able to do it itself.
19259 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19260 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19261 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19263 # Make sure all of the shared libraries are in the path before starting the
19266 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19269 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19270 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19271 $@{RM@} $@{CSC_LIST:%=%/*.o@}
19272 $@{RM@} *.o *.ali $@{MAIN@}
19275 @node Automatically Creating a List of Directories
19276 @section Automatically Creating a List of Directories
19279 In most makefiles, you will have to specify a list of directories, and
19280 store it in a variable. For small projects, it is often easier to
19281 specify each of them by hand, since you then have full control over what
19282 is the proper order for these directories, which ones should be
19285 However, in larger projects, which might involve hundreds of
19286 subdirectories, it might be more convenient to generate this list
19289 The example below presents two methods. The first one, although less
19290 general, gives you more control over the list. It involves wildcard
19291 characters, that are automatically expanded by @command{make}. Its
19292 shortcoming is that you need to explicitly specify some of the
19293 organization of your project, such as for instance the directory tree
19294 depth, whether some directories are found in a separate tree, @enddots{}
19296 The second method is the most general one. It requires an external
19297 program, called @command{find}, which is standard on all Unix systems. All
19298 the directories found under a given root directory will be added to the
19304 @font@heightrm=cmr8
19307 # The examples below are based on the following directory hierarchy:
19308 # All the directories can contain any number of files
19309 # ROOT_DIRECTORY -> a -> aa -> aaa
19312 # -> b -> ba -> baa
19315 # This Makefile creates a variable called DIRS, that can be reused any time
19316 # you need this list (see the other examples in this section)
19318 # The root of your project's directory hierarchy
19322 # First method: specify explicitly the list of directories
19323 # This allows you to specify any subset of all the directories you need.
19326 DIRS := a/aa/ a/ab/ b/ba/
19329 # Second method: use wildcards
19330 # Note that the argument(s) to wildcard below should end with a '/'.
19331 # Since wildcards also return file names, we have to filter them out
19332 # to avoid duplicate directory names.
19333 # We thus use make's @code{dir} and @code{sort} functions.
19334 # It sets DIRs to the following value (note that the directories aaa and baa
19335 # are not given, unless you change the arguments to wildcard).
19336 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19339 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19340 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19343 # Third method: use an external program
19344 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19345 # This is the most complete command: it sets DIRs to the following value:
19346 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19349 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19353 @node Generating the Command Line Switches
19354 @section Generating the Command Line Switches
19357 Once you have created the list of directories as explained in the
19358 previous section (@pxref{Automatically Creating a List of Directories}),
19359 you can easily generate the command line arguments to pass to gnatmake.
19361 For the sake of completeness, this example assumes that the source path
19362 is not the same as the object path, and that you have two separate lists
19366 # see "Automatically creating a list of directories" to create
19371 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19372 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19375 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19378 @node Overcoming Command Line Length Limits
19379 @section Overcoming Command Line Length Limits
19382 One problem that might be encountered on big projects is that many
19383 operating systems limit the length of the command line. It is thus hard to give
19384 gnatmake the list of source and object directories.
19386 This example shows how you can set up environment variables, which will
19387 make @command{gnatmake} behave exactly as if the directories had been
19388 specified on the command line, but have a much higher length limit (or
19389 even none on most systems).
19391 It assumes that you have created a list of directories in your Makefile,
19392 using one of the methods presented in
19393 @ref{Automatically Creating a List of Directories}.
19394 For the sake of completeness, we assume that the object
19395 path (where the ALI files are found) is different from the sources patch.
19397 Note a small trick in the Makefile below: for efficiency reasons, we
19398 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19399 expanded immediately by @code{make}. This way we overcome the standard
19400 make behavior which is to expand the variables only when they are
19403 On Windows, if you are using the standard Windows command shell, you must
19404 replace colons with semicolons in the assignments to these variables.
19409 @font@heightrm=cmr8
19412 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19413 # This is the same thing as putting the -I arguments on the command line.
19414 # (the equivalent of using -aI on the command line would be to define
19415 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19416 # You can of course have different values for these variables.
19418 # Note also that we need to keep the previous values of these variables, since
19419 # they might have been set before running 'make' to specify where the GNAT
19420 # library is installed.
19422 # see "Automatically creating a list of directories" to create these
19428 space:=$@{empty@} $@{empty@}
19429 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19430 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19431 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19432 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19433 export ADA_INCLUDE_PATH
19434 export ADA_OBJECT_PATH
19441 @node Memory Management Issues
19442 @chapter Memory Management Issues
19445 This chapter describes some useful memory pools provided in the GNAT library
19446 and in particular the GNAT Debug Pool facility, which can be used to detect
19447 incorrect uses of access values (including ``dangling references'').
19449 It also describes the @command{gnatmem} tool, which can be used to track down
19454 * Some Useful Memory Pools::
19455 * The GNAT Debug Pool Facility::
19457 * The gnatmem Tool::
19461 @node Some Useful Memory Pools
19462 @section Some Useful Memory Pools
19463 @findex Memory Pool
19464 @cindex storage, pool
19467 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19468 storage pool. Allocations use the standard system call @code{malloc} while
19469 deallocations use the standard system call @code{free}. No reclamation is
19470 performed when the pool goes out of scope. For performance reasons, the
19471 standard default Ada allocators/deallocators do not use any explicit storage
19472 pools but if they did, they could use this storage pool without any change in
19473 behavior. That is why this storage pool is used when the user
19474 manages to make the default implicit allocator explicit as in this example:
19475 @smallexample @c ada
19476 type T1 is access Something;
19477 -- no Storage pool is defined for T2
19478 type T2 is access Something_Else;
19479 for T2'Storage_Pool use T1'Storage_Pool;
19480 -- the above is equivalent to
19481 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19485 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19486 pool. The allocation strategy is similar to @code{Pool_Local}'s
19487 except that the all
19488 storage allocated with this pool is reclaimed when the pool object goes out of
19489 scope. This pool provides a explicit mechanism similar to the implicit one
19490 provided by several Ada 83 compilers for allocations performed through a local
19491 access type and whose purpose was to reclaim memory when exiting the
19492 scope of a given local access. As an example, the following program does not
19493 leak memory even though it does not perform explicit deallocation:
19495 @smallexample @c ada
19496 with System.Pool_Local;
19497 procedure Pooloc1 is
19498 procedure Internal is
19499 type A is access Integer;
19500 X : System.Pool_Local.Unbounded_Reclaim_Pool;
19501 for A'Storage_Pool use X;
19504 for I in 1 .. 50 loop
19509 for I in 1 .. 100 loop
19516 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19517 @code{Storage_Size} is specified for an access type.
19518 The whole storage for the pool is
19519 allocated at once, usually on the stack at the point where the access type is
19520 elaborated. It is automatically reclaimed when exiting the scope where the
19521 access type is defined. This package is not intended to be used directly by the
19522 user and it is implicitly used for each such declaration:
19524 @smallexample @c ada
19525 type T1 is access Something;
19526 for T1'Storage_Size use 10_000;
19529 @node The GNAT Debug Pool Facility
19530 @section The GNAT Debug Pool Facility
19532 @cindex storage, pool, memory corruption
19535 The use of unchecked deallocation and unchecked conversion can easily
19536 lead to incorrect memory references. The problems generated by such
19537 references are usually difficult to tackle because the symptoms can be
19538 very remote from the origin of the problem. In such cases, it is
19539 very helpful to detect the problem as early as possible. This is the
19540 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19542 In order to use the GNAT specific debugging pool, the user must
19543 associate a debug pool object with each of the access types that may be
19544 related to suspected memory problems. See Ada Reference Manual 13.11.
19545 @smallexample @c ada
19546 type Ptr is access Some_Type;
19547 Pool : GNAT.Debug_Pools.Debug_Pool;
19548 for Ptr'Storage_Pool use Pool;
19552 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19553 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19554 allow the user to redefine allocation and deallocation strategies. They
19555 also provide a checkpoint for each dereference, through the use of
19556 the primitive operation @code{Dereference} which is implicitly called at
19557 each dereference of an access value.
19559 Once an access type has been associated with a debug pool, operations on
19560 values of the type may raise four distinct exceptions,
19561 which correspond to four potential kinds of memory corruption:
19564 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19566 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19568 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19570 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19574 For types associated with a Debug_Pool, dynamic allocation is performed using
19575 the standard GNAT allocation routine. References to all allocated chunks of
19576 memory are kept in an internal dictionary. Several deallocation strategies are
19577 provided, whereupon the user can choose to release the memory to the system,
19578 keep it allocated for further invalid access checks, or fill it with an easily
19579 recognizable pattern for debug sessions. The memory pattern is the old IBM
19580 hexadecimal convention: @code{16#DEADBEEF#}.
19582 See the documentation in the file g-debpoo.ads for more information on the
19583 various strategies.
19585 Upon each dereference, a check is made that the access value denotes a
19586 properly allocated memory location. Here is a complete example of use of
19587 @code{Debug_Pools}, that includes typical instances of memory corruption:
19588 @smallexample @c ada
19592 with Gnat.Io; use Gnat.Io;
19593 with Unchecked_Deallocation;
19594 with Unchecked_Conversion;
19595 with GNAT.Debug_Pools;
19596 with System.Storage_Elements;
19597 with Ada.Exceptions; use Ada.Exceptions;
19598 procedure Debug_Pool_Test is
19600 type T is access Integer;
19601 type U is access all T;
19603 P : GNAT.Debug_Pools.Debug_Pool;
19604 for T'Storage_Pool use P;
19606 procedure Free is new Unchecked_Deallocation (Integer, T);
19607 function UC is new Unchecked_Conversion (U, T);
19610 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19620 Put_Line (Integer'Image(B.all));
19622 when E : others => Put_Line ("raised: " & Exception_Name (E));
19627 when E : others => Put_Line ("raised: " & Exception_Name (E));
19631 Put_Line (Integer'Image(B.all));
19633 when E : others => Put_Line ("raised: " & Exception_Name (E));
19638 when E : others => Put_Line ("raised: " & Exception_Name (E));
19641 end Debug_Pool_Test;
19645 The debug pool mechanism provides the following precise diagnostics on the
19646 execution of this erroneous program:
19649 Total allocated bytes : 0
19650 Total deallocated bytes : 0
19651 Current Water Mark: 0
19655 Total allocated bytes : 8
19656 Total deallocated bytes : 0
19657 Current Water Mark: 8
19660 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19661 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19662 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19663 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19665 Total allocated bytes : 8
19666 Total deallocated bytes : 4
19667 Current Water Mark: 4
19672 @node The gnatmem Tool
19673 @section The @command{gnatmem} Tool
19677 The @code{gnatmem} utility monitors dynamic allocation and
19678 deallocation activity in a program, and displays information about
19679 incorrect deallocations and possible sources of memory leaks.
19680 It provides three type of information:
19683 General information concerning memory management, such as the total
19684 number of allocations and deallocations, the amount of allocated
19685 memory and the high water mark, i.e.@: the largest amount of allocated
19686 memory in the course of program execution.
19689 Backtraces for all incorrect deallocations, that is to say deallocations
19690 which do not correspond to a valid allocation.
19693 Information on each allocation that is potentially the origin of a memory
19698 * Running gnatmem::
19699 * Switches for gnatmem::
19700 * Example of gnatmem Usage::
19703 @node Running gnatmem
19704 @subsection Running @code{gnatmem}
19707 @code{gnatmem} makes use of the output created by the special version of
19708 allocation and deallocation routines that record call information. This
19709 allows to obtain accurate dynamic memory usage history at a minimal cost to
19710 the execution speed. Note however, that @code{gnatmem} is not supported on
19711 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19712 Solaris and Windows NT/2000/XP (x86).
19715 The @code{gnatmem} command has the form
19718 $ gnatmem @ovar{switches} user_program
19722 The program must have been linked with the instrumented version of the
19723 allocation and deallocation routines. This is done by linking with the
19724 @file{libgmem.a} library. For correct symbolic backtrace information,
19725 the user program should be compiled with debugging options
19726 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19729 $ gnatmake -g my_program -largs -lgmem
19733 As library @file{libgmem.a} contains an alternate body for package
19734 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19735 when an executable is linked with library @file{libgmem.a}. It is then not
19736 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19739 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19740 This file contains information about all allocations and deallocations
19741 performed by the program. It is produced by the instrumented allocations and
19742 deallocations routines and will be used by @code{gnatmem}.
19744 In order to produce symbolic backtrace information for allocations and
19745 deallocations performed by the GNAT run-time library, you need to use a
19746 version of that library that has been compiled with the @option{-g} switch
19747 (see @ref{Rebuilding the GNAT Run-Time Library}).
19749 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19750 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19751 @option{-i} switch, gnatmem will assume that this file can be found in the
19752 current directory. For example, after you have executed @file{my_program},
19753 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19756 $ gnatmem my_program
19760 This will produce the output with the following format:
19762 *************** debut cc
19764 $ gnatmem my_program
19768 Total number of allocations : 45
19769 Total number of deallocations : 6
19770 Final Water Mark (non freed mem) : 11.29 Kilobytes
19771 High Water Mark : 11.40 Kilobytes
19776 Allocation Root # 2
19777 -------------------
19778 Number of non freed allocations : 11
19779 Final Water Mark (non freed mem) : 1.16 Kilobytes
19780 High Water Mark : 1.27 Kilobytes
19782 my_program.adb:23 my_program.alloc
19788 The first block of output gives general information. In this case, the
19789 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19790 Unchecked_Deallocation routine occurred.
19793 Subsequent paragraphs display information on all allocation roots.
19794 An allocation root is a specific point in the execution of the program
19795 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19796 construct. This root is represented by an execution backtrace (or subprogram
19797 call stack). By default the backtrace depth for allocations roots is 1, so
19798 that a root corresponds exactly to a source location. The backtrace can
19799 be made deeper, to make the root more specific.
19801 @node Switches for gnatmem
19802 @subsection Switches for @code{gnatmem}
19805 @code{gnatmem} recognizes the following switches:
19810 @cindex @option{-q} (@code{gnatmem})
19811 Quiet. Gives the minimum output needed to identify the origin of the
19812 memory leaks. Omits statistical information.
19815 @cindex @var{N} (@code{gnatmem})
19816 N is an integer literal (usually between 1 and 10) which controls the
19817 depth of the backtraces defining allocation root. The default value for
19818 N is 1. The deeper the backtrace, the more precise the localization of
19819 the root. Note that the total number of roots can depend on this
19820 parameter. This parameter must be specified @emph{before} the name of the
19821 executable to be analyzed, to avoid ambiguity.
19824 @cindex @option{-b} (@code{gnatmem})
19825 This switch has the same effect as just depth parameter.
19827 @item -i @var{file}
19828 @cindex @option{-i} (@code{gnatmem})
19829 Do the @code{gnatmem} processing starting from @file{file}, rather than
19830 @file{gmem.out} in the current directory.
19833 @cindex @option{-m} (@code{gnatmem})
19834 This switch causes @code{gnatmem} to mask the allocation roots that have less
19835 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19836 examine even the roots that didn't result in leaks.
19839 @cindex @option{-s} (@code{gnatmem})
19840 This switch causes @code{gnatmem} to sort the allocation roots according to the
19841 specified order of sort criteria, each identified by a single letter. The
19842 currently supported criteria are @code{n, h, w} standing respectively for
19843 number of unfreed allocations, high watermark, and final watermark
19844 corresponding to a specific root. The default order is @code{nwh}.
19848 @node Example of gnatmem Usage
19849 @subsection Example of @code{gnatmem} Usage
19852 The following example shows the use of @code{gnatmem}
19853 on a simple memory-leaking program.
19854 Suppose that we have the following Ada program:
19856 @smallexample @c ada
19859 with Unchecked_Deallocation;
19860 procedure Test_Gm is
19862 type T is array (1..1000) of Integer;
19863 type Ptr is access T;
19864 procedure Free is new Unchecked_Deallocation (T, Ptr);
19867 procedure My_Alloc is
19872 procedure My_DeAlloc is
19880 for I in 1 .. 5 loop
19881 for J in I .. 5 loop
19892 The program needs to be compiled with debugging option and linked with
19893 @code{gmem} library:
19896 $ gnatmake -g test_gm -largs -lgmem
19900 Then we execute the program as usual:
19907 Then @code{gnatmem} is invoked simply with
19913 which produces the following output (result may vary on different platforms):
19918 Total number of allocations : 18
19919 Total number of deallocations : 5
19920 Final Water Mark (non freed mem) : 53.00 Kilobytes
19921 High Water Mark : 56.90 Kilobytes
19923 Allocation Root # 1
19924 -------------------
19925 Number of non freed allocations : 11
19926 Final Water Mark (non freed mem) : 42.97 Kilobytes
19927 High Water Mark : 46.88 Kilobytes
19929 test_gm.adb:11 test_gm.my_alloc
19931 Allocation Root # 2
19932 -------------------
19933 Number of non freed allocations : 1
19934 Final Water Mark (non freed mem) : 10.02 Kilobytes
19935 High Water Mark : 10.02 Kilobytes
19937 s-secsta.adb:81 system.secondary_stack.ss_init
19939 Allocation Root # 3
19940 -------------------
19941 Number of non freed allocations : 1
19942 Final Water Mark (non freed mem) : 12 Bytes
19943 High Water Mark : 12 Bytes
19945 s-secsta.adb:181 system.secondary_stack.ss_init
19949 Note that the GNAT run time contains itself a certain number of
19950 allocations that have no corresponding deallocation,
19951 as shown here for root #2 and root
19952 #3. This is a normal behavior when the number of non-freed allocations
19953 is one, it allocates dynamic data structures that the run time needs for
19954 the complete lifetime of the program. Note also that there is only one
19955 allocation root in the user program with a single line back trace:
19956 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19957 program shows that 'My_Alloc' is called at 2 different points in the
19958 source (line 21 and line 24). If those two allocation roots need to be
19959 distinguished, the backtrace depth parameter can be used:
19962 $ gnatmem 3 test_gm
19966 which will give the following output:
19971 Total number of allocations : 18
19972 Total number of deallocations : 5
19973 Final Water Mark (non freed mem) : 53.00 Kilobytes
19974 High Water Mark : 56.90 Kilobytes
19976 Allocation Root # 1
19977 -------------------
19978 Number of non freed allocations : 10
19979 Final Water Mark (non freed mem) : 39.06 Kilobytes
19980 High Water Mark : 42.97 Kilobytes
19982 test_gm.adb:11 test_gm.my_alloc
19983 test_gm.adb:24 test_gm
19984 b_test_gm.c:52 main
19986 Allocation Root # 2
19987 -------------------
19988 Number of non freed allocations : 1
19989 Final Water Mark (non freed mem) : 10.02 Kilobytes
19990 High Water Mark : 10.02 Kilobytes
19992 s-secsta.adb:81 system.secondary_stack.ss_init
19993 s-secsta.adb:283 <system__secondary_stack___elabb>
19994 b_test_gm.c:33 adainit
19996 Allocation Root # 3
19997 -------------------
19998 Number of non freed allocations : 1
19999 Final Water Mark (non freed mem) : 3.91 Kilobytes
20000 High Water Mark : 3.91 Kilobytes
20002 test_gm.adb:11 test_gm.my_alloc
20003 test_gm.adb:21 test_gm
20004 b_test_gm.c:52 main
20006 Allocation Root # 4
20007 -------------------
20008 Number of non freed allocations : 1
20009 Final Water Mark (non freed mem) : 12 Bytes
20010 High Water Mark : 12 Bytes
20012 s-secsta.adb:181 system.secondary_stack.ss_init
20013 s-secsta.adb:283 <system__secondary_stack___elabb>
20014 b_test_gm.c:33 adainit
20018 The allocation root #1 of the first example has been split in 2 roots #1
20019 and #3 thanks to the more precise associated backtrace.
20023 @node Stack Related Facilities
20024 @chapter Stack Related Facilities
20027 This chapter describes some useful tools associated with stack
20028 checking and analysis. In
20029 particular, it deals with dynamic and static stack usage measurements.
20032 * Stack Overflow Checking::
20033 * Static Stack Usage Analysis::
20034 * Dynamic Stack Usage Analysis::
20037 @node Stack Overflow Checking
20038 @section Stack Overflow Checking
20039 @cindex Stack Overflow Checking
20040 @cindex -fstack-check
20043 For most operating systems, @command{gcc} does not perform stack overflow
20044 checking by default. This means that if the main environment task or
20045 some other task exceeds the available stack space, then unpredictable
20046 behavior will occur. Most native systems offer some level of protection by
20047 adding a guard page at the end of each task stack. This mechanism is usually
20048 not enough for dealing properly with stack overflow situations because
20049 a large local variable could ``jump'' above the guard page.
20050 Furthermore, when the
20051 guard page is hit, there may not be any space left on the stack for executing
20052 the exception propagation code. Enabling stack checking avoids
20055 To activate stack checking, compile all units with the gcc option
20056 @option{-fstack-check}. For example:
20059 gcc -c -fstack-check package1.adb
20063 Units compiled with this option will generate extra instructions to check
20064 that any use of the stack (for procedure calls or for declaring local
20065 variables in declare blocks) does not exceed the available stack space.
20066 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20068 For declared tasks, the stack size is controlled by the size
20069 given in an applicable @code{Storage_Size} pragma or by the value specified
20070 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20071 the default size as defined in the GNAT runtime otherwise.
20073 For the environment task, the stack size depends on
20074 system defaults and is unknown to the compiler. Stack checking
20075 may still work correctly if a fixed
20076 size stack is allocated, but this cannot be guaranteed.
20078 To ensure that a clean exception is signalled for stack
20079 overflow, set the environment variable
20080 @env{GNAT_STACK_LIMIT} to indicate the maximum
20081 stack area that can be used, as in:
20082 @cindex GNAT_STACK_LIMIT
20085 SET GNAT_STACK_LIMIT 1600
20089 The limit is given in kilobytes, so the above declaration would
20090 set the stack limit of the environment task to 1.6 megabytes.
20091 Note that the only purpose of this usage is to limit the amount
20092 of stack used by the environment task. If it is necessary to
20093 increase the amount of stack for the environment task, then this
20094 is an operating systems issue, and must be addressed with the
20095 appropriate operating systems commands.
20098 To have a fixed size stack in the environment task, the stack must be put
20099 in the P0 address space and its size specified. Use these switches to
20103 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20107 The quotes are required to keep case. The number after @samp{STACK=} is the
20108 size of the environmental task stack in pagelets (512 bytes). In this example
20109 the stack size is about 2 megabytes.
20112 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20113 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
20114 more details about the @option{/p0image} qualifier and the @option{stack}
20118 @node Static Stack Usage Analysis
20119 @section Static Stack Usage Analysis
20120 @cindex Static Stack Usage Analysis
20121 @cindex -fstack-usage
20124 A unit compiled with @option{-fstack-usage} will generate an extra file
20126 the maximum amount of stack used, on a per-function basis.
20127 The file has the same
20128 basename as the target object file with a @file{.su} extension.
20129 Each line of this file is made up of three fields:
20133 The name of the function.
20137 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20140 The second field corresponds to the size of the known part of the function
20143 The qualifier @code{static} means that the function frame size
20145 It usually means that all local variables have a static size.
20146 In this case, the second field is a reliable measure of the function stack
20149 The qualifier @code{dynamic} means that the function frame size is not static.
20150 It happens mainly when some local variables have a dynamic size. When this
20151 qualifier appears alone, the second field is not a reliable measure
20152 of the function stack analysis. When it is qualified with @code{bounded}, it
20153 means that the second field is a reliable maximum of the function stack
20156 @node Dynamic Stack Usage Analysis
20157 @section Dynamic Stack Usage Analysis
20160 It is possible to measure the maximum amount of stack used by a task, by
20161 adding a switch to @command{gnatbind}, as:
20164 $ gnatbind -u0 file
20168 With this option, at each task termination, its stack usage is output on
20170 It is not always convenient to output the stack usage when the program
20171 is still running. Hence, it is possible to delay this output until program
20172 termination. for a given number of tasks specified as the argument of the
20173 @option{-u} option. For instance:
20176 $ gnatbind -u100 file
20180 will buffer the stack usage information of the first 100 tasks to terminate and
20181 output this info at program termination. Results are displayed in four
20185 Index | Task Name | Stack Size | Actual Use [min - max]
20192 is a number associated with each task.
20195 is the name of the task analyzed.
20198 is the maximum size for the stack.
20201 is the measure done by the stack analyzer. In order to prevent overflow,
20202 the stack is not entirely analyzed, and it's not possible to know exactly how
20203 much has actually been used. The real amount of stack used is between the min
20209 The environment task stack, e.g., the stack that contains the main unit, is
20210 only processed when the environment variable GNAT_STACK_LIMIT is set.
20213 @c *********************************
20215 @c *********************************
20216 @node Verifying Properties Using gnatcheck
20217 @chapter Verifying Properties Using @command{gnatcheck}
20219 @cindex @command{gnatcheck}
20222 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20223 of Ada source files according to a given set of semantic rules.
20226 In order to check compliance with a given rule, @command{gnatcheck} has to
20227 semantically analyze the Ada sources.
20228 Therefore, checks can only be performed on
20229 legal Ada units. Moreover, when a unit depends semantically upon units located
20230 outside the current directory, the source search path has to be provided when
20231 calling @command{gnatcheck}, either through a specified project file or
20232 through @command{gnatcheck} switches as described below.
20234 A number of rules are predefined in @command{gnatcheck} and are described
20235 later in this chapter.
20236 You can also add new rules, by modifying the @command{gnatcheck} code and
20237 rebuilding the tool. In order to add a simple rule making some local checks,
20238 a small amount of straightforward ASIS-based programming is usually needed.
20240 Project support for @command{gnatcheck} is provided by the GNAT
20241 driver (see @ref{The GNAT Driver and Project Files}).
20243 Invoking @command{gnatcheck} on the command line has the form:
20246 $ gnatcheck @ovar{switches} @{@var{filename}@}
20247 @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20248 @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20255 @var{switches} specify the general tool options
20258 Each @var{filename} is the name (including the extension) of a source
20259 file to process. ``Wildcards'' are allowed, and
20260 the file name may contain path information.
20263 Each @var{arg_list_filename} is the name (including the extension) of a text
20264 file containing the names of the source files to process, separated by spaces
20268 @var{gcc_switches} is a list of switches for
20269 @command{gcc}. They will be passed on to all compiler invocations made by
20270 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20271 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20272 and use the @option{-gnatec} switch to set the configuration file.
20275 @var{rule_options} is a list of options for controlling a set of
20276 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20280 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20283 * Format of the Report File::
20284 * General gnatcheck Switches::
20285 * gnatcheck Rule Options::
20286 * Adding the Results of Compiler Checks to gnatcheck Output::
20287 * Project-Wide Checks::
20288 * Predefined Rules::
20291 @node Format of the Report File
20292 @section Format of the Report File
20293 @cindex Report file (for @code{gnatcheck})
20296 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20298 It also creates, in the current
20299 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
20300 contains the complete report of the last gnatcheck run. This report contains:
20302 @item a list of the Ada source files being checked,
20303 @item a list of enabled and disabled rules,
20304 @item a list of the diagnostic messages, ordered in three different ways
20305 and collected in three separate
20306 sections. Section 1 contains the raw list of diagnostic messages. It
20307 corresponds to the output going to @file{stdout}. Section 2 contains
20308 messages ordered by rules.
20309 Section 3 contains messages ordered by source files.
20312 @node General gnatcheck Switches
20313 @section General @command{gnatcheck} Switches
20316 The following switches control the general @command{gnatcheck} behavior
20320 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20322 Process all units including those with read-only ALI files such as
20323 those from GNAT Run-Time library.
20327 @cindex @option{-d} (@command{gnatcheck})
20332 @cindex @option{-dd} (@command{gnatcheck})
20334 Progress indicator mode (for use in GPS)
20337 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20339 List the predefined and user-defined rules. For more details see
20340 @ref{Predefined Rules}.
20342 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20344 Use full source locations references in the report file. For a construct from
20345 a generic instantiation a full source location is a chain from the location
20346 of this construct in the generic unit to the place where this unit is
20349 @cindex @option{^-m^/DIAGNOSIS_LIMIT^} (@command{gnatcheck})
20350 @item ^-m@i{nnn}^/DIAGNOSIS_LIMIT=@i{nnn}^
20351 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20352 the default value is 500. Zero means that there is no limitation on
20353 the number of diagnostic messages to be printed into Stdout.
20355 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20357 Quiet mode. All the diagnoses about rule violations are placed in the
20358 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20360 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20362 Short format of the report file (no version information, no list of applied
20363 rules, no list of checked sources is included)
20365 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20366 @item ^-s1^/COMPILER_STYLE^
20367 Include the compiler-style section in the report file
20369 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20370 @item ^-s2^/BY_RULES^
20371 Include the section containing diagnoses ordered by rules in the report file
20373 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20374 @item ^-s3^/BY_FILES_BY_RULES^
20375 Include the section containing diagnoses ordered by files and then by rules
20378 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20379 @item ^-v^/VERBOSE^
20380 Verbose mode; @command{gnatcheck} generates version information and then
20381 a trace of sources being processed.
20386 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20387 @option{^-s2^/BY_RULES^} or
20388 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20389 then the @command{gnatcheck} report file will only contain sections
20390 explicitly denoted by these options.
20392 @node gnatcheck Rule Options
20393 @section @command{gnatcheck} Rule Options
20396 The following options control the processing performed by
20397 @command{gnatcheck}.
20400 @cindex @option{+ALL} (@command{gnatcheck})
20402 Turn all the rule checks ON.
20404 @cindex @option{-ALL} (@command{gnatcheck})
20406 Turn all the rule checks OFF.
20408 @cindex @option{+R} (@command{gnatcheck})
20409 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20410 Turn on the check for a specified rule with the specified parameter, if any.
20411 @var{rule_id} must be the identifier of one of the currently implemented rules
20412 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20413 are not case-sensitive. The @var{param} item must
20414 be a string representing a valid parameter(s) for the specified rule.
20415 If it contains any space characters then this string must be enclosed in
20418 @cindex @option{-R} (@command{gnatcheck})
20419 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20420 Turn off the check for a specified rule with the specified parameter, if any.
20422 @cindex @option{-from} (@command{gnatcheck})
20423 @item -from=@var{rule_option_filename}
20424 Read the rule options from the text file @var{rule_option_filename}, referred as
20425 ``rule file'' below.
20430 The default behavior is that all the rule checks are disabled.
20432 A rule file is a text file containing a set of rule options.
20433 @cindex Rule file (for @code{gnatcheck})
20434 The file may contain empty lines and Ada-style comments (comment
20435 lines and end-of-line comments). The rule file has free format; that is,
20436 you do not have to start a new rule option on a new line.
20438 A rule file may contain other @option{-from=@var{rule_option_filename}}
20439 options, each such option being replaced with the content of the
20440 corresponding rule file during the rule files processing. In case a
20441 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20442 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20443 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20444 the processing of rule files is interrupted and a part of their content
20448 @node Adding the Results of Compiler Checks to gnatcheck Output
20449 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20452 The @command{gnatcheck} tool can include in the generated diagnostic messages
20454 the report file the results of the checks performed by the compiler. Though
20455 disabled by default, this effect may be obtained by using @option{+R} with
20456 the following rule identifiers and parameters:
20460 To record restrictions violations (that are performed by the compiler if the
20461 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20463 @code{Restrictions} with the same parameters as pragma
20464 @code{Restrictions} or @code{Restriction_Warnings}.
20467 To record compiler style checks(@pxref{Style Checking}), use the rule named
20468 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20469 which enables all the standard style checks that corresponds to @option{-gnatyy}
20470 GNAT style check option, or a string that has exactly the same
20471 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20472 @code{Style_Checks} (for further information about this pragma,
20473 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20476 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20477 named @code{Warnings} with a parameter that is a valid
20478 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20479 (for further information about this pragma, @pxref{Pragma Warnings,,,
20480 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20481 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20482 all the specific warnings, but not suppresses the warning mode,
20483 and 'e' parameter, corresponding to @option{-gnatwe} that means
20484 "treat warnings as errors", does not have any effect.
20488 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20489 option with the corresponding restriction name as a parameter. @code{-R} is
20490 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20491 warnings and style checks, use the corresponding warning and style options.
20493 @node Project-Wide Checks
20494 @section Project-Wide Checks
20495 @cindex Project-wide checks (for @command{gnatcheck})
20498 In order to perform checks on all units of a given project, you can use
20499 the GNAT driver along with the @option{-P} option:
20501 gnat check -Pproj -rules -from=my_rules
20505 If the project @code{proj} depends upon other projects, you can perform
20506 checks on the project closure using the @option{-U} option:
20508 gnat check -Pproj -U -rules -from=my_rules
20512 Finally, if not all the units are relevant to a particular main
20513 program in the project closure, you can perform checks for the set
20514 of units needed to create a given main program (unit closure) using
20515 the @option{-U} option followed by the name of the main unit:
20517 gnat check -Pproj -U main -rules -from=my_rules
20521 @node Predefined Rules
20522 @section Predefined Rules
20523 @cindex Predefined rules (for @command{gnatcheck})
20526 @c (Jan 2007) Since the global rules are still under development and are not
20527 @c documented, there is no point in explaining the difference between
20528 @c global and local rules
20530 A rule in @command{gnatcheck} is either local or global.
20531 A @emph{local rule} is a rule that applies to a well-defined section
20532 of a program and that can be checked by analyzing only this section.
20533 A @emph{global rule} requires analysis of some global properties of the
20534 whole program (mostly related to the program call graph).
20535 As of @value{NOW}, the implementation of global rules should be
20536 considered to be at a preliminary stage. You can use the
20537 @option{+GLOBAL} option to enable all the global rules, and the
20538 @option{-GLOBAL} rule option to disable all the global rules.
20540 All the global rules in the list below are
20541 so indicated by marking them ``GLOBAL''.
20542 This +GLOBAL and -GLOBAL options are not
20543 included in the list of gnatcheck options above, because at the moment they
20544 are considered as a temporary debug options.
20546 @command{gnatcheck} performs rule checks for generic
20547 instances only for global rules. This limitation may be relaxed in a later
20552 The following subsections document the rules implemented in
20553 @command{gnatcheck}.
20554 The subsection title is the same as the rule identifier, which may be
20555 used as a parameter of the @option{+R} or @option{-R} options.
20559 * Abstract_Type_Declarations::
20560 * Anonymous_Arrays::
20561 * Anonymous_Subtypes::
20563 * Boolean_Relational_Operators::
20565 * Ceiling_Violations::
20567 * Controlled_Type_Declarations::
20568 * Declarations_In_Blocks::
20569 * Default_Parameters::
20570 * Discriminated_Records::
20571 * Enumeration_Ranges_In_CASE_Statements::
20572 * Exceptions_As_Control_Flow::
20573 * EXIT_Statements_With_No_Loop_Name::
20574 * Expanded_Loop_Exit_Names::
20575 * Explicit_Full_Discrete_Ranges::
20576 * Float_Equality_Checks::
20577 * Forbidden_Pragmas::
20578 * Function_Style_Procedures::
20579 * Generics_In_Subprograms::
20580 * GOTO_Statements::
20581 * Implicit_IN_Mode_Parameters::
20582 * Implicit_SMALL_For_Fixed_Point_Types::
20583 * Improperly_Located_Instantiations::
20584 * Improper_Returns::
20585 * Library_Level_Subprograms::
20588 * Improperly_Called_Protected_Entries::
20591 * Misnamed_Identifiers::
20592 * Multiple_Entries_In_Protected_Definitions::
20594 * Non_Qualified_Aggregates::
20595 * Non_Short_Circuit_Operators::
20596 * Non_SPARK_Attributes::
20597 * Non_Tagged_Derived_Types::
20598 * Non_Visible_Exceptions::
20599 * Numeric_Literals::
20600 * OTHERS_In_Aggregates::
20601 * OTHERS_In_CASE_Statements::
20602 * OTHERS_In_Exception_Handlers::
20603 * Outer_Loop_Exits::
20604 * Overloaded_Operators::
20605 * Overly_Nested_Control_Structures::
20606 * Parameters_Out_Of_Order::
20607 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20608 * Positional_Actuals_For_Defaulted_Parameters::
20609 * Positional_Components::
20610 * Positional_Generic_Parameters::
20611 * Positional_Parameters::
20612 * Predefined_Numeric_Types::
20613 * Raising_External_Exceptions::
20614 * Raising_Predefined_Exceptions::
20615 * Separate_Numeric_Error_Handlers::
20618 * Side_Effect_Functions::
20621 * Unassigned_OUT_Parameters::
20622 * Uncommented_BEGIN_In_Package_Bodies::
20623 * Unconstrained_Array_Returns::
20624 * Universal_Ranges::
20625 * Unnamed_Blocks_And_Loops::
20627 * Unused_Subprograms::
20629 * USE_PACKAGE_Clauses::
20630 * Volatile_Objects_Without_Address_Clauses::
20634 @node Abstract_Type_Declarations
20635 @subsection @code{Abstract_Type_Declarations}
20636 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20639 Flag all declarations of abstract types. For an abstract private
20640 type, both the private and full type declarations are flagged.
20642 This rule has no parameters.
20645 @node Anonymous_Arrays
20646 @subsection @code{Anonymous_Arrays}
20647 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20650 Flag all anonymous array type definitions (by Ada semantics these can only
20651 occur in object declarations).
20653 This rule has no parameters.
20655 @node Anonymous_Subtypes
20656 @subsection @code{Anonymous_Subtypes}
20657 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20660 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20661 any instance of a subtype indication with a constraint, other than one
20662 that occurs immediately within a subtype declaration. Any use of a range
20663 other than as a constraint used immediately within a subtype declaration
20664 is considered as an anonymous subtype.
20666 An effect of this rule is that @code{for} loops such as the following are
20667 flagged (since @code{1..N} is formally a ``range''):
20669 @smallexample @c ada
20670 for I in 1 .. N loop
20676 Declaring an explicit subtype solves the problem:
20678 @smallexample @c ada
20679 subtype S is Integer range 1..N;
20687 This rule has no parameters.
20690 @subsection @code{Blocks}
20691 @cindex @code{Blocks} rule (for @command{gnatcheck})
20694 Flag each block statement.
20696 This rule has no parameters.
20698 @node Boolean_Relational_Operators
20699 @subsection @code{Boolean_Relational_Operators}
20700 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20703 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20704 ``>='', ``='' and ``/='') for the predefined Boolean type.
20705 (This rule is useful in enforcing the SPARK language restrictions.)
20707 Calls to predefined relational operators of any type derived from
20708 @code{Standard.Boolean} are not detected. Calls to user-defined functions
20709 with these designators, and uses of operators that are renamings
20710 of the predefined relational operators for @code{Standard.Boolean},
20711 are likewise not detected.
20713 This rule has no parameters.
20716 @node Ceiling_Violations
20717 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20718 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20721 Flag invocations of a protected operation by a task whose priority exceeds
20722 the protected object's ceiling.
20724 As of @value{NOW}, this rule has the following limitations:
20729 We consider only pragmas Priority and Interrupt_Priority as means to define
20730 a task/protected operation priority. We do not consider the effect of using
20731 Ada.Dynamic_Priorities.Set_Priority procedure;
20734 We consider only base task priorities, and no priority inheritance. That is,
20735 we do not make a difference between calls issued during task activation and
20736 execution of the sequence of statements from task body;
20739 Any situation when the priority of protected operation caller is set by a
20740 dynamic expression (that is, the corresponding Priority or
20741 Interrupt_Priority pragma has a non-static expression as an argument) we
20742 treat as a priority inconsistency (and, therefore, detect this situation).
20746 At the moment the notion of the main subprogram is not implemented in
20747 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20748 if this subprogram can be a main subprogram of a partition) changes the
20749 priority of an environment task. So if we have more then one such pragma in
20750 the set of processed sources, the pragma that is processed last, defines the
20751 priority of an environment task.
20753 This rule has no parameters.
20756 @node Controlled_Type_Declarations
20757 @subsection @code{Controlled_Type_Declarations}
20758 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20761 Flag all declarations of controlled types. A declaration of a private type
20762 is flagged if its full declaration declares a controlled type. A declaration
20763 of a derived type is flagged if its ancestor type is controlled. Subtype
20764 declarations are not checked. A declaration of a type that itself is not a
20765 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20766 component is not checked.
20768 This rule has no parameters.
20772 @node Declarations_In_Blocks
20773 @subsection @code{Declarations_In_Blocks}
20774 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20777 Flag all block statements containing local declarations. A @code{declare}
20778 block with an empty @i{declarative_part} or with a @i{declarative part}
20779 containing only pragmas and/or @code{use} clauses is not flagged.
20781 This rule has no parameters.
20784 @node Default_Parameters
20785 @subsection @code{Default_Parameters}
20786 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20789 Flag all default expressions for subprogram parameters. Parameter
20790 declarations of formal and generic subprograms are also checked.
20792 This rule has no parameters.
20795 @node Discriminated_Records
20796 @subsection @code{Discriminated_Records}
20797 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20800 Flag all declarations of record types with discriminants. Only the
20801 declarations of record and record extension types are checked. Incomplete,
20802 formal, private, derived and private extension type declarations are not
20803 checked. Task and protected type declarations also are not checked.
20805 This rule has no parameters.
20808 @node Enumeration_Ranges_In_CASE_Statements
20809 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20810 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20813 Flag each use of a range of enumeration literals as a choice in a
20814 @code{case} statement.
20815 All forms for specifying a range (explicit ranges
20816 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20817 An enumeration range is
20818 flagged even if contains exactly one enumeration value or no values at all. A
20819 type derived from an enumeration type is considered as an enumeration type.
20821 This rule helps prevent maintenance problems arising from adding an
20822 enumeration value to a type and having it implicitly handled by an existing
20823 @code{case} statement with an enumeration range that includes the new literal.
20825 This rule has no parameters.
20828 @node Exceptions_As_Control_Flow
20829 @subsection @code{Exceptions_As_Control_Flow}
20830 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20833 Flag each place where an exception is explicitly raised and handled in the
20834 same subprogram body. A @code{raise} statement in an exception handler,
20835 package body, task body or entry body is not flagged.
20837 The rule has no parameters.
20839 @node EXIT_Statements_With_No_Loop_Name
20840 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20841 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20844 Flag each @code{exit} statement that does not specify the name of the loop
20847 The rule has no parameters.
20850 @node Expanded_Loop_Exit_Names
20851 @subsection @code{Expanded_Loop_Exit_Names}
20852 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20855 Flag all expanded loop names in @code{exit} statements.
20857 This rule has no parameters.
20859 @node Explicit_Full_Discrete_Ranges
20860 @subsection @code{Explicit_Full_Discrete_Ranges}
20861 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20864 Flag each discrete range that has the form @code{A'First .. A'Last}.
20866 This rule has no parameters.
20868 @node Float_Equality_Checks
20869 @subsection @code{Float_Equality_Checks}
20870 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20873 Flag all calls to the predefined equality operations for floating-point types.
20874 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20875 User-defined equality operations are not flagged, nor are ``@code{=}''
20876 and ``@code{/=}'' operations for fixed-point types.
20878 This rule has no parameters.
20881 @node Forbidden_Pragmas
20882 @subsection @code{Forbidden_Pragmas}
20883 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20886 Flag each use of the specified pragmas. The pragmas to be detected
20887 are named in the rule's parameters.
20889 This rule has the following parameters:
20892 @item For the @option{+R} option
20895 @item @emph{Pragma_Name}
20896 Adds the specified pragma to the set of pragmas to be
20897 checked and sets the checks for all the specified pragmas
20898 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20899 does not correspond to any pragma name defined in the Ada
20900 standard or to the name of a GNAT-specific pragma defined
20901 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20902 Manual}, it is treated as the name of unknown pragma.
20905 All the GNAT-specific pragmas are detected; this sets
20906 the checks for all the specified pragmas ON.
20909 All pragmas are detected; this sets the rule ON.
20912 @item For the @option{-R} option
20914 @item @emph{Pragma_Name}
20915 Removes the specified pragma from the set of pragmas to be
20916 checked without affecting checks for
20917 other pragmas. @emph{Pragma_Name} is treated as a name
20918 of a pragma. If it does not correspond to any pragma
20919 defined in the Ada standard or to any name defined in
20920 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20921 this option is treated as turning OFF detection of all unknown pragmas.
20924 Turn OFF detection of all GNAT-specific pragmas
20927 Clear the list of the pragmas to be detected and
20933 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20934 the syntax of an Ada identifier and therefore can not be considered
20935 as a pragma name, a diagnostic message is generated and the corresponding
20936 parameter is ignored.
20938 When more then one parameter is given in the same rule option, the parameters
20939 must be separated by a comma.
20941 If more then one option for this rule is specified for the @command{gnatcheck}
20942 call, a new option overrides the previous one(s).
20944 The @option{+R} option with no parameters turns the rule ON with the set of
20945 pragmas to be detected defined by the previous rule options.
20946 (By default this set is empty, so if the only option specified for the rule is
20947 @option{+RForbidden_Pragmas} (with
20948 no parameter), then the rule is enabled, but it does not detect anything).
20949 The @option{-R} option with no parameter turns the rule OFF, but it does not
20950 affect the set of pragmas to be detected.
20955 @node Function_Style_Procedures
20956 @subsection @code{Function_Style_Procedures}
20957 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20960 Flag each procedure that can be rewritten as a function. A procedure can be
20961 converted into a function if it has exactly one parameter of mode @code{out}
20962 and no parameters of mode @code{in out}. Procedure declarations,
20963 formal procedure declarations, and generic procedure declarations are always
20965 bodies and body stubs are flagged only if they do not have corresponding
20966 separate declarations. Procedure renamings and procedure instantiations are
20969 If a procedure can be rewritten as a function, but its @code{out} parameter is
20970 of a limited type, it is not flagged.
20972 Protected procedures are not flagged. Null procedures also are not flagged.
20974 This rule has no parameters.
20977 @node Generics_In_Subprograms
20978 @subsection @code{Generics_In_Subprograms}
20979 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
20982 Flag each declaration of a generic unit in a subprogram. Generic
20983 declarations in the bodies of generic subprograms are also flagged.
20984 A generic unit nested in another generic unit is not flagged.
20985 If a generic unit is
20986 declared in a local package that is declared in a subprogram body, the
20987 generic unit is flagged.
20989 This rule has no parameters.
20992 @node GOTO_Statements
20993 @subsection @code{GOTO_Statements}
20994 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
20997 Flag each occurrence of a @code{goto} statement.
20999 This rule has no parameters.
21002 @node Implicit_IN_Mode_Parameters
21003 @subsection @code{Implicit_IN_Mode_Parameters}
21004 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21007 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21008 Note that @code{access} parameters, although they technically behave
21009 like @code{in} parameters, are not flagged.
21011 This rule has no parameters.
21014 @node Implicit_SMALL_For_Fixed_Point_Types
21015 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21016 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21019 Flag each fixed point type declaration that lacks an explicit
21020 representation clause to define its @code{'Small} value.
21021 Since @code{'Small} can be defined only for ordinary fixed point types,
21022 decimal fixed point type declarations are not checked.
21024 This rule has no parameters.
21027 @node Improperly_Located_Instantiations
21028 @subsection @code{Improperly_Located_Instantiations}
21029 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21032 Flag all generic instantiations in library-level package specs
21033 (including library generic packages) and in all subprogram bodies.
21035 Instantiations in task and entry bodies are not flagged. Instantiations in the
21036 bodies of protected subprograms are flagged.
21038 This rule has no parameters.
21042 @node Improper_Returns
21043 @subsection @code{Improper_Returns}
21044 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21047 Flag each explicit @code{return} statement in procedures, and
21048 multiple @code{return} statements in functions.
21049 Diagnostic messages are generated for all @code{return} statements
21050 in a procedure (thus each procedure must be written so that it
21051 returns implicitly at the end of its statement part),
21052 and for all @code{return} statements in a function after the first one.
21053 This rule supports the stylistic convention that each subprogram
21054 should have no more than one point of normal return.
21056 This rule has no parameters.
21059 @node Library_Level_Subprograms
21060 @subsection @code{Library_Level_Subprograms}
21061 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21064 Flag all library-level subprograms (including generic subprogram instantiations).
21066 This rule has no parameters.
21069 @node Local_Packages
21070 @subsection @code{Local_Packages}
21071 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21074 Flag all local packages declared in package and generic package
21076 Local packages in bodies are not flagged.
21078 This rule has no parameters.
21081 @node Improperly_Called_Protected_Entries
21082 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21083 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21086 Flag each protected entry that can be called from more than one task.
21088 This rule has no parameters.
21092 @subsection @code{Metrics}
21093 @cindex @code{Metrics} rule (for @command{gnatcheck})
21096 There is a set of checks based on computing a metric value and comparing the
21097 result with the specified upper (or lower, depending on a specific metric)
21098 value specified for a given metric. A construct is flagged if a given metric
21099 is applicable (can be computed) for it and the computed value is greater
21100 then (lover then) the specified upper (lower) bound.
21102 The name of any metric-based rule consists of the prefix @code{Metrics_}
21103 followed by the name of the corresponding metric (see the table below).
21104 For @option{+R} option, each metric-based rule has a numeric parameter
21105 specifying the bound (integer or real, depending on a metric), @option{-R}
21106 option for metric rules does not have a parameter.
21108 The following table shows the metric names for that the corresponding
21109 metrics-based checks are supported by gnatcheck, including the
21110 constraint that must be satisfied by the bound that is specified for the check
21111 and what bound - upper (U) or lower (L) - should be specified.
21113 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21115 @headitem Check Name @tab Description @tab Bounds Value
21118 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21120 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21121 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21122 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21123 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21127 The meaning and the computed values for all these metrics are exactly
21128 the same as for the corresponding metrics in @command{gnatmetric}.
21130 @emph{Example:} the rule
21132 +RMetrics_Cyclomatic_Complexity : 7
21135 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21137 To turn OFF the check for cyclomatic complexity metric, use the following option:
21139 -RMetrics_Cyclomatic_Complexity
21142 @node Misnamed_Identifiers
21143 @subsection @code{Misnamed_Identifiers}
21144 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21147 Flag the declaration of each identifier that does not have a suffix
21148 corresponding to the kind of entity being declared.
21149 The following declarations are checked:
21156 constant declarations (but not number declarations)
21159 package renaming declarations (but not generic package renaming
21164 This rule may have parameters. When used without parameters, the rule enforces
21165 the following checks:
21169 type-defining names end with @code{_T}, unless the type is an access type,
21170 in which case the suffix must be @code{_A}
21172 constant names end with @code{_C}
21174 names defining package renamings end with @code{_R}
21178 For a private or incomplete type declaration the following checks are
21179 made for the defining name suffix:
21183 For an incomplete type declaration: if the corresponding full type
21184 declaration is available, the defining identifier from the full type
21185 declaration is checked, but the defining identifier from the incomplete type
21186 declaration is not; otherwise the defining identifier from the incomplete
21187 type declaration is checked against the suffix specified for type
21191 For a private type declaration (including private extensions), the defining
21192 identifier from the private type declaration is checked against the type
21193 suffix (even if the corresponding full declaration is an access type
21194 declaration), and the defining identifier from the corresponding full type
21195 declaration is not checked.
21199 For a deferred constant, the defining name in the corresponding full constant
21200 declaration is not checked.
21202 Defining names of formal types are not checked.
21204 The rule may have the following parameters:
21208 For the @option{+R} option:
21211 Sets the default listed above for all the names to be checked.
21213 @item Type_Suffix=@emph{string}
21214 Specifies the suffix for a type name.
21216 @item Access_Suffix=@emph{string}
21217 Specifies the suffix for an access type name. If
21218 this parameter is set, it overrides for access
21219 types the suffix set by the @code{Type_Suffix} parameter.
21221 @item Constant_Suffix=@emph{string}
21222 Specifies the suffix for a constant name.
21224 @item Renaming_Suffix=@emph{string}
21225 Specifies the suffix for a package renaming name.
21229 For the @option{-R} option:
21232 Remove all the suffixes specified for the
21233 identifier suffix checks, whether by default or
21234 as specified by other rule parameters. All the
21235 checks for this rule are disabled as a result.
21238 Removes the suffix specified for types. This
21239 disables checks for types but does not disable
21240 any other checks for this rule (including the
21241 check for access type names if @code{Access_Suffix} is
21244 @item Access_Suffix
21245 Removes the suffix specified for access types.
21246 This disables checks for access type names but
21247 does not disable any other checks for this rule.
21248 If @code{Type_Suffix} is set, access type names are
21249 checked as ordinary type names.
21251 @item Constant_Suffix
21252 Removes the suffix specified for constants. This
21253 disables checks for constant names but does not
21254 disable any other checks for this rule.
21256 @item Renaming_Suffix
21257 Removes the suffix specified for package
21258 renamings. This disables checks for package
21259 renamings but does not disable any other checks
21265 If more than one parameter is used, parameters must be separated by commas.
21267 If more than one option is specified for the @command{gnatcheck} invocation,
21268 a new option overrides the previous one(s).
21270 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21272 name suffixes specified by previous options used for this rule.
21274 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21275 all the checks but keeps
21276 all the suffixes specified by previous options used for this rule.
21278 The @emph{string} value must be a valid suffix for an Ada identifier (after
21279 trimming all the leading and trailing space characters, if any).
21280 Parameters are not case sensitive, except the @emph{string} part.
21282 If any error is detected in a rule parameter, the parameter is ignored.
21283 In such a case the options that are set for the rule are not
21288 @node Multiple_Entries_In_Protected_Definitions
21289 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21290 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21293 Flag each protected definition (i.e., each protected object/type declaration)
21294 that defines more than one entry.
21295 Diagnostic messages are generated for all the entry declarations
21296 except the first one. An entry family is counted as one entry. Entries from
21297 the private part of the protected definition are also checked.
21299 This rule has no parameters.
21302 @subsection @code{Name_Clashes}
21303 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21306 Check that certain names are not used as defining identifiers. To activate
21307 this rule, you need to supply a reference to the dictionary file(s) as a rule
21308 parameter(s) (more then one dictionary file can be specified). If no
21309 dictionary file is set, this rule will not cause anything to be flagged.
21310 Only defining occurrences, not references, are checked.
21311 The check is not case-sensitive.
21313 This rule is enabled by default, but without setting any corresponding
21314 dictionary file(s); thus the default effect is to do no checks.
21316 A dictionary file is a plain text file. The maximum line length for this file
21317 is 1024 characters. If the line is longer then this limit, extra characters
21320 Each line can be either an empty line, a comment line, or a line containing
21321 a list of identifiers separated by space or HT characters.
21322 A comment is an Ada-style comment (from @code{--} to end-of-line).
21323 Identifiers must follow the Ada syntax for identifiers.
21324 A line containing one or more identifiers may end with a comment.
21326 @node Non_Qualified_Aggregates
21327 @subsection @code{Non_Qualified_Aggregates}
21328 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21331 Flag each non-qualified aggregate.
21332 A non-qualified aggregate is an
21333 aggregate that is not the expression of a qualified expression. A
21334 string literal is not considered an aggregate, but an array
21335 aggregate of a string type is considered as a normal aggregate.
21336 Aggregates of anonymous array types are not flagged.
21338 This rule has no parameters.
21341 @node Non_Short_Circuit_Operators
21342 @subsection @code{Non_Short_Circuit_Operators}
21343 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21346 Flag all calls to predefined @code{and} and @code{or} operators for
21347 any boolean type. Calls to
21348 user-defined @code{and} and @code{or} and to operators defined by renaming
21349 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21350 operators for modular types or boolean array types are not flagged.
21352 This rule has no parameters.
21356 @node Non_SPARK_Attributes
21357 @subsection @code{Non_SPARK_Attributes}
21358 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21361 The SPARK language defines the following subset of Ada 95 attribute
21362 designators as those that can be used in SPARK programs. The use of
21363 any other attribute is flagged.
21366 @item @code{'Adjacent}
21369 @item @code{'Ceiling}
21370 @item @code{'Component_Size}
21371 @item @code{'Compose}
21372 @item @code{'Copy_Sign}
21373 @item @code{'Delta}
21374 @item @code{'Denorm}
21375 @item @code{'Digits}
21376 @item @code{'Exponent}
21377 @item @code{'First}
21378 @item @code{'Floor}
21380 @item @code{'Fraction}
21382 @item @code{'Leading_Part}
21383 @item @code{'Length}
21384 @item @code{'Machine}
21385 @item @code{'Machine_Emax}
21386 @item @code{'Machine_Emin}
21387 @item @code{'Machine_Mantissa}
21388 @item @code{'Machine_Overflows}
21389 @item @code{'Machine_Radix}
21390 @item @code{'Machine_Rounds}
21393 @item @code{'Model}
21394 @item @code{'Model_Emin}
21395 @item @code{'Model_Epsilon}
21396 @item @code{'Model_Mantissa}
21397 @item @code{'Model_Small}
21398 @item @code{'Modulus}
21401 @item @code{'Range}
21402 @item @code{'Remainder}
21403 @item @code{'Rounding}
21404 @item @code{'Safe_First}
21405 @item @code{'Safe_Last}
21406 @item @code{'Scaling}
21407 @item @code{'Signed_Zeros}
21409 @item @code{'Small}
21411 @item @code{'Truncation}
21412 @item @code{'Unbiased_Rounding}
21414 @item @code{'Valid}
21418 This rule has no parameters.
21421 @node Non_Tagged_Derived_Types
21422 @subsection @code{Non_Tagged_Derived_Types}
21423 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21426 Flag all derived type declarations that do not have a record extension part.
21428 This rule has no parameters.
21432 @node Non_Visible_Exceptions
21433 @subsection @code{Non_Visible_Exceptions}
21434 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21437 Flag constructs leading to the possibility of propagating an exception
21438 out of the scope in which the exception is declared.
21439 Two cases are detected:
21443 An exception declaration in a subprogram body, task body or block
21444 statement is flagged if the body or statement does not contain a handler for
21445 that exception or a handler with an @code{others} choice.
21448 A @code{raise} statement in an exception handler of a subprogram body,
21449 task body or block statement is flagged if it (re)raises a locally
21450 declared exception. This may occur under the following circumstances:
21453 it explicitly raises a locally declared exception, or
21455 it does not specify an exception name (i.e., it is simply @code{raise;})
21456 and the enclosing handler contains a locally declared exception in its
21462 Renamings of local exceptions are not flagged.
21464 This rule has no parameters.
21467 @node Numeric_Literals
21468 @subsection @code{Numeric_Literals}
21469 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21472 Flag each use of a numeric literal in an index expression, and in any
21473 circumstance except for the following:
21477 a literal occurring in the initialization expression for a constant
21478 declaration or a named number declaration, or
21481 an integer literal that is less than or equal to a value
21482 specified by the @option{N} rule parameter.
21486 This rule may have the following parameters for the @option{+R} option:
21490 @emph{N} is an integer literal used as the maximal value that is not flagged
21491 (i.e., integer literals not exceeding this value are allowed)
21494 All integer literals are flagged
21498 If no parameters are set, the maximum unflagged value is 1.
21500 The last specified check limit (or the fact that there is no limit at
21501 all) is used when multiple @option{+R} options appear.
21503 The @option{-R} option for this rule has no parameters.
21504 It disables the rule but retains the last specified maximum unflagged value.
21505 If the @option{+R} option subsequently appears, this value is used as the
21506 threshold for the check.
21509 @node OTHERS_In_Aggregates
21510 @subsection @code{OTHERS_In_Aggregates}
21511 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21514 Flag each use of an @code{others} choice in extension aggregates.
21515 In record and array aggregates, an @code{others} choice is flagged unless
21516 it is used to refer to all components, or to all but one component.
21518 If, in case of a named array aggregate, there are two associations, one
21519 with an @code{others} choice and another with a discrete range, the
21520 @code{others} choice is flagged even if the discrete range specifies
21521 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21523 This rule has no parameters.
21525 @node OTHERS_In_CASE_Statements
21526 @subsection @code{OTHERS_In_CASE_Statements}
21527 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21530 Flag any use of an @code{others} choice in a @code{case} statement.
21532 This rule has no parameters.
21534 @node OTHERS_In_Exception_Handlers
21535 @subsection @code{OTHERS_In_Exception_Handlers}
21536 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21539 Flag any use of an @code{others} choice in an exception handler.
21541 This rule has no parameters.
21544 @node Outer_Loop_Exits
21545 @subsection @code{Outer_Loop_Exits}
21546 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21549 Flag each @code{exit} statement containing a loop name that is not the name
21550 of the immediately enclosing @code{loop} statement.
21552 This rule has no parameters.
21555 @node Overloaded_Operators
21556 @subsection @code{Overloaded_Operators}
21557 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21560 Flag each function declaration that overloads an operator symbol.
21561 A function body is checked only if the body does not have a
21562 separate spec. Formal functions are also checked. For a
21563 renaming declaration, only renaming-as-declaration is checked
21565 This rule has no parameters.
21568 @node Overly_Nested_Control_Structures
21569 @subsection @code{Overly_Nested_Control_Structures}
21570 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21573 Flag each control structure whose nesting level exceeds the value provided
21574 in the rule parameter.
21576 The control structures checked are the following:
21579 @item @code{if} statement
21580 @item @code{case} statement
21581 @item @code{loop} statement
21582 @item Selective accept statement
21583 @item Timed entry call statement
21584 @item Conditional entry call
21585 @item Asynchronous select statement
21589 The rule has the following parameter for the @option{+R} option:
21593 Positive integer specifying the maximal control structure nesting
21594 level that is not flagged
21598 If the parameter for the @option{+R} option is not specified or
21599 if it is not a positive integer, @option{+R} option is ignored.
21601 If more then one option is specified for the gnatcheck call, the later option and
21602 new parameter override the previous one(s).
21605 @node Parameters_Out_Of_Order
21606 @subsection @code{Parameters_Out_Of_Order}
21607 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21610 Flag each subprogram and entry declaration whose formal parameters are not
21611 ordered according to the following scheme:
21615 @item @code{in} and @code{access} parameters first,
21616 then @code{in out} parameters,
21617 and then @code{out} parameters;
21619 @item for @code{in} mode, parameters with default initialization expressions
21624 Only the first violation of the described order is flagged.
21626 The following constructs are checked:
21629 @item subprogram declarations (including null procedures);
21630 @item generic subprogram declarations;
21631 @item formal subprogram declarations;
21632 @item entry declarations;
21633 @item subprogram bodies and subprogram body stubs that do not
21634 have separate specifications
21638 Subprogram renamings are not checked.
21640 This rule has no parameters.
21643 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21644 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21645 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21648 Flag each generic actual parameter corresponding to a generic formal
21649 parameter with a default initialization, if positional notation is used.
21651 This rule has no parameters.
21653 @node Positional_Actuals_For_Defaulted_Parameters
21654 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21655 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21658 Flag each actual parameter to a subprogram or entry call where the
21659 corresponding formal parameter has a default expression, if positional
21662 This rule has no parameters.
21664 @node Positional_Components
21665 @subsection @code{Positional_Components}
21666 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21669 Flag each array, record and extension aggregate that includes positional
21672 This rule has no parameters.
21675 @node Positional_Generic_Parameters
21676 @subsection @code{Positional_Generic_Parameters}
21677 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21680 Flag each instantiation using positional parameter notation.
21682 This rule has no parameters.
21685 @node Positional_Parameters
21686 @subsection @code{Positional_Parameters}
21687 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21690 Flag each subprogram or entry call using positional parameter notation,
21691 except for the following:
21695 Invocations of prefix or infix operators are not flagged
21697 If the called subprogram or entry has only one formal parameter,
21698 the call is not flagged;
21700 If a subprogram call uses the @emph{Object.Operation} notation, then
21703 the first parameter (that is, @emph{Object}) is not flagged;
21705 if the called subprogram has only two parameters, the second parameter
21706 of the call is not flagged;
21711 This rule has no parameters.
21716 @node Predefined_Numeric_Types
21717 @subsection @code{Predefined_Numeric_Types}
21718 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21721 Flag each explicit use of the name of any numeric type or subtype defined
21722 in package @code{Standard}.
21724 The rationale for this rule is to detect when the
21725 program may depend on platform-specific characteristics of the implementation
21726 of the predefined numeric types. Note that this rule is over-pessimistic;
21727 for example, a program that uses @code{String} indexing
21728 likely needs a variable of type @code{Integer}.
21729 Another example is the flagging of predefined numeric types with explicit
21732 @smallexample @c ada
21733 subtype My_Integer is Integer range Left .. Right;
21734 Vy_Var : My_Integer;
21738 This rule detects only numeric types and subtypes defined in
21739 @code{Standard}. The use of numeric types and subtypes defined in other
21740 predefined packages (such as @code{System.Any_Priority} or
21741 @code{Ada.Text_IO.Count}) is not flagged
21743 This rule has no parameters.
21747 @node Raising_External_Exceptions
21748 @subsection @code{Raising_External_Exceptions}
21749 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21752 Flag any @code{raise} statement, in a program unit declared in a library
21753 package or in a generic library package, for an exception that is
21754 neither a predefined exception nor an exception that is also declared (or
21755 renamed) in the visible part of the package.
21757 This rule has no parameters.
21761 @node Raising_Predefined_Exceptions
21762 @subsection @code{Raising_Predefined_Exceptions}
21763 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21766 Flag each @code{raise} statement that raises a predefined exception
21767 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21768 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21770 This rule has no parameters.
21772 @node Separate_Numeric_Error_Handlers
21773 @subsection @code{Separate_Numeric_Error_Handlers}
21774 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
21777 Flags each exception handler that contains a choice for
21778 the predefined @code{Constraint_Error} exception, but does not contain
21779 the choice for the predefined @code{Numeric_Error} exception, or
21780 that contains the choice for @code{Numeric_Error}, but does not contain the
21781 choice for @code{Constraint_Error}.
21783 This rule has no parameters.
21787 @subsection @code{Recursion} (under construction, GLOBAL)
21788 @cindex @code{Recursion} rule (for @command{gnatcheck})
21791 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21792 calls, of recursive subprograms are detected.
21794 This rule has no parameters.
21798 @node Side_Effect_Functions
21799 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21800 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21803 Flag functions with side effects.
21805 We define a side effect as changing any data object that is not local for the
21806 body of this function.
21808 At the moment, we do NOT consider a side effect any input-output operations
21809 (changing a state or a content of any file).
21811 We do not consider protected functions for this rule (???)
21813 There are the following sources of side effect:
21816 @item Explicit (or direct) side-effect:
21820 direct assignment to a non-local variable;
21823 direct call to an entity that is known to change some data object that is
21824 not local for the body of this function (Note, that if F1 calls F2 and F2
21825 does have a side effect, this does not automatically mean that F1 also
21826 have a side effect, because it may be the case that F2 is declared in
21827 F1's body and it changes some data object that is global for F2, but
21831 @item Indirect side-effect:
21834 Subprogram calls implicitly issued by:
21837 computing initialization expressions from type declarations as a part
21838 of object elaboration or allocator evaluation;
21840 computing implicit parameters of subprogram or entry calls or generic
21845 activation of a task that change some non-local data object (directly or
21849 elaboration code of a package that is a result of a package instantiation;
21852 controlled objects;
21855 @item Situations when we can suspect a side-effect, but the full static check
21856 is either impossible or too hard:
21859 assignment to access variables or to the objects pointed by access
21863 call to a subprogram pointed by access-to-subprogram value
21871 This rule has no parameters.
21875 @subsection @code{Slices}
21876 @cindex @code{Slices} rule (for @command{gnatcheck})
21879 Flag all uses of array slicing
21881 This rule has no parameters.
21884 @node Unassigned_OUT_Parameters
21885 @subsection @code{Unassigned_OUT_Parameters}
21886 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21889 Flags procedures' @code{out} parameters that are not assigned, and
21890 identifies the contexts in which the assignments are missing.
21892 An @code{out} parameter is flagged in the statements in the procedure
21893 body's handled sequence of statements (before the procedure body's
21894 @code{exception} part, if any) if this sequence of statements contains
21895 no assignments to the parameter.
21897 An @code{out} parameter is flagged in an exception handler in the exception
21898 part of the procedure body's handled sequence of statements if the handler
21899 contains no assignment to the parameter.
21901 Bodies of generic procedures are also considered.
21903 The following are treated as assignments to an @code{out} parameter:
21907 an assignment statement, with the parameter or some component as the target;
21910 passing the parameter (or one of its components) as an @code{out} or
21911 @code{in out} parameter.
21915 This rule does not have any parameters.
21919 @node Uncommented_BEGIN_In_Package_Bodies
21920 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21921 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21924 Flags each package body with declarations and a statement part that does not
21925 include a trailing comment on the line containing the @code{begin} keyword;
21926 this trailing comment needs to specify the package name and nothing else.
21927 The @code{begin} is not flagged if the package body does not
21928 contain any declarations.
21930 If the @code{begin} keyword is placed on the
21931 same line as the last declaration or the first statement, it is flagged
21932 independently of whether the line contains a trailing comment. The
21933 diagnostic message is attached to the line containing the first statement.
21935 This rule has no parameters.
21938 @node Unconstrained_Array_Returns
21939 @subsection @code{Unconstrained_Array_Returns}
21940 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21943 Flag each function returning an unconstrained array. Function declarations,
21944 function bodies (and body stubs) having no separate specifications,
21945 and generic function instantiations are checked.
21946 Generic function declarations, function calls and function renamings are
21949 This rule has no parameters.
21951 @node Universal_Ranges
21952 @subsection @code{Universal_Ranges}
21953 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21956 Flag discrete ranges that are a part of an index constraint, constrained
21957 array definition, or @code{for}-loop parameter specification, and whose bounds
21958 are both of type @i{universal_integer}. Ranges that have at least one
21959 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21960 or an expression of non-universal type) are not flagged.
21962 This rule has no parameters.
21965 @node Unnamed_Blocks_And_Loops
21966 @subsection @code{Unnamed_Blocks_And_Loops}
21967 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
21970 Flag each unnamed block statement and loop statement.
21972 The rule has no parameters.
21977 @node Unused_Subprograms
21978 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
21979 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
21982 Flag all unused subprograms.
21984 This rule has no parameters.
21990 @node USE_PACKAGE_Clauses
21991 @subsection @code{USE_PACKAGE_Clauses}
21992 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
21995 Flag all @code{use} clauses for packages; @code{use type} clauses are
21998 This rule has no parameters.
22002 @node Volatile_Objects_Without_Address_Clauses
22003 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22004 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22007 Flag each volatile object that does not have an address clause.
22009 The following check is made: if the pragma @code{Volatile} is applied to a
22010 data object or to its type, then an address clause must
22011 be supplied for this object.
22013 This rule does not check the components of data objects,
22014 array components that are volatile as a result of the pragma
22015 @code{Volatile_Components}, or objects that are volatile because
22016 they are atomic as a result of pragmas @code{Atomic} or
22017 @code{Atomic_Components}.
22019 Only variable declarations, and not constant declarations, are checked.
22021 This rule has no parameters.
22024 @c *********************************
22025 @node Creating Sample Bodies Using gnatstub
22026 @chapter Creating Sample Bodies Using @command{gnatstub}
22030 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22031 for library unit declarations.
22033 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22034 driver (see @ref{The GNAT Driver and Project Files}).
22036 To create a body stub, @command{gnatstub} has to compile the library
22037 unit declaration. Therefore, bodies can be created only for legal
22038 library units. Moreover, if a library unit depends semantically upon
22039 units located outside the current directory, you have to provide
22040 the source search path when calling @command{gnatstub}, see the description
22041 of @command{gnatstub} switches below.
22044 * Running gnatstub::
22045 * Switches for gnatstub::
22048 @node Running gnatstub
22049 @section Running @command{gnatstub}
22052 @command{gnatstub} has the command-line interface of the form
22055 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22062 is the name of the source file that contains a library unit declaration
22063 for which a body must be created. The file name may contain the path
22065 The file name does not have to follow the GNAT file name conventions. If the
22067 does not follow GNAT file naming conventions, the name of the body file must
22069 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22070 If the file name follows the GNAT file naming
22071 conventions and the name of the body file is not provided,
22074 of the body file from the argument file name by replacing the @file{.ads}
22076 with the @file{.adb} suffix.
22079 indicates the directory in which the body stub is to be placed (the default
22084 is an optional sequence of switches as described in the next section
22087 @node Switches for gnatstub
22088 @section Switches for @command{gnatstub}
22094 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22095 If the destination directory already contains a file with the name of the
22097 for the argument spec file, replace it with the generated body stub.
22099 @item ^-hs^/HEADER=SPEC^
22100 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22101 Put the comment header (i.e., all the comments preceding the
22102 compilation unit) from the source of the library unit declaration
22103 into the body stub.
22105 @item ^-hg^/HEADER=GENERAL^
22106 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22107 Put a sample comment header into the body stub.
22109 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22110 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22111 Use the content of the file as the comment header for a generated body stub.
22115 @cindex @option{-IDIR} (@command{gnatstub})
22117 @cindex @option{-I-} (@command{gnatstub})
22120 @item /NOCURRENT_DIRECTORY
22121 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22123 ^These switches have ^This switch has^ the same meaning as in calls to
22125 ^They define ^It defines ^ the source search path in the call to
22126 @command{gcc} issued
22127 by @command{gnatstub} to compile an argument source file.
22129 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22130 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22131 This switch has the same meaning as in calls to @command{gcc}.
22132 It defines the additional configuration file to be passed to the call to
22133 @command{gcc} issued
22134 by @command{gnatstub} to compile an argument source file.
22136 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22137 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22138 (@var{n} is a non-negative integer). Set the maximum line length in the
22139 body stub to @var{n}; the default is 79. The maximum value that can be
22140 specified is 32767. Note that in the special case of configuration
22141 pragma files, the maximum is always 32767 regardless of whether or
22142 not this switch appears.
22144 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22145 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22146 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22147 the generated body sample to @var{n}.
22148 The default indentation is 3.
22150 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22151 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22152 Order local bodies alphabetically. (By default local bodies are ordered
22153 in the same way as the corresponding local specs in the argument spec file.)
22155 @item ^-i^/INDENTATION=^@var{n}
22156 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22157 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22159 @item ^-k^/TREE_FILE=SAVE^
22160 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22161 Do not remove the tree file (i.e., the snapshot of the compiler internal
22162 structures used by @command{gnatstub}) after creating the body stub.
22164 @item ^-l^/LINE_LENGTH=^@var{n}
22165 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22166 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22168 @item ^-o^/BODY=^@var{body-name}
22169 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22170 Body file name. This should be set if the argument file name does not
22172 the GNAT file naming
22173 conventions. If this switch is omitted the default name for the body will be
22175 from the argument file name according to the GNAT file naming conventions.
22178 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22179 Quiet mode: do not generate a confirmation when a body is
22180 successfully created, and do not generate a message when a body is not
22184 @item ^-r^/TREE_FILE=REUSE^
22185 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22186 Reuse the tree file (if it exists) instead of creating it. Instead of
22187 creating the tree file for the library unit declaration, @command{gnatstub}
22188 tries to find it in the current directory and use it for creating
22189 a body. If the tree file is not found, no body is created. This option
22190 also implies @option{^-k^/SAVE^}, whether or not
22191 the latter is set explicitly.
22193 @item ^-t^/TREE_FILE=OVERWRITE^
22194 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22195 Overwrite the existing tree file. If the current directory already
22196 contains the file which, according to the GNAT file naming rules should
22197 be considered as a tree file for the argument source file,
22199 will refuse to create the tree file needed to create a sample body
22200 unless this option is set.
22202 @item ^-v^/VERBOSE^
22203 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22204 Verbose mode: generate version information.
22208 @node Other Utility Programs
22209 @chapter Other Utility Programs
22212 This chapter discusses some other utility programs available in the Ada
22216 * Using Other Utility Programs with GNAT::
22217 * The External Symbol Naming Scheme of GNAT::
22218 * Converting Ada Files to html with gnathtml::
22219 * Installing gnathtml::
22226 @node Using Other Utility Programs with GNAT
22227 @section Using Other Utility Programs with GNAT
22230 The object files generated by GNAT are in standard system format and in
22231 particular the debugging information uses this format. This means
22232 programs generated by GNAT can be used with existing utilities that
22233 depend on these formats.
22236 In general, any utility program that works with C will also often work with
22237 Ada programs generated by GNAT. This includes software utilities such as
22238 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22242 @node The External Symbol Naming Scheme of GNAT
22243 @section The External Symbol Naming Scheme of GNAT
22246 In order to interpret the output from GNAT, when using tools that are
22247 originally intended for use with other languages, it is useful to
22248 understand the conventions used to generate link names from the Ada
22251 All link names are in all lowercase letters. With the exception of library
22252 procedure names, the mechanism used is simply to use the full expanded
22253 Ada name with dots replaced by double underscores. For example, suppose
22254 we have the following package spec:
22256 @smallexample @c ada
22267 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22268 the corresponding link name is @code{qrs__mn}.
22270 Of course if a @code{pragma Export} is used this may be overridden:
22272 @smallexample @c ada
22277 pragma Export (Var1, C, External_Name => "var1_name");
22279 pragma Export (Var2, C, Link_Name => "var2_link_name");
22286 In this case, the link name for @var{Var1} is whatever link name the
22287 C compiler would assign for the C function @var{var1_name}. This typically
22288 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22289 system conventions, but other possibilities exist. The link name for
22290 @var{Var2} is @var{var2_link_name}, and this is not operating system
22294 One exception occurs for library level procedures. A potential ambiguity
22295 arises between the required name @code{_main} for the C main program,
22296 and the name we would otherwise assign to an Ada library level procedure
22297 called @code{Main} (which might well not be the main program).
22299 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22300 names. So if we have a library level procedure such as
22302 @smallexample @c ada
22305 procedure Hello (S : String);
22311 the external name of this procedure will be @var{_ada_hello}.
22314 @node Converting Ada Files to html with gnathtml
22315 @section Converting Ada Files to HTML with @code{gnathtml}
22318 This @code{Perl} script allows Ada source files to be browsed using
22319 standard Web browsers. For installation procedure, see the section
22320 @xref{Installing gnathtml}.
22322 Ada reserved keywords are highlighted in a bold font and Ada comments in
22323 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22324 switch to suppress the generation of cross-referencing information, user
22325 defined variables and types will appear in a different color; you will
22326 be able to click on any identifier and go to its declaration.
22328 The command line is as follow:
22330 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
22334 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22335 an html file for every ada file, and a global file called @file{index.htm}.
22336 This file is an index of every identifier defined in the files.
22338 The available ^switches^options^ are the following ones:
22342 @cindex @option{-83} (@code{gnathtml})
22343 Only the Ada 83 subset of keywords will be highlighted.
22345 @item -cc @var{color}
22346 @cindex @option{-cc} (@code{gnathtml})
22347 This option allows you to change the color used for comments. The default
22348 value is green. The color argument can be any name accepted by html.
22351 @cindex @option{-d} (@code{gnathtml})
22352 If the Ada files depend on some other files (for instance through
22353 @code{with} clauses, the latter files will also be converted to html.
22354 Only the files in the user project will be converted to html, not the files
22355 in the run-time library itself.
22358 @cindex @option{-D} (@code{gnathtml})
22359 This command is the same as @option{-d} above, but @command{gnathtml} will
22360 also look for files in the run-time library, and generate html files for them.
22362 @item -ext @var{extension}
22363 @cindex @option{-ext} (@code{gnathtml})
22364 This option allows you to change the extension of the generated HTML files.
22365 If you do not specify an extension, it will default to @file{htm}.
22368 @cindex @option{-f} (@code{gnathtml})
22369 By default, gnathtml will generate html links only for global entities
22370 ('with'ed units, global variables and types,@dots{}). If you specify
22371 @option{-f} on the command line, then links will be generated for local
22374 @item -l @var{number}
22375 @cindex @option{-l} (@code{gnathtml})
22376 If this ^switch^option^ is provided and @var{number} is not 0, then
22377 @code{gnathtml} will number the html files every @var{number} line.
22380 @cindex @option{-I} (@code{gnathtml})
22381 Specify a directory to search for library files (@file{.ALI} files) and
22382 source files. You can provide several -I switches on the command line,
22383 and the directories will be parsed in the order of the command line.
22386 @cindex @option{-o} (@code{gnathtml})
22387 Specify the output directory for html files. By default, gnathtml will
22388 saved the generated html files in a subdirectory named @file{html/}.
22390 @item -p @var{file}
22391 @cindex @option{-p} (@code{gnathtml})
22392 If you are using Emacs and the most recent Emacs Ada mode, which provides
22393 a full Integrated Development Environment for compiling, checking,
22394 running and debugging applications, you may use @file{.gpr} files
22395 to give the directories where Emacs can find sources and object files.
22397 Using this ^switch^option^, you can tell gnathtml to use these files.
22398 This allows you to get an html version of your application, even if it
22399 is spread over multiple directories.
22401 @item -sc @var{color}
22402 @cindex @option{-sc} (@code{gnathtml})
22403 This ^switch^option^ allows you to change the color used for symbol
22405 The default value is red. The color argument can be any name accepted by html.
22407 @item -t @var{file}
22408 @cindex @option{-t} (@code{gnathtml})
22409 This ^switch^option^ provides the name of a file. This file contains a list of
22410 file names to be converted, and the effect is exactly as though they had
22411 appeared explicitly on the command line. This
22412 is the recommended way to work around the command line length limit on some
22417 @node Installing gnathtml
22418 @section Installing @code{gnathtml}
22421 @code{Perl} needs to be installed on your machine to run this script.
22422 @code{Perl} is freely available for almost every architecture and
22423 Operating System via the Internet.
22425 On Unix systems, you may want to modify the first line of the script
22426 @code{gnathtml}, to explicitly tell the Operating system where Perl
22427 is. The syntax of this line is:
22429 #!full_path_name_to_perl
22433 Alternatively, you may run the script using the following command line:
22436 $ perl gnathtml.pl @ovar{switches} @var{files}
22445 The GNAT distribution provides an Ada 95 template for the HP Language
22446 Sensitive Editor (LSE), a component of DECset. In order to
22447 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
22454 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
22455 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
22456 the collection phase with the /DEBUG qualifier.
22459 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
22460 $ DEFINE LIB$DEBUG PCA$COLLECTOR
22461 $ RUN/DEBUG <PROGRAM_NAME>
22467 @c ******************************
22468 @node Code Coverage and Profiling
22469 @chapter Code Coverage and Profiling
22470 @cindex Code Coverage
22474 This chapter describes how to use @code{gcov} - coverage testing tool - and
22475 @code{gprof} - profiler tool - on your Ada programs.
22478 * Code Coverage of Ada Programs using gcov::
22479 * Profiling an Ada Program using gprof::
22482 @node Code Coverage of Ada Programs using gcov
22483 @section Code Coverage of Ada Programs using gcov
22485 @cindex -fprofile-arcs
22486 @cindex -ftest-coverage
22488 @cindex Code Coverage
22491 @code{gcov} is a test coverage program: it analyzes the execution of a given
22492 program on selected tests, to help you determine the portions of the program
22493 that are still untested.
22495 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
22496 User's Guide. You can refer to this documentation for a more complete
22499 This chapter provides a quick startup guide, and
22500 details some Gnat-specific features.
22503 * Quick startup guide::
22507 @node Quick startup guide
22508 @subsection Quick startup guide
22510 In order to perform coverage analysis of a program using @code{gcov}, 3
22515 Code instrumentation during the compilation process
22517 Execution of the instrumented program
22519 Execution of the @code{gcov} tool to generate the result.
22522 The code instrumentation needed by gcov is created at the object level:
22523 The source code is not modified in any way, because the instrumentation code is
22524 inserted by gcc during the compilation process. To compile your code with code
22525 coverage activated, you need to recompile your whole project using the
22527 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
22528 @code{-fprofile-arcs}.
22531 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
22532 -largs -fprofile-arcs
22535 This compilation process will create @file{.gcno} files together with
22536 the usual object files.
22538 Once the program is compiled with coverage instrumentation, you can
22539 run it as many times as needed - on portions of a test suite for
22540 example. The first execution will produce @file{.gcda} files at the
22541 same location as the @file{.gcno} files. The following executions
22542 will update those files, so that a cumulative result of the covered
22543 portions of the program is generated.
22545 Finally, you need to call the @code{gcov} tool. The different options of
22546 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
22548 This will create annotated source files with a @file{.gcov} extension:
22549 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
22551 @node Gnat specifics
22552 @subsection Gnat specifics
22554 Because Ada semantics, portions of the source code may be shared among
22555 several object files. This is the case for example when generics are
22556 involved, when inlining is active or when declarations generate initialisation
22557 calls. In order to take
22558 into account this shared code, you need to call @code{gcov} on all
22559 source files of the tested program at once.
22561 The list of source files might exceed the system's maximum command line
22562 length. In order to bypass this limitation, a new mechanism has been
22563 implemented in @code{gcov}: you can now list all your project's files into a
22564 text file, and provide this file to gcov as a parameter, preceded by a @@
22565 (e.g. @samp{gcov @@mysrclist.txt}).
22567 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
22568 not supported as there can be unresolved symbols during the final link.
22570 @node Profiling an Ada Program using gprof
22571 @section Profiling an Ada Program using gprof
22577 This section is not meant to be an exhaustive documentation of @code{gprof}.
22578 Full documentation for it can be found in the GNU Profiler User's Guide
22579 documentation that is part of this GNAT distribution.
22581 Profiling a program helps determine the parts of a program that are executed
22582 most often, and are therefore the most time-consuming.
22584 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
22585 better handle Ada programs and multitasking.
22586 It is currently supported on the following platforms
22591 solaris sparc/sparc64/x86
22597 In order to profile a program using @code{gprof}, 3 steps are needed:
22601 Code instrumentation, requiring a full recompilation of the project with the
22604 Execution of the program under the analysis conditions, i.e. with the desired
22607 Analysis of the results using the @code{gprof} tool.
22611 The following sections detail the different steps, and indicate how
22612 to interpret the results:
22614 * Compilation for profiling::
22615 * Program execution::
22617 * Interpretation of profiling results::
22620 @node Compilation for profiling
22621 @subsection Compilation for profiling
22625 In order to profile a program the first step is to tell the compiler
22626 to generate the necessary profiling information. The compiler switch to be used
22627 is @code{-pg}, which must be added to other compilation switches. This
22628 switch needs to be specified both during compilation and link stages, and can
22629 be specified once when using gnatmake:
22632 gnatmake -f -pg -P my_project
22636 Note that only the objects that were compiled with the @samp{-pg} switch will be
22637 profiled; if you need to profile your whole project, use the
22638 @samp{-f} gnatmake switch to force full recompilation.
22640 @node Program execution
22641 @subsection Program execution
22644 Once the program has been compiled for profiling, you can run it as usual.
22646 The only constraint imposed by profiling is that the program must terminate
22647 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
22650 Once the program completes execution, a data file called @file{gmon.out} is
22651 generated in the directory where the program was launched from. If this file
22652 already exists, it will be overwritten.
22654 @node Running gprof
22655 @subsection Running gprof
22658 The @code{gprof} tool is called as follow:
22661 gprof my_prog gmon.out
22672 The complete form of the gprof command line is the following:
22675 gprof [^switches^options^] [executable [data-file]]
22679 @code{gprof} supports numerous ^switch^options^. The order of these
22680 ^switch^options^ does not matter. The full list of options can be found in
22681 the GNU Profiler User's Guide documentation that comes with this documentation.
22683 The following is the subset of those switches that is most relevant:
22687 @item --demangle[=@var{style}]
22688 @itemx --no-demangle
22689 @cindex @option{--demangle} (@code{gprof})
22690 These options control whether symbol names should be demangled when
22691 printing output. The default is to demangle C++ symbols. The
22692 @code{--no-demangle} option may be used to turn off demangling. Different
22693 compilers have different mangling styles. The optional demangling style
22694 argument can be used to choose an appropriate demangling style for your
22695 compiler, in particular Ada symbols generated by GNAT can be demangled using
22696 @code{--demangle=gnat}.
22698 @item -e @var{function_name}
22699 @cindex @option{-e} (@code{gprof})
22700 The @samp{-e @var{function}} option tells @code{gprof} not to print
22701 information about the function @var{function_name} (and its
22702 children@dots{}) in the call graph. The function will still be listed
22703 as a child of any functions that call it, but its index number will be
22704 shown as @samp{[not printed]}. More than one @samp{-e} option may be
22705 given; only one @var{function_name} may be indicated with each @samp{-e}
22708 @item -E @var{function_name}
22709 @cindex @option{-E} (@code{gprof})
22710 The @code{-E @var{function}} option works like the @code{-e} option, but
22711 execution time spent in the function (and children who were not called from
22712 anywhere else), will not be used to compute the percentages-of-time for
22713 the call graph. More than one @samp{-E} option may be given; only one
22714 @var{function_name} may be indicated with each @samp{-E} option.
22716 @item -f @var{function_name}
22717 @cindex @option{-f} (@code{gprof})
22718 The @samp{-f @var{function}} option causes @code{gprof} to limit the
22719 call graph to the function @var{function_name} and its children (and
22720 their children@dots{}). More than one @samp{-f} option may be given;
22721 only one @var{function_name} may be indicated with each @samp{-f}
22724 @item -F @var{function_name}
22725 @cindex @option{-F} (@code{gprof})
22726 The @samp{-F @var{function}} option works like the @code{-f} option, but
22727 only time spent in the function and its children (and their
22728 children@dots{}) will be used to determine total-time and
22729 percentages-of-time for the call graph. More than one @samp{-F} option
22730 may be given; only one @var{function_name} may be indicated with each
22731 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
22735 @node Interpretation of profiling results
22736 @subsection Interpretation of profiling results
22740 The results of the profiling analysis are represented by two arrays: the
22741 'flat profile' and the 'call graph'. Full documentation of those outputs
22742 can be found in the GNU Profiler User's Guide.
22744 The flat profile shows the time spent in each function of the program, and how
22745 many time it has been called. This allows you to locate easily the most
22746 time-consuming functions.
22748 The call graph shows, for each subprogram, the subprograms that call it,
22749 and the subprograms that it calls. It also provides an estimate of the time
22750 spent in each of those callers/called subprograms.
22753 @c ******************************
22754 @node Running and Debugging Ada Programs
22755 @chapter Running and Debugging Ada Programs
22759 This chapter discusses how to debug Ada programs.
22761 It applies to GNAT on the Alpha OpenVMS platform;
22762 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
22763 since HP has implemented Ada support in the OpenVMS debugger on I64.
22766 An incorrect Ada program may be handled in three ways by the GNAT compiler:
22770 The illegality may be a violation of the static semantics of Ada. In
22771 that case GNAT diagnoses the constructs in the program that are illegal.
22772 It is then a straightforward matter for the user to modify those parts of
22776 The illegality may be a violation of the dynamic semantics of Ada. In
22777 that case the program compiles and executes, but may generate incorrect
22778 results, or may terminate abnormally with some exception.
22781 When presented with a program that contains convoluted errors, GNAT
22782 itself may terminate abnormally without providing full diagnostics on
22783 the incorrect user program.
22787 * The GNAT Debugger GDB::
22789 * Introduction to GDB Commands::
22790 * Using Ada Expressions::
22791 * Calling User-Defined Subprograms::
22792 * Using the Next Command in a Function::
22795 * Debugging Generic Units::
22796 * GNAT Abnormal Termination or Failure to Terminate::
22797 * Naming Conventions for GNAT Source Files::
22798 * Getting Internal Debugging Information::
22799 * Stack Traceback::
22805 @node The GNAT Debugger GDB
22806 @section The GNAT Debugger GDB
22809 @code{GDB} is a general purpose, platform-independent debugger that
22810 can be used to debug mixed-language programs compiled with @command{gcc},
22811 and in particular is capable of debugging Ada programs compiled with
22812 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
22813 complex Ada data structures.
22815 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
22817 located in the GNU:[DOCS] directory,
22819 for full details on the usage of @code{GDB}, including a section on
22820 its usage on programs. This manual should be consulted for full
22821 details. The section that follows is a brief introduction to the
22822 philosophy and use of @code{GDB}.
22824 When GNAT programs are compiled, the compiler optionally writes debugging
22825 information into the generated object file, including information on
22826 line numbers, and on declared types and variables. This information is
22827 separate from the generated code. It makes the object files considerably
22828 larger, but it does not add to the size of the actual executable that
22829 will be loaded into memory, and has no impact on run-time performance. The
22830 generation of debug information is triggered by the use of the
22831 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
22832 used to carry out the compilations. It is important to emphasize that
22833 the use of these options does not change the generated code.
22835 The debugging information is written in standard system formats that
22836 are used by many tools, including debuggers and profilers. The format
22837 of the information is typically designed to describe C types and
22838 semantics, but GNAT implements a translation scheme which allows full
22839 details about Ada types and variables to be encoded into these
22840 standard C formats. Details of this encoding scheme may be found in
22841 the file exp_dbug.ads in the GNAT source distribution. However, the
22842 details of this encoding are, in general, of no interest to a user,
22843 since @code{GDB} automatically performs the necessary decoding.
22845 When a program is bound and linked, the debugging information is
22846 collected from the object files, and stored in the executable image of
22847 the program. Again, this process significantly increases the size of
22848 the generated executable file, but it does not increase the size of
22849 the executable program itself. Furthermore, if this program is run in
22850 the normal manner, it runs exactly as if the debug information were
22851 not present, and takes no more actual memory.
22853 However, if the program is run under control of @code{GDB}, the
22854 debugger is activated. The image of the program is loaded, at which
22855 point it is ready to run. If a run command is given, then the program
22856 will run exactly as it would have if @code{GDB} were not present. This
22857 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
22858 entirely non-intrusive until a breakpoint is encountered. If no
22859 breakpoint is ever hit, the program will run exactly as it would if no
22860 debugger were present. When a breakpoint is hit, @code{GDB} accesses
22861 the debugging information and can respond to user commands to inspect
22862 variables, and more generally to report on the state of execution.
22866 @section Running GDB
22869 This section describes how to initiate the debugger.
22870 @c The above sentence is really just filler, but it was otherwise
22871 @c clumsy to get the first paragraph nonindented given the conditional
22872 @c nature of the description
22875 The debugger can be launched from a @code{GPS} menu or
22876 directly from the command line. The description below covers the latter use.
22877 All the commands shown can be used in the @code{GPS} debug console window,
22878 but there are usually more GUI-based ways to achieve the same effect.
22881 The command to run @code{GDB} is
22884 $ ^gdb program^GDB PROGRAM^
22888 where @code{^program^PROGRAM^} is the name of the executable file. This
22889 activates the debugger and results in a prompt for debugger commands.
22890 The simplest command is simply @code{run}, which causes the program to run
22891 exactly as if the debugger were not present. The following section
22892 describes some of the additional commands that can be given to @code{GDB}.
22894 @c *******************************
22895 @node Introduction to GDB Commands
22896 @section Introduction to GDB Commands
22899 @code{GDB} contains a large repertoire of commands. @xref{Top,,
22900 Debugging with GDB, gdb, Debugging with GDB},
22902 located in the GNU:[DOCS] directory,
22904 for extensive documentation on the use
22905 of these commands, together with examples of their use. Furthermore,
22906 the command @command{help} invoked from within GDB activates a simple help
22907 facility which summarizes the available commands and their options.
22908 In this section we summarize a few of the most commonly
22909 used commands to give an idea of what @code{GDB} is about. You should create
22910 a simple program with debugging information and experiment with the use of
22911 these @code{GDB} commands on the program as you read through the
22915 @item set args @var{arguments}
22916 The @var{arguments} list above is a list of arguments to be passed to
22917 the program on a subsequent run command, just as though the arguments
22918 had been entered on a normal invocation of the program. The @code{set args}
22919 command is not needed if the program does not require arguments.
22922 The @code{run} command causes execution of the program to start from
22923 the beginning. If the program is already running, that is to say if
22924 you are currently positioned at a breakpoint, then a prompt will ask
22925 for confirmation that you want to abandon the current execution and
22928 @item breakpoint @var{location}
22929 The breakpoint command sets a breakpoint, that is to say a point at which
22930 execution will halt and @code{GDB} will await further
22931 commands. @var{location} is
22932 either a line number within a file, given in the format @code{file:linenumber},
22933 or it is the name of a subprogram. If you request that a breakpoint be set on
22934 a subprogram that is overloaded, a prompt will ask you to specify on which of
22935 those subprograms you want to breakpoint. You can also
22936 specify that all of them should be breakpointed. If the program is run
22937 and execution encounters the breakpoint, then the program
22938 stops and @code{GDB} signals that the breakpoint was encountered by
22939 printing the line of code before which the program is halted.
22941 @item breakpoint exception @var{name}
22942 A special form of the breakpoint command which breakpoints whenever
22943 exception @var{name} is raised.
22944 If @var{name} is omitted,
22945 then a breakpoint will occur when any exception is raised.
22947 @item print @var{expression}
22948 This will print the value of the given expression. Most simple
22949 Ada expression formats are properly handled by @code{GDB}, so the expression
22950 can contain function calls, variables, operators, and attribute references.
22953 Continues execution following a breakpoint, until the next breakpoint or the
22954 termination of the program.
22957 Executes a single line after a breakpoint. If the next statement
22958 is a subprogram call, execution continues into (the first statement of)
22959 the called subprogram.
22962 Executes a single line. If this line is a subprogram call, executes and
22963 returns from the call.
22966 Lists a few lines around the current source location. In practice, it
22967 is usually more convenient to have a separate edit window open with the
22968 relevant source file displayed. Successive applications of this command
22969 print subsequent lines. The command can be given an argument which is a
22970 line number, in which case it displays a few lines around the specified one.
22973 Displays a backtrace of the call chain. This command is typically
22974 used after a breakpoint has occurred, to examine the sequence of calls that
22975 leads to the current breakpoint. The display includes one line for each
22976 activation record (frame) corresponding to an active subprogram.
22979 At a breakpoint, @code{GDB} can display the values of variables local
22980 to the current frame. The command @code{up} can be used to
22981 examine the contents of other active frames, by moving the focus up
22982 the stack, that is to say from callee to caller, one frame at a time.
22985 Moves the focus of @code{GDB} down from the frame currently being
22986 examined to the frame of its callee (the reverse of the previous command),
22988 @item frame @var{n}
22989 Inspect the frame with the given number. The value 0 denotes the frame
22990 of the current breakpoint, that is to say the top of the call stack.
22995 The above list is a very short introduction to the commands that
22996 @code{GDB} provides. Important additional capabilities, including conditional
22997 breakpoints, the ability to execute command sequences on a breakpoint,
22998 the ability to debug at the machine instruction level and many other
22999 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23000 Debugging with GDB}. Note that most commands can be abbreviated
23001 (for example, c for continue, bt for backtrace).
23003 @node Using Ada Expressions
23004 @section Using Ada Expressions
23005 @cindex Ada expressions
23008 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23009 extensions. The philosophy behind the design of this subset is
23013 That @code{GDB} should provide basic literals and access to operations for
23014 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23015 leaving more sophisticated computations to subprograms written into the
23016 program (which therefore may be called from @code{GDB}).
23019 That type safety and strict adherence to Ada language restrictions
23020 are not particularly important to the @code{GDB} user.
23023 That brevity is important to the @code{GDB} user.
23027 Thus, for brevity, the debugger acts as if there were
23028 implicit @code{with} and @code{use} clauses in effect for all user-written
23029 packages, thus making it unnecessary to fully qualify most names with
23030 their packages, regardless of context. Where this causes ambiguity,
23031 @code{GDB} asks the user's intent.
23033 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23034 GDB, gdb, Debugging with GDB}.
23036 @node Calling User-Defined Subprograms
23037 @section Calling User-Defined Subprograms
23040 An important capability of @code{GDB} is the ability to call user-defined
23041 subprograms while debugging. This is achieved simply by entering
23042 a subprogram call statement in the form:
23045 call subprogram-name (parameters)
23049 The keyword @code{call} can be omitted in the normal case where the
23050 @code{subprogram-name} does not coincide with any of the predefined
23051 @code{GDB} commands.
23053 The effect is to invoke the given subprogram, passing it the
23054 list of parameters that is supplied. The parameters can be expressions and
23055 can include variables from the program being debugged. The
23056 subprogram must be defined
23057 at the library level within your program, and @code{GDB} will call the
23058 subprogram within the environment of your program execution (which
23059 means that the subprogram is free to access or even modify variables
23060 within your program).
23062 The most important use of this facility is in allowing the inclusion of
23063 debugging routines that are tailored to particular data structures
23064 in your program. Such debugging routines can be written to provide a suitably
23065 high-level description of an abstract type, rather than a low-level dump
23066 of its physical layout. After all, the standard
23067 @code{GDB print} command only knows the physical layout of your
23068 types, not their abstract meaning. Debugging routines can provide information
23069 at the desired semantic level and are thus enormously useful.
23071 For example, when debugging GNAT itself, it is crucial to have access to
23072 the contents of the tree nodes used to represent the program internally.
23073 But tree nodes are represented simply by an integer value (which in turn
23074 is an index into a table of nodes).
23075 Using the @code{print} command on a tree node would simply print this integer
23076 value, which is not very useful. But the PN routine (defined in file
23077 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23078 a useful high level representation of the tree node, which includes the
23079 syntactic category of the node, its position in the source, the integers
23080 that denote descendant nodes and parent node, as well as varied
23081 semantic information. To study this example in more detail, you might want to
23082 look at the body of the PN procedure in the stated file.
23084 @node Using the Next Command in a Function
23085 @section Using the Next Command in a Function
23088 When you use the @code{next} command in a function, the current source
23089 location will advance to the next statement as usual. A special case
23090 arises in the case of a @code{return} statement.
23092 Part of the code for a return statement is the ``epilog'' of the function.
23093 This is the code that returns to the caller. There is only one copy of
23094 this epilog code, and it is typically associated with the last return
23095 statement in the function if there is more than one return. In some
23096 implementations, this epilog is associated with the first statement
23099 The result is that if you use the @code{next} command from a return
23100 statement that is not the last return statement of the function you
23101 may see a strange apparent jump to the last return statement or to
23102 the start of the function. You should simply ignore this odd jump.
23103 The value returned is always that from the first return statement
23104 that was stepped through.
23106 @node Ada Exceptions
23107 @section Breaking on Ada Exceptions
23111 You can set breakpoints that trip when your program raises
23112 selected exceptions.
23115 @item break exception
23116 Set a breakpoint that trips whenever (any task in the) program raises
23119 @item break exception @var{name}
23120 Set a breakpoint that trips whenever (any task in the) program raises
23121 the exception @var{name}.
23123 @item break exception unhandled
23124 Set a breakpoint that trips whenever (any task in the) program raises an
23125 exception for which there is no handler.
23127 @item info exceptions
23128 @itemx info exceptions @var{regexp}
23129 The @code{info exceptions} command permits the user to examine all defined
23130 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23131 argument, prints out only those exceptions whose name matches @var{regexp}.
23139 @code{GDB} allows the following task-related commands:
23143 This command shows a list of current Ada tasks, as in the following example:
23150 ID TID P-ID Thread Pri State Name
23151 1 8088000 0 807e000 15 Child Activation Wait main_task
23152 2 80a4000 1 80ae000 15 Accept/Select Wait b
23153 3 809a800 1 80a4800 15 Child Activation Wait a
23154 * 4 80ae800 3 80b8000 15 Running c
23158 In this listing, the asterisk before the first task indicates it to be the
23159 currently running task. The first column lists the task ID that is used
23160 to refer to tasks in the following commands.
23162 @item break @var{linespec} task @var{taskid}
23163 @itemx break @var{linespec} task @var{taskid} if @dots{}
23164 @cindex Breakpoints and tasks
23165 These commands are like the @code{break @dots{} thread @dots{}}.
23166 @var{linespec} specifies source lines.
23168 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23169 to specify that you only want @code{GDB} to stop the program when a
23170 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23171 numeric task identifiers assigned by @code{GDB}, shown in the first
23172 column of the @samp{info tasks} display.
23174 If you do not specify @samp{task @var{taskid}} when you set a
23175 breakpoint, the breakpoint applies to @emph{all} tasks of your
23178 You can use the @code{task} qualifier on conditional breakpoints as
23179 well; in this case, place @samp{task @var{taskid}} before the
23180 breakpoint condition (before the @code{if}).
23182 @item task @var{taskno}
23183 @cindex Task switching
23185 This command allows to switch to the task referred by @var{taskno}. In
23186 particular, This allows to browse the backtrace of the specified
23187 task. It is advised to switch back to the original task before
23188 continuing execution otherwise the scheduling of the program may be
23193 For more detailed information on the tasking support,
23194 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23196 @node Debugging Generic Units
23197 @section Debugging Generic Units
23198 @cindex Debugging Generic Units
23202 GNAT always uses code expansion for generic instantiation. This means that
23203 each time an instantiation occurs, a complete copy of the original code is
23204 made, with appropriate substitutions of formals by actuals.
23206 It is not possible to refer to the original generic entities in
23207 @code{GDB}, but it is always possible to debug a particular instance of
23208 a generic, by using the appropriate expanded names. For example, if we have
23210 @smallexample @c ada
23215 generic package k is
23216 procedure kp (v1 : in out integer);
23220 procedure kp (v1 : in out integer) is
23226 package k1 is new k;
23227 package k2 is new k;
23229 var : integer := 1;
23242 Then to break on a call to procedure kp in the k2 instance, simply
23246 (gdb) break g.k2.kp
23250 When the breakpoint occurs, you can step through the code of the
23251 instance in the normal manner and examine the values of local variables, as for
23254 @node GNAT Abnormal Termination or Failure to Terminate
23255 @section GNAT Abnormal Termination or Failure to Terminate
23256 @cindex GNAT Abnormal Termination or Failure to Terminate
23259 When presented with programs that contain serious errors in syntax
23261 GNAT may on rare occasions experience problems in operation, such
23263 segmentation fault or illegal memory access, raising an internal
23264 exception, terminating abnormally, or failing to terminate at all.
23265 In such cases, you can activate
23266 various features of GNAT that can help you pinpoint the construct in your
23267 program that is the likely source of the problem.
23269 The following strategies are presented in increasing order of
23270 difficulty, corresponding to your experience in using GNAT and your
23271 familiarity with compiler internals.
23275 Run @command{gcc} with the @option{-gnatf}. This first
23276 switch causes all errors on a given line to be reported. In its absence,
23277 only the first error on a line is displayed.
23279 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23280 are encountered, rather than after compilation is terminated. If GNAT
23281 terminates prematurely or goes into an infinite loop, the last error
23282 message displayed may help to pinpoint the culprit.
23285 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23286 mode, @command{gcc} produces ongoing information about the progress of the
23287 compilation and provides the name of each procedure as code is
23288 generated. This switch allows you to find which Ada procedure was being
23289 compiled when it encountered a code generation problem.
23292 @cindex @option{-gnatdc} switch
23293 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23294 switch that does for the front-end what @option{^-v^VERBOSE^} does
23295 for the back end. The system prints the name of each unit,
23296 either a compilation unit or nested unit, as it is being analyzed.
23298 Finally, you can start
23299 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23300 front-end of GNAT, and can be run independently (normally it is just
23301 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23302 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23303 @code{where} command is the first line of attack; the variable
23304 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23305 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23306 which the execution stopped, and @code{input_file name} indicates the name of
23310 @node Naming Conventions for GNAT Source Files
23311 @section Naming Conventions for GNAT Source Files
23314 In order to examine the workings of the GNAT system, the following
23315 brief description of its organization may be helpful:
23319 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23322 All files prefixed with @file{^par^PAR^} are components of the parser. The
23323 numbers correspond to chapters of the Ada Reference Manual. For example,
23324 parsing of select statements can be found in @file{par-ch9.adb}.
23327 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23328 numbers correspond to chapters of the Ada standard. For example, all
23329 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23330 addition, some features of the language require sufficient special processing
23331 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23332 dynamic dispatching, etc.
23335 All files prefixed with @file{^exp^EXP^} perform normalization and
23336 expansion of the intermediate representation (abstract syntax tree, or AST).
23337 these files use the same numbering scheme as the parser and semantics files.
23338 For example, the construction of record initialization procedures is done in
23339 @file{exp_ch3.adb}.
23342 The files prefixed with @file{^bind^BIND^} implement the binder, which
23343 verifies the consistency of the compilation, determines an order of
23344 elaboration, and generates the bind file.
23347 The files @file{atree.ads} and @file{atree.adb} detail the low-level
23348 data structures used by the front-end.
23351 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
23352 the abstract syntax tree as produced by the parser.
23355 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
23356 all entities, computed during semantic analysis.
23359 Library management issues are dealt with in files with prefix
23365 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
23366 defined in Annex A.
23371 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23372 defined in Annex B.
23376 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23377 both language-defined children and GNAT run-time routines.
23381 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23382 general-purpose packages, fully documented in their specs. All
23383 the other @file{.c} files are modifications of common @command{gcc} files.
23386 @node Getting Internal Debugging Information
23387 @section Getting Internal Debugging Information
23390 Most compilers have internal debugging switches and modes. GNAT
23391 does also, except GNAT internal debugging switches and modes are not
23392 secret. A summary and full description of all the compiler and binder
23393 debug flags are in the file @file{debug.adb}. You must obtain the
23394 sources of the compiler to see the full detailed effects of these flags.
23396 The switches that print the source of the program (reconstructed from
23397 the internal tree) are of general interest for user programs, as are the
23399 the full internal tree, and the entity table (the symbol table
23400 information). The reconstructed source provides a readable version of the
23401 program after the front-end has completed analysis and expansion,
23402 and is useful when studying the performance of specific constructs.
23403 For example, constraint checks are indicated, complex aggregates
23404 are replaced with loops and assignments, and tasking primitives
23405 are replaced with run-time calls.
23407 @node Stack Traceback
23408 @section Stack Traceback
23410 @cindex stack traceback
23411 @cindex stack unwinding
23414 Traceback is a mechanism to display the sequence of subprogram calls that
23415 leads to a specified execution point in a program. Often (but not always)
23416 the execution point is an instruction at which an exception has been raised.
23417 This mechanism is also known as @i{stack unwinding} because it obtains
23418 its information by scanning the run-time stack and recovering the activation
23419 records of all active subprograms. Stack unwinding is one of the most
23420 important tools for program debugging.
23422 The first entry stored in traceback corresponds to the deepest calling level,
23423 that is to say the subprogram currently executing the instruction
23424 from which we want to obtain the traceback.
23426 Note that there is no runtime performance penalty when stack traceback
23427 is enabled, and no exception is raised during program execution.
23430 * Non-Symbolic Traceback::
23431 * Symbolic Traceback::
23434 @node Non-Symbolic Traceback
23435 @subsection Non-Symbolic Traceback
23436 @cindex traceback, non-symbolic
23439 Note: this feature is not supported on all platforms. See
23440 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
23444 * Tracebacks From an Unhandled Exception::
23445 * Tracebacks From Exception Occurrences (non-symbolic)::
23446 * Tracebacks From Anywhere in a Program (non-symbolic)::
23449 @node Tracebacks From an Unhandled Exception
23450 @subsubsection Tracebacks From an Unhandled Exception
23453 A runtime non-symbolic traceback is a list of addresses of call instructions.
23454 To enable this feature you must use the @option{-E}
23455 @code{gnatbind}'s option. With this option a stack traceback is stored as part
23456 of exception information. You can retrieve this information using the
23457 @code{addr2line} tool.
23459 Here is a simple example:
23461 @smallexample @c ada
23467 raise Constraint_Error;
23482 $ gnatmake stb -bargs -E
23485 Execution terminated by unhandled exception
23486 Exception name: CONSTRAINT_ERROR
23488 Call stack traceback locations:
23489 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23493 As we see the traceback lists a sequence of addresses for the unhandled
23494 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
23495 guess that this exception come from procedure P1. To translate these
23496 addresses into the source lines where the calls appear, the
23497 @code{addr2line} tool, described below, is invaluable. The use of this tool
23498 requires the program to be compiled with debug information.
23501 $ gnatmake -g stb -bargs -E
23504 Execution terminated by unhandled exception
23505 Exception name: CONSTRAINT_ERROR
23507 Call stack traceback locations:
23508 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23510 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
23511 0x4011f1 0x77e892a4
23513 00401373 at d:/stb/stb.adb:5
23514 0040138B at d:/stb/stb.adb:10
23515 0040139C at d:/stb/stb.adb:14
23516 00401335 at d:/stb/b~stb.adb:104
23517 004011C4 at /build/@dots{}/crt1.c:200
23518 004011F1 at /build/@dots{}/crt1.c:222
23519 77E892A4 in ?? at ??:0
23523 The @code{addr2line} tool has several other useful options:
23527 to get the function name corresponding to any location
23529 @item --demangle=gnat
23530 to use the gnat decoding mode for the function names. Note that
23531 for binutils version 2.9.x the option is simply @option{--demangle}.
23535 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
23536 0x40139c 0x401335 0x4011c4 0x4011f1
23538 00401373 in stb.p1 at d:/stb/stb.adb:5
23539 0040138B in stb.p2 at d:/stb/stb.adb:10
23540 0040139C in stb at d:/stb/stb.adb:14
23541 00401335 in main at d:/stb/b~stb.adb:104
23542 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
23543 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
23547 From this traceback we can see that the exception was raised in
23548 @file{stb.adb} at line 5, which was reached from a procedure call in
23549 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
23550 which contains the call to the main program.
23551 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
23552 and the output will vary from platform to platform.
23554 It is also possible to use @code{GDB} with these traceback addresses to debug
23555 the program. For example, we can break at a given code location, as reported
23556 in the stack traceback:
23562 Furthermore, this feature is not implemented inside Windows DLL. Only
23563 the non-symbolic traceback is reported in this case.
23566 (gdb) break *0x401373
23567 Breakpoint 1 at 0x401373: file stb.adb, line 5.
23571 It is important to note that the stack traceback addresses
23572 do not change when debug information is included. This is particularly useful
23573 because it makes it possible to release software without debug information (to
23574 minimize object size), get a field report that includes a stack traceback
23575 whenever an internal bug occurs, and then be able to retrieve the sequence
23576 of calls with the same program compiled with debug information.
23578 @node Tracebacks From Exception Occurrences (non-symbolic)
23579 @subsubsection Tracebacks From Exception Occurrences
23582 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
23583 The stack traceback is attached to the exception information string, and can
23584 be retrieved in an exception handler within the Ada program, by means of the
23585 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
23587 @smallexample @c ada
23589 with Ada.Exceptions;
23594 use Ada.Exceptions;
23602 Text_IO.Put_Line (Exception_Information (E));
23616 This program will output:
23621 Exception name: CONSTRAINT_ERROR
23622 Message: stb.adb:12
23623 Call stack traceback locations:
23624 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
23627 @node Tracebacks From Anywhere in a Program (non-symbolic)
23628 @subsubsection Tracebacks From Anywhere in a Program
23631 It is also possible to retrieve a stack traceback from anywhere in a
23632 program. For this you need to
23633 use the @code{GNAT.Traceback} API. This package includes a procedure called
23634 @code{Call_Chain} that computes a complete stack traceback, as well as useful
23635 display procedures described below. It is not necessary to use the
23636 @option{-E gnatbind} option in this case, because the stack traceback mechanism
23637 is invoked explicitly.
23640 In the following example we compute a traceback at a specific location in
23641 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
23642 convert addresses to strings:
23644 @smallexample @c ada
23646 with GNAT.Traceback;
23647 with GNAT.Debug_Utilities;
23653 use GNAT.Traceback;
23656 TB : Tracebacks_Array (1 .. 10);
23657 -- We are asking for a maximum of 10 stack frames.
23659 -- Len will receive the actual number of stack frames returned.
23661 Call_Chain (TB, Len);
23663 Text_IO.Put ("In STB.P1 : ");
23665 for K in 1 .. Len loop
23666 Text_IO.Put (Debug_Utilities.Image (TB (K)));
23687 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
23688 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
23692 You can then get further information by invoking the @code{addr2line}
23693 tool as described earlier (note that the hexadecimal addresses
23694 need to be specified in C format, with a leading ``0x'').
23696 @node Symbolic Traceback
23697 @subsection Symbolic Traceback
23698 @cindex traceback, symbolic
23701 A symbolic traceback is a stack traceback in which procedure names are
23702 associated with each code location.
23705 Note that this feature is not supported on all platforms. See
23706 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
23707 list of currently supported platforms.
23710 Note that the symbolic traceback requires that the program be compiled
23711 with debug information. If it is not compiled with debug information
23712 only the non-symbolic information will be valid.
23715 * Tracebacks From Exception Occurrences (symbolic)::
23716 * Tracebacks From Anywhere in a Program (symbolic)::
23719 @node Tracebacks From Exception Occurrences (symbolic)
23720 @subsubsection Tracebacks From Exception Occurrences
23722 @smallexample @c ada
23724 with GNAT.Traceback.Symbolic;
23730 raise Constraint_Error;
23747 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
23752 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
23755 0040149F in stb.p1 at stb.adb:8
23756 004014B7 in stb.p2 at stb.adb:13
23757 004014CF in stb.p3 at stb.adb:18
23758 004015DD in ada.stb at stb.adb:22
23759 00401461 in main at b~stb.adb:168
23760 004011C4 in __mingw_CRTStartup at crt1.c:200
23761 004011F1 in mainCRTStartup at crt1.c:222
23762 77E892A4 in ?? at ??:0
23766 In the above example the ``.\'' syntax in the @command{gnatmake} command
23767 is currently required by @command{addr2line} for files that are in
23768 the current working directory.
23769 Moreover, the exact sequence of linker options may vary from platform
23771 The above @option{-largs} section is for Windows platforms. By contrast,
23772 under Unix there is no need for the @option{-largs} section.
23773 Differences across platforms are due to details of linker implementation.
23775 @node Tracebacks From Anywhere in a Program (symbolic)
23776 @subsubsection Tracebacks From Anywhere in a Program
23779 It is possible to get a symbolic stack traceback
23780 from anywhere in a program, just as for non-symbolic tracebacks.
23781 The first step is to obtain a non-symbolic
23782 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
23783 information. Here is an example:
23785 @smallexample @c ada
23787 with GNAT.Traceback;
23788 with GNAT.Traceback.Symbolic;
23793 use GNAT.Traceback;
23794 use GNAT.Traceback.Symbolic;
23797 TB : Tracebacks_Array (1 .. 10);
23798 -- We are asking for a maximum of 10 stack frames.
23800 -- Len will receive the actual number of stack frames returned.
23802 Call_Chain (TB, Len);
23803 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
23816 @c ******************************
23818 @node Compatibility with HP Ada
23819 @chapter Compatibility with HP Ada
23820 @cindex Compatibility
23825 @cindex Compatibility between GNAT and HP Ada
23826 This chapter compares HP Ada (formerly known as ``DEC Ada'')
23827 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
23828 GNAT is highly compatible
23829 with HP Ada, and it should generally be straightforward to port code
23830 from the HP Ada environment to GNAT. However, there are a few language
23831 and implementation differences of which the user must be aware. These
23832 differences are discussed in this chapter. In
23833 addition, the operating environment and command structure for the
23834 compiler are different, and these differences are also discussed.
23836 For further details on these and other compatibility issues,
23837 see Appendix E of the HP publication
23838 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
23840 Except where otherwise indicated, the description of GNAT for OpenVMS
23841 applies to both the Alpha and I64 platforms.
23843 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
23844 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23846 The discussion in this chapter addresses specifically the implementation
23847 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
23848 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
23849 GNAT always follows the Alpha implementation.
23851 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
23852 attributes are recognized, although only a subset of them can sensibly
23853 be implemented. The description of pragmas in
23854 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
23855 indicates whether or not they are applicable to non-VMS systems.
23858 * Ada Language Compatibility::
23859 * Differences in the Definition of Package System::
23860 * Language-Related Features::
23861 * The Package STANDARD::
23862 * The Package SYSTEM::
23863 * Tasking and Task-Related Features::
23864 * Pragmas and Pragma-Related Features::
23865 * Library of Predefined Units::
23867 * Main Program Definition::
23868 * Implementation-Defined Attributes::
23869 * Compiler and Run-Time Interfacing::
23870 * Program Compilation and Library Management::
23872 * Implementation Limits::
23873 * Tools and Utilities::
23876 @node Ada Language Compatibility
23877 @section Ada Language Compatibility
23880 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23881 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23882 with Ada 83, and therefore Ada 83 programs will compile
23883 and run under GNAT with
23884 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23885 provides details on specific incompatibilities.
23887 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23888 as well as the pragma @code{ADA_83}, to force the compiler to
23889 operate in Ada 83 mode. This mode does not guarantee complete
23890 conformance to Ada 83, but in practice is sufficient to
23891 eliminate most sources of incompatibilities.
23892 In particular, it eliminates the recognition of the
23893 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23894 in Ada 83 programs is legal, and handles the cases of packages
23895 with optional bodies, and generics that instantiate unconstrained
23896 types without the use of @code{(<>)}.
23898 @node Differences in the Definition of Package System
23899 @section Differences in the Definition of Package @code{System}
23902 An Ada compiler is allowed to add
23903 implementation-dependent declarations to package @code{System}.
23905 GNAT does not take advantage of this permission, and the version of
23906 @code{System} provided by GNAT exactly matches that defined in the Ada
23909 However, HP Ada adds an extensive set of declarations to package
23911 as fully documented in the HP Ada manuals. To minimize changes required
23912 for programs that make use of these extensions, GNAT provides the pragma
23913 @code{Extend_System} for extending the definition of package System. By using:
23914 @cindex pragma @code{Extend_System}
23915 @cindex @code{Extend_System} pragma
23917 @smallexample @c ada
23920 pragma Extend_System (Aux_DEC);
23926 the set of definitions in @code{System} is extended to include those in
23927 package @code{System.Aux_DEC}.
23928 @cindex @code{System.Aux_DEC} package
23929 @cindex @code{Aux_DEC} package (child of @code{System})
23930 These definitions are incorporated directly into package @code{System},
23931 as though they had been declared there. For a
23932 list of the declarations added, see the spec of this package,
23933 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23934 @cindex @file{s-auxdec.ads} file
23935 The pragma @code{Extend_System} is a configuration pragma, which means that
23936 it can be placed in the file @file{gnat.adc}, so that it will automatically
23937 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23938 for further details.
23940 An alternative approach that avoids the use of the non-standard
23941 @code{Extend_System} pragma is to add a context clause to the unit that
23942 references these facilities:
23944 @smallexample @c ada
23946 with System.Aux_DEC;
23947 use System.Aux_DEC;
23952 The effect is not quite semantically identical to incorporating
23953 the declarations directly into package @code{System},
23954 but most programs will not notice a difference
23955 unless they use prefix notation (e.g.@: @code{System.Integer_8})
23956 to reference the entities directly in package @code{System}.
23957 For units containing such references,
23958 the prefixes must either be removed, or the pragma @code{Extend_System}
23961 @node Language-Related Features
23962 @section Language-Related Features
23965 The following sections highlight differences in types,
23966 representations of types, operations, alignment, and
23970 * Integer Types and Representations::
23971 * Floating-Point Types and Representations::
23972 * Pragmas Float_Representation and Long_Float::
23973 * Fixed-Point Types and Representations::
23974 * Record and Array Component Alignment::
23975 * Address Clauses::
23976 * Other Representation Clauses::
23979 @node Integer Types and Representations
23980 @subsection Integer Types and Representations
23983 The set of predefined integer types is identical in HP Ada and GNAT.
23984 Furthermore the representation of these integer types is also identical,
23985 including the capability of size clauses forcing biased representation.
23988 HP Ada for OpenVMS Alpha systems has defined the
23989 following additional integer types in package @code{System}:
24006 @code{LARGEST_INTEGER}
24010 In GNAT, the first four of these types may be obtained from the
24011 standard Ada package @code{Interfaces}.
24012 Alternatively, by use of the pragma @code{Extend_System}, identical
24013 declarations can be referenced directly in package @code{System}.
24014 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24016 @node Floating-Point Types and Representations
24017 @subsection Floating-Point Types and Representations
24018 @cindex Floating-Point types
24021 The set of predefined floating-point types is identical in HP Ada and GNAT.
24022 Furthermore the representation of these floating-point
24023 types is also identical. One important difference is that the default
24024 representation for HP Ada is @code{VAX_Float}, but the default representation
24027 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24028 pragma @code{Float_Representation} as described in the HP Ada
24030 For example, the declarations:
24032 @smallexample @c ada
24034 type F_Float is digits 6;
24035 pragma Float_Representation (VAX_Float, F_Float);
24040 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24042 This set of declarations actually appears in @code{System.Aux_DEC},
24044 the full set of additional floating-point declarations provided in
24045 the HP Ada version of package @code{System}.
24046 This and similar declarations may be accessed in a user program
24047 by using pragma @code{Extend_System}. The use of this
24048 pragma, and the related pragma @code{Long_Float} is described in further
24049 detail in the following section.
24051 @node Pragmas Float_Representation and Long_Float
24052 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24055 HP Ada provides the pragma @code{Float_Representation}, which
24056 acts as a program library switch to allow control over
24057 the internal representation chosen for the predefined
24058 floating-point types declared in the package @code{Standard}.
24059 The format of this pragma is as follows:
24061 @smallexample @c ada
24063 pragma Float_Representation(VAX_Float | IEEE_Float);
24068 This pragma controls the representation of floating-point
24073 @code{VAX_Float} specifies that floating-point
24074 types are represented by default with the VAX system hardware types
24075 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24076 Note that the @code{H-floating}
24077 type was available only on VAX systems, and is not available
24078 in either HP Ada or GNAT.
24081 @code{IEEE_Float} specifies that floating-point
24082 types are represented by default with the IEEE single and
24083 double floating-point types.
24087 GNAT provides an identical implementation of the pragma
24088 @code{Float_Representation}, except that it functions as a
24089 configuration pragma. Note that the
24090 notion of configuration pragma corresponds closely to the
24091 HP Ada notion of a program library switch.
24093 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24095 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24096 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24097 advisable to change the format of numbers passed to standard library
24098 routines, and if necessary explicit type conversions may be needed.
24100 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24101 efficient, and (given that it conforms to an international standard)
24102 potentially more portable.
24103 The situation in which @code{VAX_Float} may be useful is in interfacing
24104 to existing code and data that expect the use of @code{VAX_Float}.
24105 In such a situation use the predefined @code{VAX_Float}
24106 types in package @code{System}, as extended by
24107 @code{Extend_System}. For example, use @code{System.F_Float}
24108 to specify the 32-bit @code{F-Float} format.
24111 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24112 to allow control over the internal representation chosen
24113 for the predefined type @code{Long_Float} and for floating-point
24114 type declarations with digits specified in the range 7 .. 15.
24115 The format of this pragma is as follows:
24117 @smallexample @c ada
24119 pragma Long_Float (D_FLOAT | G_FLOAT);
24123 @node Fixed-Point Types and Representations
24124 @subsection Fixed-Point Types and Representations
24127 On HP Ada for OpenVMS Alpha systems, rounding is
24128 away from zero for both positive and negative numbers.
24129 Therefore, @code{+0.5} rounds to @code{1},
24130 and @code{-0.5} rounds to @code{-1}.
24132 On GNAT the results of operations
24133 on fixed-point types are in accordance with the Ada
24134 rules. In particular, results of operations on decimal
24135 fixed-point types are truncated.
24137 @node Record and Array Component Alignment
24138 @subsection Record and Array Component Alignment
24141 On HP Ada for OpenVMS Alpha, all non-composite components
24142 are aligned on natural boundaries. For example, 1-byte
24143 components are aligned on byte boundaries, 2-byte
24144 components on 2-byte boundaries, 4-byte components on 4-byte
24145 byte boundaries, and so on. The OpenVMS Alpha hardware
24146 runs more efficiently with naturally aligned data.
24148 On GNAT, alignment rules are compatible
24149 with HP Ada for OpenVMS Alpha.
24151 @node Address Clauses
24152 @subsection Address Clauses
24155 In HP Ada and GNAT, address clauses are supported for
24156 objects and imported subprograms.
24157 The predefined type @code{System.Address} is a private type
24158 in both compilers on Alpha OpenVMS, with the same representation
24159 (it is simply a machine pointer). Addition, subtraction, and comparison
24160 operations are available in the standard Ada package
24161 @code{System.Storage_Elements}, or in package @code{System}
24162 if it is extended to include @code{System.Aux_DEC} using a
24163 pragma @code{Extend_System} as previously described.
24165 Note that code that @code{with}'s both this extended package @code{System}
24166 and the package @code{System.Storage_Elements} should not @code{use}
24167 both packages, or ambiguities will result. In general it is better
24168 not to mix these two sets of facilities. The Ada package was
24169 designed specifically to provide the kind of features that HP Ada
24170 adds directly to package @code{System}.
24172 The type @code{System.Address} is a 64-bit integer type in GNAT for
24173 I64 OpenVMS. For more information,
24174 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24176 GNAT is compatible with HP Ada in its handling of address
24177 clauses, except for some limitations in
24178 the form of address clauses for composite objects with
24179 initialization. Such address clauses are easily replaced
24180 by the use of an explicitly-defined constant as described
24181 in the Ada Reference Manual (13.1(22)). For example, the sequence
24184 @smallexample @c ada
24186 X, Y : Integer := Init_Func;
24187 Q : String (X .. Y) := "abc";
24189 for Q'Address use Compute_Address;
24194 will be rejected by GNAT, since the address cannot be computed at the time
24195 that @code{Q} is declared. To achieve the intended effect, write instead:
24197 @smallexample @c ada
24200 X, Y : Integer := Init_Func;
24201 Q_Address : constant Address := Compute_Address;
24202 Q : String (X .. Y) := "abc";
24204 for Q'Address use Q_Address;
24210 which will be accepted by GNAT (and other Ada compilers), and is also
24211 compatible with Ada 83. A fuller description of the restrictions
24212 on address specifications is found in @ref{Top, GNAT Reference Manual,
24213 About This Guide, gnat_rm, GNAT Reference Manual}.
24215 @node Other Representation Clauses
24216 @subsection Other Representation Clauses
24219 GNAT implements in a compatible manner all the representation
24220 clauses supported by HP Ada. In addition, GNAT
24221 implements the representation clause forms that were introduced in Ada 95,
24222 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24224 @node The Package STANDARD
24225 @section The Package @code{STANDARD}
24228 The package @code{STANDARD}, as implemented by HP Ada, is fully
24229 described in the @cite{Ada Reference Manual} and in the
24230 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24231 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24233 In addition, HP Ada supports the Latin-1 character set in
24234 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24235 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24236 the type @code{WIDE_CHARACTER}.
24238 The floating-point types supported by GNAT are those
24239 supported by HP Ada, but the defaults are different, and are controlled by
24240 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24242 @node The Package SYSTEM
24243 @section The Package @code{SYSTEM}
24246 HP Ada provides a specific version of the package
24247 @code{SYSTEM} for each platform on which the language is implemented.
24248 For the complete spec of the package @code{SYSTEM}, see
24249 Appendix F of the @cite{HP Ada Language Reference Manual}.
24251 On HP Ada, the package @code{SYSTEM} includes the following conversion
24254 @item @code{TO_ADDRESS(INTEGER)}
24256 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24258 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24260 @item @code{TO_INTEGER(ADDRESS)}
24262 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24264 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24265 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24269 By default, GNAT supplies a version of @code{SYSTEM} that matches
24270 the definition given in the @cite{Ada Reference Manual}.
24272 is a subset of the HP system definitions, which is as
24273 close as possible to the original definitions. The only difference
24274 is that the definition of @code{SYSTEM_NAME} is different:
24276 @smallexample @c ada
24278 type Name is (SYSTEM_NAME_GNAT);
24279 System_Name : constant Name := SYSTEM_NAME_GNAT;
24284 Also, GNAT adds the Ada declarations for
24285 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24287 However, the use of the following pragma causes GNAT
24288 to extend the definition of package @code{SYSTEM} so that it
24289 encompasses the full set of HP-specific extensions,
24290 including the functions listed above:
24292 @smallexample @c ada
24294 pragma Extend_System (Aux_DEC);
24299 The pragma @code{Extend_System} is a configuration pragma that
24300 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24301 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24303 HP Ada does not allow the recompilation of the package
24304 @code{SYSTEM}. Instead HP Ada provides several pragmas
24305 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24306 to modify values in the package @code{SYSTEM}.
24307 On OpenVMS Alpha systems, the pragma
24308 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24309 its single argument.
24311 GNAT does permit the recompilation of package @code{SYSTEM} using
24312 the special switch @option{-gnatg}, and this switch can be used if
24313 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24314 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24315 or @code{MEMORY_SIZE} by any other means.
24317 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24318 enumeration literal @code{SYSTEM_NAME_GNAT}.
24320 The definitions provided by the use of
24322 @smallexample @c ada
24323 pragma Extend_System (AUX_Dec);
24327 are virtually identical to those provided by the HP Ada 83 package
24328 @code{SYSTEM}. One important difference is that the name of the
24330 function for type @code{UNSIGNED_LONGWORD} is changed to
24331 @code{TO_ADDRESS_LONG}.
24332 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24333 discussion of why this change was necessary.
24336 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24338 an extension to Ada 83 not strictly compatible with the reference manual.
24339 GNAT, in order to be exactly compatible with the standard,
24340 does not provide this capability. In HP Ada 83, the
24341 point of this definition is to deal with a call like:
24343 @smallexample @c ada
24344 TO_ADDRESS (16#12777#);
24348 Normally, according to Ada 83 semantics, one would expect this to be
24349 ambiguous, since it matches both the @code{INTEGER} and
24350 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
24351 However, in HP Ada 83, there is no ambiguity, since the
24352 definition using @i{universal_integer} takes precedence.
24354 In GNAT, since the version with @i{universal_integer} cannot be supplied,
24356 not possible to be 100% compatible. Since there are many programs using
24357 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
24359 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
24360 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
24362 @smallexample @c ada
24363 function To_Address (X : Integer) return Address;
24364 pragma Pure_Function (To_Address);
24366 function To_Address_Long (X : Unsigned_Longword) return Address;
24367 pragma Pure_Function (To_Address_Long);
24371 This means that programs using @code{TO_ADDRESS} for
24372 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24374 @node Tasking and Task-Related Features
24375 @section Tasking and Task-Related Features
24378 This section compares the treatment of tasking in GNAT
24379 and in HP Ada for OpenVMS Alpha.
24380 The GNAT description applies to both Alpha and I64 OpenVMS.
24381 For detailed information on tasking in
24382 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24383 relevant run-time reference manual.
24386 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24387 * Assigning Task IDs::
24388 * Task IDs and Delays::
24389 * Task-Related Pragmas::
24390 * Scheduling and Task Priority::
24392 * External Interrupts::
24395 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24396 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24399 On OpenVMS Alpha systems, each Ada task (except a passive
24400 task) is implemented as a single stream of execution
24401 that is created and managed by the kernel. On these
24402 systems, HP Ada tasking support is based on DECthreads,
24403 an implementation of the POSIX standard for threads.
24405 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24406 code that calls DECthreads routines can be used together.
24407 The interaction between Ada tasks and DECthreads routines
24408 can have some benefits. For example when on OpenVMS Alpha,
24409 HP Ada can call C code that is already threaded.
24411 GNAT uses the facilities of DECthreads,
24412 and Ada tasks are mapped to threads.
24414 @node Assigning Task IDs
24415 @subsection Assigning Task IDs
24418 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24419 the environment task that executes the main program. On
24420 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24421 that have been created but are not yet activated.
24423 On OpenVMS Alpha systems, task IDs are assigned at
24424 activation. On GNAT systems, task IDs are also assigned at
24425 task creation but do not have the same form or values as
24426 task ID values in HP Ada. There is no null task, and the
24427 environment task does not have a specific task ID value.
24429 @node Task IDs and Delays
24430 @subsection Task IDs and Delays
24433 On OpenVMS Alpha systems, tasking delays are implemented
24434 using Timer System Services. The Task ID is used for the
24435 identification of the timer request (the @code{REQIDT} parameter).
24436 If Timers are used in the application take care not to use
24437 @code{0} for the identification, because cancelling such a timer
24438 will cancel all timers and may lead to unpredictable results.
24440 @node Task-Related Pragmas
24441 @subsection Task-Related Pragmas
24444 Ada supplies the pragma @code{TASK_STORAGE}, which allows
24445 specification of the size of the guard area for a task
24446 stack. (The guard area forms an area of memory that has no
24447 read or write access and thus helps in the detection of
24448 stack overflow.) On OpenVMS Alpha systems, if the pragma
24449 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
24450 area is created. In the absence of a pragma @code{TASK_STORAGE},
24451 a default guard area is created.
24453 GNAT supplies the following task-related pragmas:
24456 @item @code{TASK_INFO}
24458 This pragma appears within a task definition and
24459 applies to the task in which it appears. The argument
24460 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
24462 @item @code{TASK_STORAGE}
24464 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
24465 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
24466 @code{SUPPRESS}, and @code{VOLATILE}.
24468 @node Scheduling and Task Priority
24469 @subsection Scheduling and Task Priority
24472 HP Ada implements the Ada language requirement that
24473 when two tasks are eligible for execution and they have
24474 different priorities, the lower priority task does not
24475 execute while the higher priority task is waiting. The HP
24476 Ada Run-Time Library keeps a task running until either the
24477 task is suspended or a higher priority task becomes ready.
24479 On OpenVMS Alpha systems, the default strategy is round-
24480 robin with preemption. Tasks of equal priority take turns
24481 at the processor. A task is run for a certain period of
24482 time and then placed at the tail of the ready queue for
24483 its priority level.
24485 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
24486 which can be used to enable or disable round-robin
24487 scheduling of tasks with the same priority.
24488 See the relevant HP Ada run-time reference manual for
24489 information on using the pragmas to control HP Ada task
24492 GNAT follows the scheduling rules of Annex D (Real-Time
24493 Annex) of the @cite{Ada Reference Manual}. In general, this
24494 scheduling strategy is fully compatible with HP Ada
24495 although it provides some additional constraints (as
24496 fully documented in Annex D).
24497 GNAT implements time slicing control in a manner compatible with
24498 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
24499 are identical to the HP Ada 83 pragma of the same name.
24500 Note that it is not possible to mix GNAT tasking and
24501 HP Ada 83 tasking in the same program, since the two run-time
24502 libraries are not compatible.
24504 @node The Task Stack
24505 @subsection The Task Stack
24508 In HP Ada, a task stack is allocated each time a
24509 non-passive task is activated. As soon as the task is
24510 terminated, the storage for the task stack is deallocated.
24511 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
24512 a default stack size is used. Also, regardless of the size
24513 specified, some additional space is allocated for task
24514 management purposes. On OpenVMS Alpha systems, at least
24515 one page is allocated.
24517 GNAT handles task stacks in a similar manner. In accordance with
24518 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
24519 an alternative method for controlling the task stack size.
24520 The specification of the attribute @code{T'STORAGE_SIZE} is also
24521 supported in a manner compatible with HP Ada.
24523 @node External Interrupts
24524 @subsection External Interrupts
24527 On HP Ada, external interrupts can be associated with task entries.
24528 GNAT is compatible with HP Ada in its handling of external interrupts.
24530 @node Pragmas and Pragma-Related Features
24531 @section Pragmas and Pragma-Related Features
24534 Both HP Ada and GNAT supply all language-defined pragmas
24535 as specified by the Ada 83 standard. GNAT also supplies all
24536 language-defined pragmas introduced by Ada 95 and Ada 2005.
24537 In addition, GNAT implements the implementation-defined pragmas
24541 @item @code{AST_ENTRY}
24543 @item @code{COMMON_OBJECT}
24545 @item @code{COMPONENT_ALIGNMENT}
24547 @item @code{EXPORT_EXCEPTION}
24549 @item @code{EXPORT_FUNCTION}
24551 @item @code{EXPORT_OBJECT}
24553 @item @code{EXPORT_PROCEDURE}
24555 @item @code{EXPORT_VALUED_PROCEDURE}
24557 @item @code{FLOAT_REPRESENTATION}
24561 @item @code{IMPORT_EXCEPTION}
24563 @item @code{IMPORT_FUNCTION}
24565 @item @code{IMPORT_OBJECT}
24567 @item @code{IMPORT_PROCEDURE}
24569 @item @code{IMPORT_VALUED_PROCEDURE}
24571 @item @code{INLINE_GENERIC}
24573 @item @code{INTERFACE_NAME}
24575 @item @code{LONG_FLOAT}
24577 @item @code{MAIN_STORAGE}
24579 @item @code{PASSIVE}
24581 @item @code{PSECT_OBJECT}
24583 @item @code{SHARE_GENERIC}
24585 @item @code{SUPPRESS_ALL}
24587 @item @code{TASK_STORAGE}
24589 @item @code{TIME_SLICE}
24595 These pragmas are all fully implemented, with the exception of @code{TITLE},
24596 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
24597 recognized, but which have no
24598 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
24599 use of Ada protected objects. In GNAT, all generics are inlined.
24601 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
24602 a separate subprogram specification which must appear before the
24605 GNAT also supplies a number of implementation-defined pragmas as follows:
24607 @item @code{ABORT_DEFER}
24609 @item @code{ADA_83}
24611 @item @code{ADA_95}
24613 @item @code{ADA_05}
24615 @item @code{ANNOTATE}
24617 @item @code{ASSERT}
24619 @item @code{C_PASS_BY_COPY}
24621 @item @code{CPP_CLASS}
24623 @item @code{CPP_CONSTRUCTOR}
24625 @item @code{CPP_DESTRUCTOR}
24629 @item @code{EXTEND_SYSTEM}
24631 @item @code{LINKER_ALIAS}
24633 @item @code{LINKER_SECTION}
24635 @item @code{MACHINE_ATTRIBUTE}
24637 @item @code{NO_RETURN}
24639 @item @code{PURE_FUNCTION}
24641 @item @code{SOURCE_FILE_NAME}
24643 @item @code{SOURCE_REFERENCE}
24645 @item @code{TASK_INFO}
24647 @item @code{UNCHECKED_UNION}
24649 @item @code{UNIMPLEMENTED_UNIT}
24651 @item @code{UNIVERSAL_DATA}
24653 @item @code{UNSUPPRESS}
24655 @item @code{WARNINGS}
24657 @item @code{WEAK_EXTERNAL}
24661 For full details on these GNAT implementation-defined pragmas,
24662 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
24666 * Restrictions on the Pragma INLINE::
24667 * Restrictions on the Pragma INTERFACE::
24668 * Restrictions on the Pragma SYSTEM_NAME::
24671 @node Restrictions on the Pragma INLINE
24672 @subsection Restrictions on Pragma @code{INLINE}
24675 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
24677 @item Parameters cannot have a task type.
24679 @item Function results cannot be task types, unconstrained
24680 array types, or unconstrained types with discriminants.
24682 @item Bodies cannot declare the following:
24684 @item Subprogram body or stub (imported subprogram is allowed)
24688 @item Generic declarations
24690 @item Instantiations
24694 @item Access types (types derived from access types allowed)
24696 @item Array or record types
24698 @item Dependent tasks
24700 @item Direct recursive calls of subprogram or containing
24701 subprogram, directly or via a renaming
24707 In GNAT, the only restriction on pragma @code{INLINE} is that the
24708 body must occur before the call if both are in the same
24709 unit, and the size must be appropriately small. There are
24710 no other specific restrictions which cause subprograms to
24711 be incapable of being inlined.
24713 @node Restrictions on the Pragma INTERFACE
24714 @subsection Restrictions on Pragma @code{INTERFACE}
24717 The following restrictions on pragma @code{INTERFACE}
24718 are enforced by both HP Ada and GNAT:
24720 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
24721 Default is the default on OpenVMS Alpha systems.
24723 @item Parameter passing: Language specifies default
24724 mechanisms but can be overridden with an @code{EXPORT} pragma.
24727 @item Ada: Use internal Ada rules.
24729 @item Bliss, C: Parameters must be mode @code{in}; cannot be
24730 record or task type. Result cannot be a string, an
24731 array, or a record.
24733 @item Fortran: Parameters cannot have a task type. Result cannot
24734 be a string, an array, or a record.
24739 GNAT is entirely upwards compatible with HP Ada, and in addition allows
24740 record parameters for all languages.
24742 @node Restrictions on the Pragma SYSTEM_NAME
24743 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
24746 For HP Ada for OpenVMS Alpha, the enumeration literal
24747 for the type @code{NAME} is @code{OPENVMS_AXP}.
24748 In GNAT, the enumeration
24749 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
24751 @node Library of Predefined Units
24752 @section Library of Predefined Units
24755 A library of predefined units is provided as part of the
24756 HP Ada and GNAT implementations. HP Ada does not provide
24757 the package @code{MACHINE_CODE} but instead recommends importing
24760 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
24761 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
24763 The HP Ada Predefined Library units are modified to remove post-Ada 83
24764 incompatibilities and to make them interoperable with GNAT
24765 (@pxref{Changes to DECLIB}, for details).
24766 The units are located in the @file{DECLIB} directory.
24768 The GNAT RTL is contained in
24769 the @file{ADALIB} directory, and
24770 the default search path is set up to find @code{DECLIB} units in preference
24771 to @code{ADALIB} units with the same name (@code{TEXT_IO},
24772 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
24775 * Changes to DECLIB::
24778 @node Changes to DECLIB
24779 @subsection Changes to @code{DECLIB}
24782 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
24783 compatibility are minor and include the following:
24786 @item Adjusting the location of pragmas and record representation
24787 clauses to obey Ada 95 (and thus Ada 2005) rules
24789 @item Adding the proper notation to generic formal parameters
24790 that take unconstrained types in instantiation
24792 @item Adding pragma @code{ELABORATE_BODY} to package specs
24793 that have package bodies not otherwise allowed
24795 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
24796 ``@code{PROTECTD}''.
24797 Currently these are found only in the @code{STARLET} package spec.
24799 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
24800 where the address size is constrained to 32 bits.
24804 None of the above changes is visible to users.
24810 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
24813 @item Command Language Interpreter (CLI interface)
24815 @item DECtalk Run-Time Library (DTK interface)
24817 @item Librarian utility routines (LBR interface)
24819 @item General Purpose Run-Time Library (LIB interface)
24821 @item Math Run-Time Library (MTH interface)
24823 @item National Character Set Run-Time Library (NCS interface)
24825 @item Compiled Code Support Run-Time Library (OTS interface)
24827 @item Parallel Processing Run-Time Library (PPL interface)
24829 @item Screen Management Run-Time Library (SMG interface)
24831 @item Sort Run-Time Library (SOR interface)
24833 @item String Run-Time Library (STR interface)
24835 @item STARLET System Library
24838 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
24840 @item X Windows Toolkit (XT interface)
24842 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
24846 GNAT provides implementations of these HP bindings in the @code{DECLIB}
24847 directory, on both the Alpha and I64 OpenVMS platforms.
24849 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
24851 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
24852 A pragma @code{Linker_Options} has been added to packages @code{Xm},
24853 @code{Xt}, and @code{X_Lib}
24854 causing the default X/Motif sharable image libraries to be linked in. This
24855 is done via options files named @file{xm.opt}, @file{xt.opt}, and
24856 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
24858 It may be necessary to edit these options files to update or correct the
24859 library names if, for example, the newer X/Motif bindings from
24860 @file{ADA$EXAMPLES}
24861 had been (previous to installing GNAT) copied and renamed to supersede the
24862 default @file{ADA$PREDEFINED} versions.
24865 * Shared Libraries and Options Files::
24866 * Interfaces to C::
24869 @node Shared Libraries and Options Files
24870 @subsection Shared Libraries and Options Files
24873 When using the HP Ada
24874 predefined X and Motif bindings, the linking with their sharable images is
24875 done automatically by @command{GNAT LINK}.
24876 When using other X and Motif bindings, you need
24877 to add the corresponding sharable images to the command line for
24878 @code{GNAT LINK}. When linking with shared libraries, or with
24879 @file{.OPT} files, you must
24880 also add them to the command line for @command{GNAT LINK}.
24882 A shared library to be used with GNAT is built in the same way as other
24883 libraries under VMS. The VMS Link command can be used in standard fashion.
24885 @node Interfaces to C
24886 @subsection Interfaces to C
24890 provides the following Ada types and operations:
24893 @item C types package (@code{C_TYPES})
24895 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24897 @item Other_types (@code{SHORT_INT})
24901 Interfacing to C with GNAT, you can use the above approach
24902 described for HP Ada or the facilities of Annex B of
24903 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24904 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24905 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
24907 The @option{-gnatF} qualifier forces default and explicit
24908 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24909 to be uppercased for compatibility with the default behavior
24910 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24912 @node Main Program Definition
24913 @section Main Program Definition
24916 The following section discusses differences in the
24917 definition of main programs on HP Ada and GNAT.
24918 On HP Ada, main programs are defined to meet the
24919 following conditions:
24921 @item Procedure with no formal parameters (returns @code{0} upon
24924 @item Procedure with no formal parameters (returns @code{42} when
24925 an unhandled exception is raised)
24927 @item Function with no formal parameters whose returned value
24928 is of a discrete type
24930 @item Procedure with one @code{out} formal of a discrete type for
24931 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
24936 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24937 a main function or main procedure returns a discrete
24938 value whose size is less than 64 bits (32 on VAX systems),
24939 the value is zero- or sign-extended as appropriate.
24940 On GNAT, main programs are defined as follows:
24942 @item Must be a non-generic, parameterless subprogram that
24943 is either a procedure or function returning an Ada
24944 @code{STANDARD.INTEGER} (the predefined type)
24946 @item Cannot be a generic subprogram or an instantiation of a
24950 @node Implementation-Defined Attributes
24951 @section Implementation-Defined Attributes
24954 GNAT provides all HP Ada implementation-defined
24957 @node Compiler and Run-Time Interfacing
24958 @section Compiler and Run-Time Interfacing
24961 HP Ada provides the following qualifiers to pass options to the linker
24964 @item @option{/WAIT} and @option{/SUBMIT}
24966 @item @option{/COMMAND}
24968 @item @option{/@r{[}NO@r{]}MAP}
24970 @item @option{/OUTPUT=@var{file-spec}}
24972 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
24976 To pass options to the linker, GNAT provides the following
24980 @item @option{/EXECUTABLE=@var{exec-name}}
24982 @item @option{/VERBOSE}
24984 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
24988 For more information on these switches, see
24989 @ref{Switches for gnatlink}.
24990 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
24991 to control optimization. HP Ada also supplies the
24994 @item @code{OPTIMIZE}
24996 @item @code{INLINE}
24998 @item @code{INLINE_GENERIC}
25000 @item @code{SUPPRESS_ALL}
25002 @item @code{PASSIVE}
25006 In GNAT, optimization is controlled strictly by command
25007 line parameters, as described in the corresponding section of this guide.
25008 The HP pragmas for control of optimization are
25009 recognized but ignored.
25011 Note that in GNAT, the default is optimization off, whereas in HP Ada
25012 the default is that optimization is turned on.
25014 @node Program Compilation and Library Management
25015 @section Program Compilation and Library Management
25018 HP Ada and GNAT provide a comparable set of commands to
25019 build programs. HP Ada also provides a program library,
25020 which is a concept that does not exist on GNAT. Instead,
25021 GNAT provides directories of sources that are compiled as
25024 The following table summarizes
25025 the HP Ada commands and provides
25026 equivalent GNAT commands. In this table, some GNAT
25027 equivalents reflect the fact that GNAT does not use the
25028 concept of a program library. Instead, it uses a model
25029 in which collections of source and object files are used
25030 in a manner consistent with other languages like C and
25031 Fortran. Therefore, standard system file commands are used
25032 to manipulate these elements. Those GNAT commands are marked with
25034 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25037 @multitable @columnfractions .35 .65
25039 @item @emph{HP Ada Command}
25040 @tab @emph{GNAT Equivalent / Description}
25042 @item @command{ADA}
25043 @tab @command{GNAT COMPILE}@*
25044 Invokes the compiler to compile one or more Ada source files.
25046 @item @command{ACS ATTACH}@*
25047 @tab [No equivalent]@*
25048 Switches control of terminal from current process running the program
25051 @item @command{ACS CHECK}
25052 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25053 Forms the execution closure of one
25054 or more compiled units and checks completeness and currency.
25056 @item @command{ACS COMPILE}
25057 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25058 Forms the execution closure of one or
25059 more specified units, checks completeness and currency,
25060 identifies units that have revised source files, compiles same,
25061 and recompiles units that are or will become obsolete.
25062 Also completes incomplete generic instantiations.
25064 @item @command{ACS COPY FOREIGN}
25066 Copies a foreign object file into the program library as a
25069 @item @command{ACS COPY UNIT}
25071 Copies a compiled unit from one program library to another.
25073 @item @command{ACS CREATE LIBRARY}
25074 @tab Create /directory (*)@*
25075 Creates a program library.
25077 @item @command{ACS CREATE SUBLIBRARY}
25078 @tab Create /directory (*)@*
25079 Creates a program sublibrary.
25081 @item @command{ACS DELETE LIBRARY}
25083 Deletes a program library and its contents.
25085 @item @command{ACS DELETE SUBLIBRARY}
25087 Deletes a program sublibrary and its contents.
25089 @item @command{ACS DELETE UNIT}
25090 @tab Delete file (*)@*
25091 On OpenVMS systems, deletes one or more compiled units from
25092 the current program library.
25094 @item @command{ACS DIRECTORY}
25095 @tab Directory (*)@*
25096 On OpenVMS systems, lists units contained in the current
25099 @item @command{ACS ENTER FOREIGN}
25101 Allows the import of a foreign body as an Ada library
25102 spec and enters a reference to a pointer.
25104 @item @command{ACS ENTER UNIT}
25106 Enters a reference (pointer) from the current program library to
25107 a unit compiled into another program library.
25109 @item @command{ACS EXIT}
25110 @tab [No equivalent]@*
25111 Exits from the program library manager.
25113 @item @command{ACS EXPORT}
25115 Creates an object file that contains system-specific object code
25116 for one or more units. With GNAT, object files can simply be copied
25117 into the desired directory.
25119 @item @command{ACS EXTRACT SOURCE}
25121 Allows access to the copied source file for each Ada compilation unit
25123 @item @command{ACS HELP}
25124 @tab @command{HELP GNAT}@*
25125 Provides online help.
25127 @item @command{ACS LINK}
25128 @tab @command{GNAT LINK}@*
25129 Links an object file containing Ada units into an executable file.
25131 @item @command{ACS LOAD}
25133 Loads (partially compiles) Ada units into the program library.
25134 Allows loading a program from a collection of files into a library
25135 without knowing the relationship among units.
25137 @item @command{ACS MERGE}
25139 Merges into the current program library, one or more units from
25140 another library where they were modified.
25142 @item @command{ACS RECOMPILE}
25143 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25144 Recompiles from external or copied source files any obsolete
25145 unit in the closure. Also, completes any incomplete generic
25148 @item @command{ACS REENTER}
25149 @tab @command{GNAT MAKE}@*
25150 Reenters current references to units compiled after last entered
25151 with the @command{ACS ENTER UNIT} command.
25153 @item @command{ACS SET LIBRARY}
25154 @tab Set default (*)@*
25155 Defines a program library to be the compilation context as well
25156 as the target library for compiler output and commands in general.
25158 @item @command{ACS SET PRAGMA}
25159 @tab Edit @file{gnat.adc} (*)@*
25160 Redefines specified values of the library characteristics
25161 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25162 and @code{Float_Representation}.
25164 @item @command{ACS SET SOURCE}
25165 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25166 Defines the source file search list for the @command{ACS COMPILE} command.
25168 @item @command{ACS SHOW LIBRARY}
25169 @tab Directory (*)@*
25170 Lists information about one or more program libraries.
25172 @item @command{ACS SHOW PROGRAM}
25173 @tab [No equivalent]@*
25174 Lists information about the execution closure of one or
25175 more units in the program library.
25177 @item @command{ACS SHOW SOURCE}
25178 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25179 Shows the source file search used when compiling units.
25181 @item @command{ACS SHOW VERSION}
25182 @tab Compile with @option{VERBOSE} option
25183 Displays the version number of the compiler and program library
25186 @item @command{ACS SPAWN}
25187 @tab [No equivalent]@*
25188 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25191 @item @command{ACS VERIFY}
25192 @tab [No equivalent]@*
25193 Performs a series of consistency checks on a program library to
25194 determine whether the library structure and library files are in
25201 @section Input-Output
25204 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25205 Management Services (RMS) to perform operations on
25209 HP Ada and GNAT predefine an identical set of input-
25210 output packages. To make the use of the
25211 generic @code{TEXT_IO} operations more convenient, HP Ada
25212 provides predefined library packages that instantiate the
25213 integer and floating-point operations for the predefined
25214 integer and floating-point types as shown in the following table.
25216 @multitable @columnfractions .45 .55
25217 @item @emph{Package Name} @tab Instantiation
25219 @item @code{INTEGER_TEXT_IO}
25220 @tab @code{INTEGER_IO(INTEGER)}
25222 @item @code{SHORT_INTEGER_TEXT_IO}
25223 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25225 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25226 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25228 @item @code{FLOAT_TEXT_IO}
25229 @tab @code{FLOAT_IO(FLOAT)}
25231 @item @code{LONG_FLOAT_TEXT_IO}
25232 @tab @code{FLOAT_IO(LONG_FLOAT)}
25236 The HP Ada predefined packages and their operations
25237 are implemented using OpenVMS Alpha files and input-output
25238 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25239 Familiarity with the following is recommended:
25241 @item RMS file organizations and access methods
25243 @item OpenVMS file specifications and directories
25245 @item OpenVMS File Definition Language (FDL)
25249 GNAT provides I/O facilities that are completely
25250 compatible with HP Ada. The distribution includes the
25251 standard HP Ada versions of all I/O packages, operating
25252 in a manner compatible with HP Ada. In particular, the
25253 following packages are by default the HP Ada (Ada 83)
25254 versions of these packages rather than the renamings
25255 suggested in Annex J of the Ada Reference Manual:
25257 @item @code{TEXT_IO}
25259 @item @code{SEQUENTIAL_IO}
25261 @item @code{DIRECT_IO}
25265 The use of the standard child package syntax (for
25266 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25268 GNAT provides HP-compatible predefined instantiations
25269 of the @code{TEXT_IO} packages, and also
25270 provides the standard predefined instantiations required
25271 by the @cite{Ada Reference Manual}.
25273 For further information on how GNAT interfaces to the file
25274 system or how I/O is implemented in programs written in
25275 mixed languages, see @ref{Implementation of the Standard I/O,,,
25276 gnat_rm, GNAT Reference Manual}.
25277 This chapter covers the following:
25279 @item Standard I/O packages
25281 @item @code{FORM} strings
25283 @item @code{ADA.DIRECT_IO}
25285 @item @code{ADA.SEQUENTIAL_IO}
25287 @item @code{ADA.TEXT_IO}
25289 @item Stream pointer positioning
25291 @item Reading and writing non-regular files
25293 @item @code{GET_IMMEDIATE}
25295 @item Treating @code{TEXT_IO} files as streams
25302 @node Implementation Limits
25303 @section Implementation Limits
25306 The following table lists implementation limits for HP Ada
25308 @multitable @columnfractions .60 .20 .20
25310 @item @emph{Compilation Parameter}
25315 @item In a subprogram or entry declaration, maximum number of
25316 formal parameters that are of an unconstrained record type
25321 @item Maximum identifier length (number of characters)
25326 @item Maximum number of characters in a source line
25331 @item Maximum collection size (number of bytes)
25336 @item Maximum number of discriminants for a record type
25341 @item Maximum number of formal parameters in an entry or
25342 subprogram declaration
25347 @item Maximum number of dimensions in an array type
25352 @item Maximum number of library units and subunits in a compilation.
25357 @item Maximum number of library units and subunits in an execution.
25362 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
25363 or @code{PSECT_OBJECT}
25368 @item Maximum number of enumeration literals in an enumeration type
25374 @item Maximum number of lines in a source file
25379 @item Maximum number of bits in any object
25384 @item Maximum size of the static portion of a stack frame (approximate)
25389 @node Tools and Utilities
25390 @section Tools and Utilities
25393 The following table lists some of the OpenVMS development tools
25394 available for HP Ada, and the corresponding tools for
25395 use with @value{EDITION} on Alpha and I64 platforms.
25396 Aside from the debugger, all the OpenVMS tools identified are part
25397 of the DECset package.
25400 @c Specify table in TeX since Texinfo does a poor job
25404 \settabs\+Language-Sensitive Editor\quad
25405 &Product with HP Ada\quad
25408 &\it Product with HP Ada
25409 & \it Product with GNAT Pro\cr
25411 \+Code Management System
25415 \+Language-Sensitive Editor
25417 & emacs or HP LSE (Alpha)\cr
25427 & OpenVMS Debug (I64)\cr
25429 \+Source Code Analyzer /
25446 \+Coverage Analyzer
25450 \+Module Management
25452 & Not applicable\cr
25462 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
25463 @c the TeX version above for the printed version
25465 @c @multitable @columnfractions .3 .4 .4
25466 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
25468 @tab @i{Tool with HP Ada}
25469 @tab @i{Tool with @value{EDITION}}
25470 @item Code Management@*System
25473 @item Language-Sensitive@*Editor
25475 @tab emacs or HP LSE (Alpha)
25484 @tab OpenVMS Debug (I64)
25485 @item Source Code Analyzer /@*Cross Referencer
25489 @tab HP Digital Test@*Manager (DTM)
25491 @item Performance and@*Coverage Analyzer
25494 @item Module Management@*System
25496 @tab Not applicable
25503 @c **************************************
25504 @node Platform-Specific Information for the Run-Time Libraries
25505 @appendix Platform-Specific Information for the Run-Time Libraries
25506 @cindex Tasking and threads libraries
25507 @cindex Threads libraries and tasking
25508 @cindex Run-time libraries (platform-specific information)
25511 The GNAT run-time implementation may vary with respect to both the
25512 underlying threads library and the exception handling scheme.
25513 For threads support, one or more of the following are supplied:
25515 @item @b{native threads library}, a binding to the thread package from
25516 the underlying operating system
25518 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
25519 POSIX thread package
25523 For exception handling, either or both of two models are supplied:
25525 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
25526 Most programs should experience a substantial speed improvement by
25527 being compiled with a ZCX run-time.
25528 This is especially true for
25529 tasking applications or applications with many exception handlers.}
25530 @cindex Zero-Cost Exceptions
25531 @cindex ZCX (Zero-Cost Exceptions)
25532 which uses binder-generated tables that
25533 are interrogated at run time to locate a handler
25535 @item @b{setjmp / longjmp} (``SJLJ''),
25536 @cindex setjmp/longjmp Exception Model
25537 @cindex SJLJ (setjmp/longjmp Exception Model)
25538 which uses dynamically-set data to establish
25539 the set of handlers
25543 This appendix summarizes which combinations of threads and exception support
25544 are supplied on various GNAT platforms.
25545 It then shows how to select a particular library either
25546 permanently or temporarily,
25547 explains the properties of (and tradeoffs among) the various threads
25548 libraries, and provides some additional
25549 information about several specific platforms.
25552 * Summary of Run-Time Configurations::
25553 * Specifying a Run-Time Library::
25554 * Choosing the Scheduling Policy::
25555 * Solaris-Specific Considerations::
25556 * Linux-Specific Considerations::
25557 * AIX-Specific Considerations::
25558 * Irix-Specific Considerations::
25559 * RTX-Specific Considerations::
25562 @node Summary of Run-Time Configurations
25563 @section Summary of Run-Time Configurations
25565 @multitable @columnfractions .30 .70
25566 @item @b{alpha-openvms}
25567 @item @code{@ @ }@i{rts-native (default)}
25568 @item @code{@ @ @ @ }Tasking @tab native VMS threads
25569 @item @code{@ @ @ @ }Exceptions @tab ZCX
25571 @item @b{alpha-tru64}
25572 @item @code{@ @ }@i{rts-native (default)}
25573 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
25574 @item @code{@ @ @ @ }Exceptions @tab ZCX
25576 @item @code{@ @ }@i{rts-sjlj}
25577 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
25578 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25580 @item @b{ia64-hp_linux}
25581 @item @code{@ @ }@i{rts-native (default)}
25582 @item @code{@ @ @ @ }Tasking @tab pthread library
25583 @item @code{@ @ @ @ }Exceptions @tab ZCX
25585 @item @b{ia64-hpux}
25586 @item @code{@ @ }@i{rts-native (default)}
25587 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
25588 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25590 @item @b{ia64-openvms}
25591 @item @code{@ @ }@i{rts-native (default)}
25592 @item @code{@ @ @ @ }Tasking @tab native VMS threads
25593 @item @code{@ @ @ @ }Exceptions @tab ZCX
25595 @item @b{ia64-sgi_linux}
25596 @item @code{@ @ }@i{rts-native (default)}
25597 @item @code{@ @ @ @ }Tasking @tab pthread library
25598 @item @code{@ @ @ @ }Exceptions @tab ZCX
25600 @item @b{mips-irix}
25601 @item @code{@ @ }@i{rts-native (default)}
25602 @item @code{@ @ @ @ }Tasking @tab native IRIX threads
25603 @item @code{@ @ @ @ }Exceptions @tab ZCX
25606 @item @code{@ @ }@i{rts-native (default)}
25607 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
25608 @item @code{@ @ @ @ }Exceptions @tab ZCX
25610 @item @code{@ @ }@i{rts-sjlj}
25611 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
25612 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25615 @item @code{@ @ }@i{rts-native (default)}
25616 @item @code{@ @ @ @ }Tasking @tab native AIX threads
25617 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25619 @item @b{ppc-darwin}
25620 @item @code{@ @ }@i{rts-native (default)}
25621 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
25622 @item @code{@ @ @ @ }Exceptions @tab ZCX
25624 @item @b{sparc-solaris} @tab
25625 @item @code{@ @ }@i{rts-native (default)}
25626 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
25627 @item @code{@ @ @ @ }Exceptions @tab ZCX
25629 @item @code{@ @ }@i{rts-pthread}
25630 @item @code{@ @ @ @ }Tasking @tab pthread library
25631 @item @code{@ @ @ @ }Exceptions @tab ZCX
25633 @item @code{@ @ }@i{rts-sjlj}
25634 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
25635 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25637 @item @b{sparc64-solaris} @tab
25638 @item @code{@ @ }@i{rts-native (default)}
25639 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
25640 @item @code{@ @ @ @ }Exceptions @tab ZCX
25642 @item @b{x86-linux}
25643 @item @code{@ @ }@i{rts-native (default)}
25644 @item @code{@ @ @ @ }Tasking @tab pthread library
25645 @item @code{@ @ @ @ }Exceptions @tab ZCX
25647 @item @code{@ @ }@i{rts-sjlj}
25648 @item @code{@ @ @ @ }Tasking @tab pthread library
25649 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25652 @item @code{@ @ }@i{rts-native (default)}
25653 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
25654 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25656 @item @b{x86-solaris}
25657 @item @code{@ @ }@i{rts-native (default)}
25658 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
25659 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25661 @item @b{x86-windows}
25662 @item @code{@ @ }@i{rts-native (default)}
25663 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
25664 @item @code{@ @ @ @ }Exceptions @tab ZCX
25666 @item @code{@ @ }@i{rts-sjlj (default)}
25667 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
25668 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25670 @item @b{x86-windows-rtx}
25671 @item @code{@ @ }@i{rts-rtx-rtss (default)}
25672 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
25673 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25675 @item @code{@ @ }@i{rts-rtx-w32}
25676 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
25677 @item @code{@ @ @ @ }Exceptions @tab ZCX
25679 @item @b{x86_64-linux}
25680 @item @code{@ @ }@i{rts-native (default)}
25681 @item @code{@ @ @ @ }Tasking @tab pthread library
25682 @item @code{@ @ @ @ }Exceptions @tab ZCX
25684 @item @code{@ @ }@i{rts-sjlj}
25685 @item @code{@ @ @ @ }Tasking @tab pthread library
25686 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25690 @node Specifying a Run-Time Library
25691 @section Specifying a Run-Time Library
25694 The @file{adainclude} subdirectory containing the sources of the GNAT
25695 run-time library, and the @file{adalib} subdirectory containing the
25696 @file{ALI} files and the static and/or shared GNAT library, are located
25697 in the gcc target-dependent area:
25700 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
25704 As indicated above, on some platforms several run-time libraries are supplied.
25705 These libraries are installed in the target dependent area and
25706 contain a complete source and binary subdirectory. The detailed description
25707 below explains the differences between the different libraries in terms of
25708 their thread support.
25710 The default run-time library (when GNAT is installed) is @emph{rts-native}.
25711 This default run time is selected by the means of soft links.
25712 For example on x86-linux:
25718 +--- adainclude----------+
25720 +--- adalib-----------+ |
25722 +--- rts-native | |
25724 | +--- adainclude <---+
25726 | +--- adalib <----+
25737 If the @i{rts-sjlj} library is to be selected on a permanent basis,
25738 these soft links can be modified with the following commands:
25742 $ rm -f adainclude adalib
25743 $ ln -s rts-sjlj/adainclude adainclude
25744 $ ln -s rts-sjlj/adalib adalib
25748 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
25749 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
25750 @file{$target/ada_object_path}.
25752 Selecting another run-time library temporarily can be
25753 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
25754 @cindex @option{--RTS} option
25756 @node Choosing the Scheduling Policy
25757 @section Choosing the Scheduling Policy
25760 When using a POSIX threads implementation, you have a choice of several
25761 scheduling policies: @code{SCHED_FIFO},
25762 @cindex @code{SCHED_FIFO} scheduling policy
25764 @cindex @code{SCHED_RR} scheduling policy
25765 and @code{SCHED_OTHER}.
25766 @cindex @code{SCHED_OTHER} scheduling policy
25767 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
25768 or @code{SCHED_RR} requires special (e.g., root) privileges.
25770 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
25772 @cindex @code{SCHED_FIFO} scheduling policy
25773 you can use one of the following:
25777 @code{pragma Time_Slice (0.0)}
25778 @cindex pragma Time_Slice
25780 the corresponding binder option @option{-T0}
25781 @cindex @option{-T0} option
25783 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
25784 @cindex pragma Task_Dispatching_Policy
25788 To specify @code{SCHED_RR},
25789 @cindex @code{SCHED_RR} scheduling policy
25790 you should use @code{pragma Time_Slice} with a
25791 value greater than @code{0.0}, or else use the corresponding @option{-T}
25794 @node Solaris-Specific Considerations
25795 @section Solaris-Specific Considerations
25796 @cindex Solaris Sparc threads libraries
25799 This section addresses some topics related to the various threads libraries
25803 * Solaris Threads Issues::
25806 @node Solaris Threads Issues
25807 @subsection Solaris Threads Issues
25810 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
25811 library based on POSIX threads --- @emph{rts-pthread}.
25812 @cindex rts-pthread threads library
25813 This run-time library has the advantage of being mostly shared across all
25814 POSIX-compliant thread implementations, and it also provides under
25815 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
25816 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
25817 and @code{PTHREAD_PRIO_PROTECT}
25818 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
25819 semantics that can be selected using the predefined pragma
25820 @code{Locking_Policy}
25821 @cindex pragma Locking_Policy (under rts-pthread)
25823 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
25824 @cindex @code{Inheritance_Locking} (under rts-pthread)
25825 @cindex @code{Ceiling_Locking} (under rts-pthread)
25827 As explained above, the native run-time library is based on the Solaris thread
25828 library (@code{libthread}) and is the default library.
25830 When the Solaris threads library is used (this is the default), programs
25831 compiled with GNAT can automatically take advantage of
25832 and can thus execute on multiple processors.
25833 The user can alternatively specify a processor on which the program should run
25834 to emulate a single-processor system. The multiprocessor / uniprocessor choice
25836 setting the environment variable @env{GNAT_PROCESSOR}
25837 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
25838 to one of the following:
25842 Use the default configuration (run the program on all
25843 available processors) - this is the same as having @code{GNAT_PROCESSOR}
25847 Let the run-time implementation choose one processor and run the program on
25850 @item 0 .. Last_Proc
25851 Run the program on the specified processor.
25852 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
25853 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
25856 @node Linux-Specific Considerations
25857 @section Linux-Specific Considerations
25858 @cindex Linux threads libraries
25861 On GNU/Linux without NPTL support (usually system with GNU C Library
25862 older than 2.3), the signal model is not POSIX compliant, which means
25863 that to send a signal to the process, you need to send the signal to all
25864 threads, e.g.@: by using @code{killpg()}.
25866 @node AIX-Specific Considerations
25867 @section AIX-Specific Considerations
25868 @cindex AIX resolver library
25871 On AIX, the resolver library initializes some internal structure on
25872 the first call to @code{get*by*} functions, which are used to implement
25873 @code{GNAT.Sockets.Get_Host_By_Name} and
25874 @code{GNAT.Sockets.Get_Host_By_Address}.
25875 If such initialization occurs within an Ada task, and the stack size for
25876 the task is the default size, a stack overflow may occur.
25878 To avoid this overflow, the user should either ensure that the first call
25879 to @code{GNAT.Sockets.Get_Host_By_Name} or
25880 @code{GNAT.Sockets.Get_Host_By_Addrss}
25881 occurs in the environment task, or use @code{pragma Storage_Size} to
25882 specify a sufficiently large size for the stack of the task that contains
25885 @node Irix-Specific Considerations
25886 @section Irix-Specific Considerations
25887 @cindex Irix libraries
25890 The GCC support libraries coming with the Irix compiler have moved to
25891 their canonical place with respect to the general Irix ABI related
25892 conventions. Running applications built with the default shared GNAT
25893 run-time now requires the LD_LIBRARY_PATH environment variable to
25894 include this location. A possible way to achieve this is to issue the
25895 following command line on a bash prompt:
25899 $ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
25903 @node RTX-Specific Considerations
25904 @section RTX-Specific Considerations
25905 @cindex RTX libraries
25908 The Real-time Extension (RTX) to Windows is based on the Windows Win32
25909 API. Applications can be built to work in two different modes:
25913 Windows executables that run in Ring 3 to utilize memory protection
25914 (@emph{rts-rtx-w32}).
25917 Real-time subsystem (RTSS) executables that run in Ring 0, where
25918 performance can be optimized with RTSS applications taking precedent
25919 over all Windows applications (@emph{rts-rtx-rtss}).
25923 @c *******************************
25924 @node Example of Binder Output File
25925 @appendix Example of Binder Output File
25928 This Appendix displays the source code for @command{gnatbind}'s output
25929 file generated for a simple ``Hello World'' program.
25930 Comments have been added for clarification purposes.
25932 @smallexample @c adanocomment
25936 -- The package is called Ada_Main unless this name is actually used
25937 -- as a unit name in the partition, in which case some other unique
25941 package ada_main is
25943 Elab_Final_Code : Integer;
25944 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25946 -- The main program saves the parameters (argument count,
25947 -- argument values, environment pointer) in global variables
25948 -- for later access by other units including
25949 -- Ada.Command_Line.
25951 gnat_argc : Integer;
25952 gnat_argv : System.Address;
25953 gnat_envp : System.Address;
25955 -- The actual variables are stored in a library routine. This
25956 -- is useful for some shared library situations, where there
25957 -- are problems if variables are not in the library.
25959 pragma Import (C, gnat_argc);
25960 pragma Import (C, gnat_argv);
25961 pragma Import (C, gnat_envp);
25963 -- The exit status is similarly an external location
25965 gnat_exit_status : Integer;
25966 pragma Import (C, gnat_exit_status);
25968 GNAT_Version : constant String :=
25969 "GNAT Version: 6.0.0w (20061115)";
25970 pragma Export (C, GNAT_Version, "__gnat_version");
25972 -- This is the generated adafinal routine that performs
25973 -- finalization at the end of execution. In the case where
25974 -- Ada is the main program, this main program makes a call
25975 -- to adafinal at program termination.
25977 procedure adafinal;
25978 pragma Export (C, adafinal, "adafinal");
25980 -- This is the generated adainit routine that performs
25981 -- initialization at the start of execution. In the case
25982 -- where Ada is the main program, this main program makes
25983 -- a call to adainit at program startup.
25986 pragma Export (C, adainit, "adainit");
25988 -- This routine is called at the start of execution. It is
25989 -- a dummy routine that is used by the debugger to breakpoint
25990 -- at the start of execution.
25992 procedure Break_Start;
25993 pragma Import (C, Break_Start, "__gnat_break_start");
25995 -- This is the actual generated main program (it would be
25996 -- suppressed if the no main program switch were used). As
25997 -- required by standard system conventions, this program has
25998 -- the external name main.
26002 argv : System.Address;
26003 envp : System.Address)
26005 pragma Export (C, main, "main");
26007 -- The following set of constants give the version
26008 -- identification values for every unit in the bound
26009 -- partition. This identification is computed from all
26010 -- dependent semantic units, and corresponds to the
26011 -- string that would be returned by use of the
26012 -- Body_Version or Version attributes.
26014 type Version_32 is mod 2 ** 32;
26015 u00001 : constant Version_32 := 16#7880BEB3#;
26016 u00002 : constant Version_32 := 16#0D24CBD0#;
26017 u00003 : constant Version_32 := 16#3283DBEB#;
26018 u00004 : constant Version_32 := 16#2359F9ED#;
26019 u00005 : constant Version_32 := 16#664FB847#;
26020 u00006 : constant Version_32 := 16#68E803DF#;
26021 u00007 : constant Version_32 := 16#5572E604#;
26022 u00008 : constant Version_32 := 16#46B173D8#;
26023 u00009 : constant Version_32 := 16#156A40CF#;
26024 u00010 : constant Version_32 := 16#033DABE0#;
26025 u00011 : constant Version_32 := 16#6AB38FEA#;
26026 u00012 : constant Version_32 := 16#22B6217D#;
26027 u00013 : constant Version_32 := 16#68A22947#;
26028 u00014 : constant Version_32 := 16#18CC4A56#;
26029 u00015 : constant Version_32 := 16#08258E1B#;
26030 u00016 : constant Version_32 := 16#367D5222#;
26031 u00017 : constant Version_32 := 16#20C9ECA4#;
26032 u00018 : constant Version_32 := 16#50D32CB6#;
26033 u00019 : constant Version_32 := 16#39A8BB77#;
26034 u00020 : constant Version_32 := 16#5CF8FA2B#;
26035 u00021 : constant Version_32 := 16#2F1EB794#;
26036 u00022 : constant Version_32 := 16#31AB6444#;
26037 u00023 : constant Version_32 := 16#1574B6E9#;
26038 u00024 : constant Version_32 := 16#5109C189#;
26039 u00025 : constant Version_32 := 16#56D770CD#;
26040 u00026 : constant Version_32 := 16#02F9DE3D#;
26041 u00027 : constant Version_32 := 16#08AB6B2C#;
26042 u00028 : constant Version_32 := 16#3FA37670#;
26043 u00029 : constant Version_32 := 16#476457A0#;
26044 u00030 : constant Version_32 := 16#731E1B6E#;
26045 u00031 : constant Version_32 := 16#23C2E789#;
26046 u00032 : constant Version_32 := 16#0F1BD6A1#;
26047 u00033 : constant Version_32 := 16#7C25DE96#;
26048 u00034 : constant Version_32 := 16#39ADFFA2#;
26049 u00035 : constant Version_32 := 16#571DE3E7#;
26050 u00036 : constant Version_32 := 16#5EB646AB#;
26051 u00037 : constant Version_32 := 16#4249379B#;
26052 u00038 : constant Version_32 := 16#0357E00A#;
26053 u00039 : constant Version_32 := 16#3784FB72#;
26054 u00040 : constant Version_32 := 16#2E723019#;
26055 u00041 : constant Version_32 := 16#623358EA#;
26056 u00042 : constant Version_32 := 16#107F9465#;
26057 u00043 : constant Version_32 := 16#6843F68A#;
26058 u00044 : constant Version_32 := 16#63305874#;
26059 u00045 : constant Version_32 := 16#31E56CE1#;
26060 u00046 : constant Version_32 := 16#02917970#;
26061 u00047 : constant Version_32 := 16#6CCBA70E#;
26062 u00048 : constant Version_32 := 16#41CD4204#;
26063 u00049 : constant Version_32 := 16#572E3F58#;
26064 u00050 : constant Version_32 := 16#20729FF5#;
26065 u00051 : constant Version_32 := 16#1D4F93E8#;
26066 u00052 : constant Version_32 := 16#30B2EC3D#;
26067 u00053 : constant Version_32 := 16#34054F96#;
26068 u00054 : constant Version_32 := 16#5A199860#;
26069 u00055 : constant Version_32 := 16#0E7F912B#;
26070 u00056 : constant Version_32 := 16#5760634A#;
26071 u00057 : constant Version_32 := 16#5D851835#;
26073 -- The following Export pragmas export the version numbers
26074 -- with symbolic names ending in B (for body) or S
26075 -- (for spec) so that they can be located in a link. The
26076 -- information provided here is sufficient to track down
26077 -- the exact versions of units used in a given build.
26079 pragma Export (C, u00001, "helloB");
26080 pragma Export (C, u00002, "system__standard_libraryB");
26081 pragma Export (C, u00003, "system__standard_libraryS");
26082 pragma Export (C, u00004, "adaS");
26083 pragma Export (C, u00005, "ada__text_ioB");
26084 pragma Export (C, u00006, "ada__text_ioS");
26085 pragma Export (C, u00007, "ada__exceptionsB");
26086 pragma Export (C, u00008, "ada__exceptionsS");
26087 pragma Export (C, u00009, "gnatS");
26088 pragma Export (C, u00010, "gnat__heap_sort_aB");
26089 pragma Export (C, u00011, "gnat__heap_sort_aS");
26090 pragma Export (C, u00012, "systemS");
26091 pragma Export (C, u00013, "system__exception_tableB");
26092 pragma Export (C, u00014, "system__exception_tableS");
26093 pragma Export (C, u00015, "gnat__htableB");
26094 pragma Export (C, u00016, "gnat__htableS");
26095 pragma Export (C, u00017, "system__exceptionsS");
26096 pragma Export (C, u00018, "system__machine_state_operationsB");
26097 pragma Export (C, u00019, "system__machine_state_operationsS");
26098 pragma Export (C, u00020, "system__machine_codeS");
26099 pragma Export (C, u00021, "system__storage_elementsB");
26100 pragma Export (C, u00022, "system__storage_elementsS");
26101 pragma Export (C, u00023, "system__secondary_stackB");
26102 pragma Export (C, u00024, "system__secondary_stackS");
26103 pragma Export (C, u00025, "system__parametersB");
26104 pragma Export (C, u00026, "system__parametersS");
26105 pragma Export (C, u00027, "system__soft_linksB");
26106 pragma Export (C, u00028, "system__soft_linksS");
26107 pragma Export (C, u00029, "system__stack_checkingB");
26108 pragma Export (C, u00030, "system__stack_checkingS");
26109 pragma Export (C, u00031, "system__tracebackB");
26110 pragma Export (C, u00032, "system__tracebackS");
26111 pragma Export (C, u00033, "ada__streamsS");
26112 pragma Export (C, u00034, "ada__tagsB");
26113 pragma Export (C, u00035, "ada__tagsS");
26114 pragma Export (C, u00036, "system__string_opsB");
26115 pragma Export (C, u00037, "system__string_opsS");
26116 pragma Export (C, u00038, "interfacesS");
26117 pragma Export (C, u00039, "interfaces__c_streamsB");
26118 pragma Export (C, u00040, "interfaces__c_streamsS");
26119 pragma Export (C, u00041, "system__file_ioB");
26120 pragma Export (C, u00042, "system__file_ioS");
26121 pragma Export (C, u00043, "ada__finalizationB");
26122 pragma Export (C, u00044, "ada__finalizationS");
26123 pragma Export (C, u00045, "system__finalization_rootB");
26124 pragma Export (C, u00046, "system__finalization_rootS");
26125 pragma Export (C, u00047, "system__finalization_implementationB");
26126 pragma Export (C, u00048, "system__finalization_implementationS");
26127 pragma Export (C, u00049, "system__string_ops_concat_3B");
26128 pragma Export (C, u00050, "system__string_ops_concat_3S");
26129 pragma Export (C, u00051, "system__stream_attributesB");
26130 pragma Export (C, u00052, "system__stream_attributesS");
26131 pragma Export (C, u00053, "ada__io_exceptionsS");
26132 pragma Export (C, u00054, "system__unsigned_typesS");
26133 pragma Export (C, u00055, "system__file_control_blockS");
26134 pragma Export (C, u00056, "ada__finalization__list_controllerB");
26135 pragma Export (C, u00057, "ada__finalization__list_controllerS");
26137 -- BEGIN ELABORATION ORDER
26140 -- gnat.heap_sort_a (spec)
26141 -- gnat.heap_sort_a (body)
26142 -- gnat.htable (spec)
26143 -- gnat.htable (body)
26144 -- interfaces (spec)
26146 -- system.machine_code (spec)
26147 -- system.parameters (spec)
26148 -- system.parameters (body)
26149 -- interfaces.c_streams (spec)
26150 -- interfaces.c_streams (body)
26151 -- system.standard_library (spec)
26152 -- ada.exceptions (spec)
26153 -- system.exception_table (spec)
26154 -- system.exception_table (body)
26155 -- ada.io_exceptions (spec)
26156 -- system.exceptions (spec)
26157 -- system.storage_elements (spec)
26158 -- system.storage_elements (body)
26159 -- system.machine_state_operations (spec)
26160 -- system.machine_state_operations (body)
26161 -- system.secondary_stack (spec)
26162 -- system.stack_checking (spec)
26163 -- system.soft_links (spec)
26164 -- system.soft_links (body)
26165 -- system.stack_checking (body)
26166 -- system.secondary_stack (body)
26167 -- system.standard_library (body)
26168 -- system.string_ops (spec)
26169 -- system.string_ops (body)
26172 -- ada.streams (spec)
26173 -- system.finalization_root (spec)
26174 -- system.finalization_root (body)
26175 -- system.string_ops_concat_3 (spec)
26176 -- system.string_ops_concat_3 (body)
26177 -- system.traceback (spec)
26178 -- system.traceback (body)
26179 -- ada.exceptions (body)
26180 -- system.unsigned_types (spec)
26181 -- system.stream_attributes (spec)
26182 -- system.stream_attributes (body)
26183 -- system.finalization_implementation (spec)
26184 -- system.finalization_implementation (body)
26185 -- ada.finalization (spec)
26186 -- ada.finalization (body)
26187 -- ada.finalization.list_controller (spec)
26188 -- ada.finalization.list_controller (body)
26189 -- system.file_control_block (spec)
26190 -- system.file_io (spec)
26191 -- system.file_io (body)
26192 -- ada.text_io (spec)
26193 -- ada.text_io (body)
26195 -- END ELABORATION ORDER
26199 -- The following source file name pragmas allow the generated file
26200 -- names to be unique for different main programs. They are needed
26201 -- since the package name will always be Ada_Main.
26203 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26204 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26206 -- Generated package body for Ada_Main starts here
26208 package body ada_main is
26210 -- The actual finalization is performed by calling the
26211 -- library routine in System.Standard_Library.Adafinal
26213 procedure Do_Finalize;
26214 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26221 procedure adainit is
26223 -- These booleans are set to True once the associated unit has
26224 -- been elaborated. It is also used to avoid elaborating the
26225 -- same unit twice.
26228 pragma Import (Ada, E040, "interfaces__c_streams_E");
26231 pragma Import (Ada, E008, "ada__exceptions_E");
26234 pragma Import (Ada, E014, "system__exception_table_E");
26237 pragma Import (Ada, E053, "ada__io_exceptions_E");
26240 pragma Import (Ada, E017, "system__exceptions_E");
26243 pragma Import (Ada, E024, "system__secondary_stack_E");
26246 pragma Import (Ada, E030, "system__stack_checking_E");
26249 pragma Import (Ada, E028, "system__soft_links_E");
26252 pragma Import (Ada, E035, "ada__tags_E");
26255 pragma Import (Ada, E033, "ada__streams_E");
26258 pragma Import (Ada, E046, "system__finalization_root_E");
26261 pragma Import (Ada, E048, "system__finalization_implementation_E");
26264 pragma Import (Ada, E044, "ada__finalization_E");
26267 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26270 pragma Import (Ada, E055, "system__file_control_block_E");
26273 pragma Import (Ada, E042, "system__file_io_E");
26276 pragma Import (Ada, E006, "ada__text_io_E");
26278 -- Set_Globals is a library routine that stores away the
26279 -- value of the indicated set of global values in global
26280 -- variables within the library.
26282 procedure Set_Globals
26283 (Main_Priority : Integer;
26284 Time_Slice_Value : Integer;
26285 WC_Encoding : Character;
26286 Locking_Policy : Character;
26287 Queuing_Policy : Character;
26288 Task_Dispatching_Policy : Character;
26289 Adafinal : System.Address;
26290 Unreserve_All_Interrupts : Integer;
26291 Exception_Tracebacks : Integer);
26292 @findex __gnat_set_globals
26293 pragma Import (C, Set_Globals, "__gnat_set_globals");
26295 -- SDP_Table_Build is a library routine used to build the
26296 -- exception tables. See unit Ada.Exceptions in files
26297 -- a-except.ads/adb for full details of how zero cost
26298 -- exception handling works. This procedure, the call to
26299 -- it, and the two following tables are all omitted if the
26300 -- build is in longjmp/setjmp exception mode.
26302 @findex SDP_Table_Build
26303 @findex Zero Cost Exceptions
26304 procedure SDP_Table_Build
26305 (SDP_Addresses : System.Address;
26306 SDP_Count : Natural;
26307 Elab_Addresses : System.Address;
26308 Elab_Addr_Count : Natural);
26309 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26311 -- Table of Unit_Exception_Table addresses. Used for zero
26312 -- cost exception handling to build the top level table.
26314 ST : aliased constant array (1 .. 23) of System.Address := (
26316 Ada.Text_Io'UET_Address,
26317 Ada.Exceptions'UET_Address,
26318 Gnat.Heap_Sort_A'UET_Address,
26319 System.Exception_Table'UET_Address,
26320 System.Machine_State_Operations'UET_Address,
26321 System.Secondary_Stack'UET_Address,
26322 System.Parameters'UET_Address,
26323 System.Soft_Links'UET_Address,
26324 System.Stack_Checking'UET_Address,
26325 System.Traceback'UET_Address,
26326 Ada.Streams'UET_Address,
26327 Ada.Tags'UET_Address,
26328 System.String_Ops'UET_Address,
26329 Interfaces.C_Streams'UET_Address,
26330 System.File_Io'UET_Address,
26331 Ada.Finalization'UET_Address,
26332 System.Finalization_Root'UET_Address,
26333 System.Finalization_Implementation'UET_Address,
26334 System.String_Ops_Concat_3'UET_Address,
26335 System.Stream_Attributes'UET_Address,
26336 System.File_Control_Block'UET_Address,
26337 Ada.Finalization.List_Controller'UET_Address);
26339 -- Table of addresses of elaboration routines. Used for
26340 -- zero cost exception handling to make sure these
26341 -- addresses are included in the top level procedure
26344 EA : aliased constant array (1 .. 23) of System.Address := (
26345 adainit'Code_Address,
26346 Do_Finalize'Code_Address,
26347 Ada.Exceptions'Elab_Spec'Address,
26348 System.Exceptions'Elab_Spec'Address,
26349 Interfaces.C_Streams'Elab_Spec'Address,
26350 System.Exception_Table'Elab_Body'Address,
26351 Ada.Io_Exceptions'Elab_Spec'Address,
26352 System.Stack_Checking'Elab_Spec'Address,
26353 System.Soft_Links'Elab_Body'Address,
26354 System.Secondary_Stack'Elab_Body'Address,
26355 Ada.Tags'Elab_Spec'Address,
26356 Ada.Tags'Elab_Body'Address,
26357 Ada.Streams'Elab_Spec'Address,
26358 System.Finalization_Root'Elab_Spec'Address,
26359 Ada.Exceptions'Elab_Body'Address,
26360 System.Finalization_Implementation'Elab_Spec'Address,
26361 System.Finalization_Implementation'Elab_Body'Address,
26362 Ada.Finalization'Elab_Spec'Address,
26363 Ada.Finalization.List_Controller'Elab_Spec'Address,
26364 System.File_Control_Block'Elab_Spec'Address,
26365 System.File_Io'Elab_Body'Address,
26366 Ada.Text_Io'Elab_Spec'Address,
26367 Ada.Text_Io'Elab_Body'Address);
26369 -- Start of processing for adainit
26373 -- Call SDP_Table_Build to build the top level procedure
26374 -- table for zero cost exception handling (omitted in
26375 -- longjmp/setjmp mode).
26377 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26379 -- Call Set_Globals to record various information for
26380 -- this partition. The values are derived by the binder
26381 -- from information stored in the ali files by the compiler.
26383 @findex __gnat_set_globals
26385 (Main_Priority => -1,
26386 -- Priority of main program, -1 if no pragma Priority used
26388 Time_Slice_Value => -1,
26389 -- Time slice from Time_Slice pragma, -1 if none used
26391 WC_Encoding => 'b',
26392 -- Wide_Character encoding used, default is brackets
26394 Locking_Policy => ' ',
26395 -- Locking_Policy used, default of space means not
26396 -- specified, otherwise it is the first character of
26397 -- the policy name.
26399 Queuing_Policy => ' ',
26400 -- Queuing_Policy used, default of space means not
26401 -- specified, otherwise it is the first character of
26402 -- the policy name.
26404 Task_Dispatching_Policy => ' ',
26405 -- Task_Dispatching_Policy used, default of space means
26406 -- not specified, otherwise first character of the
26409 Adafinal => System.Null_Address,
26410 -- Address of Adafinal routine, not used anymore
26412 Unreserve_All_Interrupts => 0,
26413 -- Set true if pragma Unreserve_All_Interrupts was used
26415 Exception_Tracebacks => 0);
26416 -- Indicates if exception tracebacks are enabled
26418 Elab_Final_Code := 1;
26420 -- Now we have the elaboration calls for all units in the partition.
26421 -- The Elab_Spec and Elab_Body attributes generate references to the
26422 -- implicit elaboration procedures generated by the compiler for
26423 -- each unit that requires elaboration.
26426 Interfaces.C_Streams'Elab_Spec;
26430 Ada.Exceptions'Elab_Spec;
26433 System.Exception_Table'Elab_Body;
26437 Ada.Io_Exceptions'Elab_Spec;
26441 System.Exceptions'Elab_Spec;
26445 System.Stack_Checking'Elab_Spec;
26448 System.Soft_Links'Elab_Body;
26453 System.Secondary_Stack'Elab_Body;
26457 Ada.Tags'Elab_Spec;
26460 Ada.Tags'Elab_Body;
26464 Ada.Streams'Elab_Spec;
26468 System.Finalization_Root'Elab_Spec;
26472 Ada.Exceptions'Elab_Body;
26476 System.Finalization_Implementation'Elab_Spec;
26479 System.Finalization_Implementation'Elab_Body;
26483 Ada.Finalization'Elab_Spec;
26487 Ada.Finalization.List_Controller'Elab_Spec;
26491 System.File_Control_Block'Elab_Spec;
26495 System.File_Io'Elab_Body;
26499 Ada.Text_Io'Elab_Spec;
26502 Ada.Text_Io'Elab_Body;
26506 Elab_Final_Code := 0;
26514 procedure adafinal is
26523 -- main is actually a function, as in the ANSI C standard,
26524 -- defined to return the exit status. The three parameters
26525 -- are the argument count, argument values and environment
26528 @findex Main Program
26531 argv : System.Address;
26532 envp : System.Address)
26535 -- The initialize routine performs low level system
26536 -- initialization using a standard library routine which
26537 -- sets up signal handling and performs any other
26538 -- required setup. The routine can be found in file
26541 @findex __gnat_initialize
26542 procedure initialize;
26543 pragma Import (C, initialize, "__gnat_initialize");
26545 -- The finalize routine performs low level system
26546 -- finalization using a standard library routine. The
26547 -- routine is found in file a-final.c and in the standard
26548 -- distribution is a dummy routine that does nothing, so
26549 -- really this is a hook for special user finalization.
26551 @findex __gnat_finalize
26552 procedure finalize;
26553 pragma Import (C, finalize, "__gnat_finalize");
26555 -- We get to the main program of the partition by using
26556 -- pragma Import because if we try to with the unit and
26557 -- call it Ada style, then not only do we waste time
26558 -- recompiling it, but also, we don't really know the right
26559 -- switches (e.g.@: identifier character set) to be used
26562 procedure Ada_Main_Program;
26563 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26565 -- Start of processing for main
26568 -- Save global variables
26574 -- Call low level system initialization
26578 -- Call our generated Ada initialization routine
26582 -- This is the point at which we want the debugger to get
26587 -- Now we call the main program of the partition
26591 -- Perform Ada finalization
26595 -- Perform low level system finalization
26599 -- Return the proper exit status
26600 return (gnat_exit_status);
26603 -- This section is entirely comments, so it has no effect on the
26604 -- compilation of the Ada_Main package. It provides the list of
26605 -- object files and linker options, as well as some standard
26606 -- libraries needed for the link. The gnatlink utility parses
26607 -- this b~hello.adb file to read these comment lines to generate
26608 -- the appropriate command line arguments for the call to the
26609 -- system linker. The BEGIN/END lines are used for sentinels for
26610 -- this parsing operation.
26612 -- The exact file names will of course depend on the environment,
26613 -- host/target and location of files on the host system.
26615 @findex Object file list
26616 -- BEGIN Object file/option list
26619 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26620 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26621 -- END Object file/option list
26627 The Ada code in the above example is exactly what is generated by the
26628 binder. We have added comments to more clearly indicate the function
26629 of each part of the generated @code{Ada_Main} package.
26631 The code is standard Ada in all respects, and can be processed by any
26632 tools that handle Ada. In particular, it is possible to use the debugger
26633 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26634 suppose that for reasons that you do not understand, your program is crashing
26635 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26636 you can place a breakpoint on the call:
26638 @smallexample @c ada
26639 Ada.Text_Io'Elab_Body;
26643 and trace the elaboration routine for this package to find out where
26644 the problem might be (more usually of course you would be debugging
26645 elaboration code in your own application).
26647 @node Elaboration Order Handling in GNAT
26648 @appendix Elaboration Order Handling in GNAT
26649 @cindex Order of elaboration
26650 @cindex Elaboration control
26653 * Elaboration Code::
26654 * Checking the Elaboration Order::
26655 * Controlling the Elaboration Order::
26656 * Controlling Elaboration in GNAT - Internal Calls::
26657 * Controlling Elaboration in GNAT - External Calls::
26658 * Default Behavior in GNAT - Ensuring Safety::
26659 * Treatment of Pragma Elaborate::
26660 * Elaboration Issues for Library Tasks::
26661 * Mixing Elaboration Models::
26662 * What to Do If the Default Elaboration Behavior Fails::
26663 * Elaboration for Access-to-Subprogram Values::
26664 * Summary of Procedures for Elaboration Control::
26665 * Other Elaboration Order Considerations::
26669 This chapter describes the handling of elaboration code in Ada and
26670 in GNAT, and discusses how the order of elaboration of program units can
26671 be controlled in GNAT, either automatically or with explicit programming
26674 @node Elaboration Code
26675 @section Elaboration Code
26678 Ada provides rather general mechanisms for executing code at elaboration
26679 time, that is to say before the main program starts executing. Such code arises
26683 @item Initializers for variables.
26684 Variables declared at the library level, in package specs or bodies, can
26685 require initialization that is performed at elaboration time, as in:
26686 @smallexample @c ada
26688 Sqrt_Half : Float := Sqrt (0.5);
26692 @item Package initialization code
26693 Code in a @code{BEGIN-END} section at the outer level of a package body is
26694 executed as part of the package body elaboration code.
26696 @item Library level task allocators
26697 Tasks that are declared using task allocators at the library level
26698 start executing immediately and hence can execute at elaboration time.
26702 Subprogram calls are possible in any of these contexts, which means that
26703 any arbitrary part of the program may be executed as part of the elaboration
26704 code. It is even possible to write a program which does all its work at
26705 elaboration time, with a null main program, although stylistically this
26706 would usually be considered an inappropriate way to structure
26709 An important concern arises in the context of elaboration code:
26710 we have to be sure that it is executed in an appropriate order. What we
26711 have is a series of elaboration code sections, potentially one section
26712 for each unit in the program. It is important that these execute
26713 in the correct order. Correctness here means that, taking the above
26714 example of the declaration of @code{Sqrt_Half},
26715 if some other piece of
26716 elaboration code references @code{Sqrt_Half},
26717 then it must run after the
26718 section of elaboration code that contains the declaration of
26721 There would never be any order of elaboration problem if we made a rule
26722 that whenever you @code{with} a unit, you must elaborate both the spec and body
26723 of that unit before elaborating the unit doing the @code{with}'ing:
26725 @smallexample @c ada
26729 package Unit_2 is @dots{}
26735 would require that both the body and spec of @code{Unit_1} be elaborated
26736 before the spec of @code{Unit_2}. However, a rule like that would be far too
26737 restrictive. In particular, it would make it impossible to have routines
26738 in separate packages that were mutually recursive.
26740 You might think that a clever enough compiler could look at the actual
26741 elaboration code and determine an appropriate correct order of elaboration,
26742 but in the general case, this is not possible. Consider the following
26745 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
26747 the variable @code{Sqrt_1}, which is declared in the elaboration code
26748 of the body of @code{Unit_1}:
26750 @smallexample @c ada
26752 Sqrt_1 : Float := Sqrt (0.1);
26757 The elaboration code of the body of @code{Unit_1} also contains:
26759 @smallexample @c ada
26762 if expression_1 = 1 then
26763 Q := Unit_2.Func_2;
26770 @code{Unit_2} is exactly parallel,
26771 it has a procedure @code{Func_2} that references
26772 the variable @code{Sqrt_2}, which is declared in the elaboration code of
26773 the body @code{Unit_2}:
26775 @smallexample @c ada
26777 Sqrt_2 : Float := Sqrt (0.1);
26782 The elaboration code of the body of @code{Unit_2} also contains:
26784 @smallexample @c ada
26787 if expression_2 = 2 then
26788 Q := Unit_1.Func_1;
26795 Now the question is, which of the following orders of elaboration is
26820 If you carefully analyze the flow here, you will see that you cannot tell
26821 at compile time the answer to this question.
26822 If @code{expression_1} is not equal to 1,
26823 and @code{expression_2} is not equal to 2,
26824 then either order is acceptable, because neither of the function calls is
26825 executed. If both tests evaluate to true, then neither order is acceptable
26826 and in fact there is no correct order.
26828 If one of the two expressions is true, and the other is false, then one
26829 of the above orders is correct, and the other is incorrect. For example,
26830 if @code{expression_1} /= 1 and @code{expression_2} = 2,
26831 then the call to @code{Func_1}
26832 will occur, but not the call to @code{Func_2.}
26833 This means that it is essential
26834 to elaborate the body of @code{Unit_1} before
26835 the body of @code{Unit_2}, so the first
26836 order of elaboration is correct and the second is wrong.
26838 By making @code{expression_1} and @code{expression_2}
26839 depend on input data, or perhaps
26840 the time of day, we can make it impossible for the compiler or binder
26841 to figure out which of these expressions will be true, and hence it
26842 is impossible to guarantee a safe order of elaboration at run time.
26844 @node Checking the Elaboration Order
26845 @section Checking the Elaboration Order
26848 In some languages that involve the same kind of elaboration problems,
26849 e.g.@: Java and C++, the programmer is expected to worry about these
26850 ordering problems himself, and it is common to
26851 write a program in which an incorrect elaboration order gives
26852 surprising results, because it references variables before they
26854 Ada is designed to be a safe language, and a programmer-beware approach is
26855 clearly not sufficient. Consequently, the language provides three lines
26859 @item Standard rules
26860 Some standard rules restrict the possible choice of elaboration
26861 order. In particular, if you @code{with} a unit, then its spec is always
26862 elaborated before the unit doing the @code{with}. Similarly, a parent
26863 spec is always elaborated before the child spec, and finally
26864 a spec is always elaborated before its corresponding body.
26866 @item Dynamic elaboration checks
26867 @cindex Elaboration checks
26868 @cindex Checks, elaboration
26869 Dynamic checks are made at run time, so that if some entity is accessed
26870 before it is elaborated (typically by means of a subprogram call)
26871 then the exception (@code{Program_Error}) is raised.
26873 @item Elaboration control
26874 Facilities are provided for the programmer to specify the desired order
26878 Let's look at these facilities in more detail. First, the rules for
26879 dynamic checking. One possible rule would be simply to say that the
26880 exception is raised if you access a variable which has not yet been
26881 elaborated. The trouble with this approach is that it could require
26882 expensive checks on every variable reference. Instead Ada has two
26883 rules which are a little more restrictive, but easier to check, and
26887 @item Restrictions on calls
26888 A subprogram can only be called at elaboration time if its body
26889 has been elaborated. The rules for elaboration given above guarantee
26890 that the spec of the subprogram has been elaborated before the
26891 call, but not the body. If this rule is violated, then the
26892 exception @code{Program_Error} is raised.
26894 @item Restrictions on instantiations
26895 A generic unit can only be instantiated if the body of the generic
26896 unit has been elaborated. Again, the rules for elaboration given above
26897 guarantee that the spec of the generic unit has been elaborated
26898 before the instantiation, but not the body. If this rule is
26899 violated, then the exception @code{Program_Error} is raised.
26903 The idea is that if the body has been elaborated, then any variables
26904 it references must have been elaborated; by checking for the body being
26905 elaborated we guarantee that none of its references causes any
26906 trouble. As we noted above, this is a little too restrictive, because a
26907 subprogram that has no non-local references in its body may in fact be safe
26908 to call. However, it really would be unsafe to rely on this, because
26909 it would mean that the caller was aware of details of the implementation
26910 in the body. This goes against the basic tenets of Ada.
26912 A plausible implementation can be described as follows.
26913 A Boolean variable is associated with each subprogram
26914 and each generic unit. This variable is initialized to False, and is set to
26915 True at the point body is elaborated. Every call or instantiation checks the
26916 variable, and raises @code{Program_Error} if the variable is False.
26918 Note that one might think that it would be good enough to have one Boolean
26919 variable for each package, but that would not deal with cases of trying
26920 to call a body in the same package as the call
26921 that has not been elaborated yet.
26922 Of course a compiler may be able to do enough analysis to optimize away
26923 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
26924 does such optimizations, but still the easiest conceptual model is to
26925 think of there being one variable per subprogram.
26927 @node Controlling the Elaboration Order
26928 @section Controlling the Elaboration Order
26931 In the previous section we discussed the rules in Ada which ensure
26932 that @code{Program_Error} is raised if an incorrect elaboration order is
26933 chosen. This prevents erroneous executions, but we need mechanisms to
26934 specify a correct execution and avoid the exception altogether.
26935 To achieve this, Ada provides a number of features for controlling
26936 the order of elaboration. We discuss these features in this section.
26938 First, there are several ways of indicating to the compiler that a given
26939 unit has no elaboration problems:
26942 @item packages that do not require a body
26943 A library package that does not require a body does not permit
26944 a body (this rule was introduced in Ada 95).
26945 Thus if we have a such a package, as in:
26947 @smallexample @c ada
26950 package Definitions is
26952 type m is new integer;
26954 type a is array (1 .. 10) of m;
26955 type b is array (1 .. 20) of m;
26963 A package that @code{with}'s @code{Definitions} may safely instantiate
26964 @code{Definitions.Subp} because the compiler can determine that there
26965 definitely is no package body to worry about in this case
26968 @cindex pragma Pure
26970 Places sufficient restrictions on a unit to guarantee that
26971 no call to any subprogram in the unit can result in an
26972 elaboration problem. This means that the compiler does not need
26973 to worry about the point of elaboration of such units, and in
26974 particular, does not need to check any calls to any subprograms
26977 @item pragma Preelaborate
26978 @findex Preelaborate
26979 @cindex pragma Preelaborate
26980 This pragma places slightly less stringent restrictions on a unit than
26982 but these restrictions are still sufficient to ensure that there
26983 are no elaboration problems with any calls to the unit.
26985 @item pragma Elaborate_Body
26986 @findex Elaborate_Body
26987 @cindex pragma Elaborate_Body
26988 This pragma requires that the body of a unit be elaborated immediately
26989 after its spec. Suppose a unit @code{A} has such a pragma,
26990 and unit @code{B} does
26991 a @code{with} of unit @code{A}. Recall that the standard rules require
26992 the spec of unit @code{A}
26993 to be elaborated before the @code{with}'ing unit; given the pragma in
26994 @code{A}, we also know that the body of @code{A}
26995 will be elaborated before @code{B}, so
26996 that calls to @code{A} are safe and do not need a check.
27001 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27003 @code{Elaborate_Body} does not guarantee that the program is
27004 free of elaboration problems, because it may not be possible
27005 to satisfy the requested elaboration order.
27006 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27008 marks @code{Unit_1} as @code{Elaborate_Body},
27009 and not @code{Unit_2,} then the order of
27010 elaboration will be:
27022 Now that means that the call to @code{Func_1} in @code{Unit_2}
27023 need not be checked,
27024 it must be safe. But the call to @code{Func_2} in
27025 @code{Unit_1} may still fail if
27026 @code{Expression_1} is equal to 1,
27027 and the programmer must still take
27028 responsibility for this not being the case.
27030 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27031 eliminated, except for calls entirely within a body, which are
27032 in any case fully under programmer control. However, using the pragma
27033 everywhere is not always possible.
27034 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27035 we marked both of them as having pragma @code{Elaborate_Body}, then
27036 clearly there would be no possible elaboration order.
27038 The above pragmas allow a server to guarantee safe use by clients, and
27039 clearly this is the preferable approach. Consequently a good rule
27040 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27041 and if this is not possible,
27042 mark them as @code{Elaborate_Body} if possible.
27043 As we have seen, there are situations where neither of these
27044 three pragmas can be used.
27045 So we also provide methods for clients to control the
27046 order of elaboration of the servers on which they depend:
27049 @item pragma Elaborate (unit)
27051 @cindex pragma Elaborate
27052 This pragma is placed in the context clause, after a @code{with} clause,
27053 and it requires that the body of the named unit be elaborated before
27054 the unit in which the pragma occurs. The idea is to use this pragma
27055 if the current unit calls at elaboration time, directly or indirectly,
27056 some subprogram in the named unit.
27058 @item pragma Elaborate_All (unit)
27059 @findex Elaborate_All
27060 @cindex pragma Elaborate_All
27061 This is a stronger version of the Elaborate pragma. Consider the
27065 Unit A @code{with}'s unit B and calls B.Func in elab code
27066 Unit B @code{with}'s unit C, and B.Func calls C.Func
27070 Now if we put a pragma @code{Elaborate (B)}
27071 in unit @code{A}, this ensures that the
27072 body of @code{B} is elaborated before the call, but not the
27073 body of @code{C}, so
27074 the call to @code{C.Func} could still cause @code{Program_Error} to
27077 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27078 not only that the body of the named unit be elaborated before the
27079 unit doing the @code{with}, but also the bodies of all units that the
27080 named unit uses, following @code{with} links transitively. For example,
27081 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27083 not only that the body of @code{B} be elaborated before @code{A},
27085 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27089 We are now in a position to give a usage rule in Ada for avoiding
27090 elaboration problems, at least if dynamic dispatching and access to
27091 subprogram values are not used. We will handle these cases separately
27094 The rule is simple. If a unit has elaboration code that can directly or
27095 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27096 a generic package in a @code{with}'ed unit,
27097 then if the @code{with}'ed unit does not have
27098 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27099 a pragma @code{Elaborate_All}
27100 for the @code{with}'ed unit. By following this rule a client is
27101 assured that calls can be made without risk of an exception.
27103 For generic subprogram instantiations, the rule can be relaxed to
27104 require only a pragma @code{Elaborate} since elaborating the body
27105 of a subprogram cannot cause any transitive elaboration (we are
27106 not calling the subprogram in this case, just elaborating its
27109 If this rule is not followed, then a program may be in one of four
27113 @item No order exists
27114 No order of elaboration exists which follows the rules, taking into
27115 account any @code{Elaborate}, @code{Elaborate_All},
27116 or @code{Elaborate_Body} pragmas. In
27117 this case, an Ada compiler must diagnose the situation at bind
27118 time, and refuse to build an executable program.
27120 @item One or more orders exist, all incorrect
27121 One or more acceptable elaboration orders exist, and all of them
27122 generate an elaboration order problem. In this case, the binder
27123 can build an executable program, but @code{Program_Error} will be raised
27124 when the program is run.
27126 @item Several orders exist, some right, some incorrect
27127 One or more acceptable elaboration orders exists, and some of them
27128 work, and some do not. The programmer has not controlled
27129 the order of elaboration, so the binder may or may not pick one of
27130 the correct orders, and the program may or may not raise an
27131 exception when it is run. This is the worst case, because it means
27132 that the program may fail when moved to another compiler, or even
27133 another version of the same compiler.
27135 @item One or more orders exists, all correct
27136 One ore more acceptable elaboration orders exist, and all of them
27137 work. In this case the program runs successfully. This state of
27138 affairs can be guaranteed by following the rule we gave above, but
27139 may be true even if the rule is not followed.
27143 Note that one additional advantage of following our rules on the use
27144 of @code{Elaborate} and @code{Elaborate_All}
27145 is that the program continues to stay in the ideal (all orders OK) state
27146 even if maintenance
27147 changes some bodies of some units. Conversely, if a program that does
27148 not follow this rule happens to be safe at some point, this state of affairs
27149 may deteriorate silently as a result of maintenance changes.
27151 You may have noticed that the above discussion did not mention
27152 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27153 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27154 code in the body makes calls to some other unit, so it is still necessary
27155 to use @code{Elaborate_All} on such units.
27157 @node Controlling Elaboration in GNAT - Internal Calls
27158 @section Controlling Elaboration in GNAT - Internal Calls
27161 In the case of internal calls, i.e., calls within a single package, the
27162 programmer has full control over the order of elaboration, and it is up
27163 to the programmer to elaborate declarations in an appropriate order. For
27166 @smallexample @c ada
27169 function One return Float;
27173 function One return Float is
27182 will obviously raise @code{Program_Error} at run time, because function
27183 One will be called before its body is elaborated. In this case GNAT will
27184 generate a warning that the call will raise @code{Program_Error}:
27190 2. function One return Float;
27192 4. Q : Float := One;
27194 >>> warning: cannot call "One" before body is elaborated
27195 >>> warning: Program_Error will be raised at run time
27198 6. function One return Float is
27211 Note that in this particular case, it is likely that the call is safe, because
27212 the function @code{One} does not access any global variables.
27213 Nevertheless in Ada, we do not want the validity of the check to depend on
27214 the contents of the body (think about the separate compilation case), so this
27215 is still wrong, as we discussed in the previous sections.
27217 The error is easily corrected by rearranging the declarations so that the
27218 body of @code{One} appears before the declaration containing the call
27219 (note that in Ada 95 and Ada 2005,
27220 declarations can appear in any order, so there is no restriction that
27221 would prevent this reordering, and if we write:
27223 @smallexample @c ada
27226 function One return Float;
27228 function One return Float is
27239 then all is well, no warning is generated, and no
27240 @code{Program_Error} exception
27242 Things are more complicated when a chain of subprograms is executed:
27244 @smallexample @c ada
27247 function A return Integer;
27248 function B return Integer;
27249 function C return Integer;
27251 function B return Integer is begin return A; end;
27252 function C return Integer is begin return B; end;
27256 function A return Integer is begin return 1; end;
27262 Now the call to @code{C}
27263 at elaboration time in the declaration of @code{X} is correct, because
27264 the body of @code{C} is already elaborated,
27265 and the call to @code{B} within the body of
27266 @code{C} is correct, but the call
27267 to @code{A} within the body of @code{B} is incorrect, because the body
27268 of @code{A} has not been elaborated, so @code{Program_Error}
27269 will be raised on the call to @code{A}.
27270 In this case GNAT will generate a
27271 warning that @code{Program_Error} may be
27272 raised at the point of the call. Let's look at the warning:
27278 2. function A return Integer;
27279 3. function B return Integer;
27280 4. function C return Integer;
27282 6. function B return Integer is begin return A; end;
27284 >>> warning: call to "A" before body is elaborated may
27285 raise Program_Error
27286 >>> warning: "B" called at line 7
27287 >>> warning: "C" called at line 9
27289 7. function C return Integer is begin return B; end;
27291 9. X : Integer := C;
27293 11. function A return Integer is begin return 1; end;
27303 Note that the message here says ``may raise'', instead of the direct case,
27304 where the message says ``will be raised''. That's because whether
27306 actually called depends in general on run-time flow of control.
27307 For example, if the body of @code{B} said
27309 @smallexample @c ada
27312 function B return Integer is
27314 if some-condition-depending-on-input-data then
27325 then we could not know until run time whether the incorrect call to A would
27326 actually occur, so @code{Program_Error} might
27327 or might not be raised. It is possible for a compiler to
27328 do a better job of analyzing bodies, to
27329 determine whether or not @code{Program_Error}
27330 might be raised, but it certainly
27331 couldn't do a perfect job (that would require solving the halting problem
27332 and is provably impossible), and because this is a warning anyway, it does
27333 not seem worth the effort to do the analysis. Cases in which it
27334 would be relevant are rare.
27336 In practice, warnings of either of the forms given
27337 above will usually correspond to
27338 real errors, and should be examined carefully and eliminated.
27339 In the rare case where a warning is bogus, it can be suppressed by any of
27340 the following methods:
27344 Compile with the @option{-gnatws} switch set
27347 Suppress @code{Elaboration_Check} for the called subprogram
27350 Use pragma @code{Warnings_Off} to turn warnings off for the call
27354 For the internal elaboration check case,
27355 GNAT by default generates the
27356 necessary run-time checks to ensure
27357 that @code{Program_Error} is raised if any
27358 call fails an elaboration check. Of course this can only happen if a
27359 warning has been issued as described above. The use of pragma
27360 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27361 some of these checks, meaning that it may be possible (but is not
27362 guaranteed) for a program to be able to call a subprogram whose body
27363 is not yet elaborated, without raising a @code{Program_Error} exception.
27365 @node Controlling Elaboration in GNAT - External Calls
27366 @section Controlling Elaboration in GNAT - External Calls
27369 The previous section discussed the case in which the execution of a
27370 particular thread of elaboration code occurred entirely within a
27371 single unit. This is the easy case to handle, because a programmer
27372 has direct and total control over the order of elaboration, and
27373 furthermore, checks need only be generated in cases which are rare
27374 and which the compiler can easily detect.
27375 The situation is more complex when separate compilation is taken into account.
27376 Consider the following:
27378 @smallexample @c ada
27382 function Sqrt (Arg : Float) return Float;
27385 package body Math is
27386 function Sqrt (Arg : Float) return Float is
27395 X : Float := Math.Sqrt (0.5);
27408 where @code{Main} is the main program. When this program is executed, the
27409 elaboration code must first be executed, and one of the jobs of the
27410 binder is to determine the order in which the units of a program are
27411 to be elaborated. In this case we have four units: the spec and body
27413 the spec of @code{Stuff} and the body of @code{Main}).
27414 In what order should the four separate sections of elaboration code
27417 There are some restrictions in the order of elaboration that the binder
27418 can choose. In particular, if unit U has a @code{with}
27419 for a package @code{X}, then you
27420 are assured that the spec of @code{X}
27421 is elaborated before U , but you are
27422 not assured that the body of @code{X}
27423 is elaborated before U.
27424 This means that in the above case, the binder is allowed to choose the
27435 but that's not good, because now the call to @code{Math.Sqrt}
27436 that happens during
27437 the elaboration of the @code{Stuff}
27438 spec happens before the body of @code{Math.Sqrt} is
27439 elaborated, and hence causes @code{Program_Error} exception to be raised.
27440 At first glance, one might say that the binder is misbehaving, because
27441 obviously you want to elaborate the body of something you @code{with}
27443 that is not a general rule that can be followed in all cases. Consider
27445 @smallexample @c ada
27448 package X is @dots{}
27450 package Y is @dots{}
27453 package body Y is @dots{}
27456 package body X is @dots{}
27462 This is a common arrangement, and, apart from the order of elaboration
27463 problems that might arise in connection with elaboration code, this works fine.
27464 A rule that says that you must first elaborate the body of anything you
27465 @code{with} cannot work in this case:
27466 the body of @code{X} @code{with}'s @code{Y},
27467 which means you would have to
27468 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
27470 you have to elaborate the body of @code{X} first, but @dots{} and we have a
27471 loop that cannot be broken.
27473 It is true that the binder can in many cases guess an order of elaboration
27474 that is unlikely to cause a @code{Program_Error}
27475 exception to be raised, and it tries to do so (in the
27476 above example of @code{Math/Stuff/Spec}, the GNAT binder will
27478 elaborate the body of @code{Math} right after its spec, so all will be well).
27480 However, a program that blindly relies on the binder to be helpful can
27481 get into trouble, as we discussed in the previous sections, so
27483 provides a number of facilities for assisting the programmer in
27484 developing programs that are robust with respect to elaboration order.
27486 @node Default Behavior in GNAT - Ensuring Safety
27487 @section Default Behavior in GNAT - Ensuring Safety
27490 The default behavior in GNAT ensures elaboration safety. In its
27491 default mode GNAT implements the
27492 rule we previously described as the right approach. Let's restate it:
27496 @emph{If a unit has elaboration code that can directly or indirectly make a
27497 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
27498 package in a @code{with}'ed unit, then if the @code{with}'ed unit
27499 does not have pragma @code{Pure} or
27500 @code{Preelaborate}, then the client should have an
27501 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
27503 @emph{In the case of instantiating a generic subprogram, it is always
27504 sufficient to have only an @code{Elaborate} pragma for the
27505 @code{with}'ed unit.}
27509 By following this rule a client is assured that calls and instantiations
27510 can be made without risk of an exception.
27512 In this mode GNAT traces all calls that are potentially made from
27513 elaboration code, and puts in any missing implicit @code{Elaborate}
27514 and @code{Elaborate_All} pragmas.
27515 The advantage of this approach is that no elaboration problems
27516 are possible if the binder can find an elaboration order that is
27517 consistent with these implicit @code{Elaborate} and
27518 @code{Elaborate_All} pragmas. The
27519 disadvantage of this approach is that no such order may exist.
27521 If the binder does not generate any diagnostics, then it means that it has
27522 found an elaboration order that is guaranteed to be safe. However, the binder
27523 may still be relying on implicitly generated @code{Elaborate} and
27524 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27527 If it is important to guarantee portability, then the compilations should
27530 (warn on elaboration problems) switch. This will cause warning messages
27531 to be generated indicating the missing @code{Elaborate} and
27532 @code{Elaborate_All} pragmas.
27533 Consider the following source program:
27535 @smallexample @c ada
27540 m : integer := k.r;
27547 where it is clear that there
27548 should be a pragma @code{Elaborate_All}
27549 for unit @code{k}. An implicit pragma will be generated, and it is
27550 likely that the binder will be able to honor it. However, if you want
27551 to port this program to some other Ada compiler than GNAT.
27552 it is safer to include the pragma explicitly in the source. If this
27553 unit is compiled with the
27555 switch, then the compiler outputs a warning:
27562 3. m : integer := k.r;
27564 >>> warning: call to "r" may raise Program_Error
27565 >>> warning: missing pragma Elaborate_All for "k"
27573 and these warnings can be used as a guide for supplying manually
27574 the missing pragmas. It is usually a bad idea to use this warning
27575 option during development. That's because it will warn you when
27576 you need to put in a pragma, but cannot warn you when it is time
27577 to take it out. So the use of pragma @code{Elaborate_All} may lead to
27578 unnecessary dependencies and even false circularities.
27580 This default mode is more restrictive than the Ada Reference
27581 Manual, and it is possible to construct programs which will compile
27582 using the dynamic model described there, but will run into a
27583 circularity using the safer static model we have described.
27585 Of course any Ada compiler must be able to operate in a mode
27586 consistent with the requirements of the Ada Reference Manual,
27587 and in particular must have the capability of implementing the
27588 standard dynamic model of elaboration with run-time checks.
27590 In GNAT, this standard mode can be achieved either by the use of
27591 the @option{-gnatE} switch on the compiler (@command{gcc} or
27592 @command{gnatmake}) command, or by the use of the configuration pragma:
27594 @smallexample @c ada
27595 pragma Elaboration_Checks (RM);
27599 Either approach will cause the unit affected to be compiled using the
27600 standard dynamic run-time elaboration checks described in the Ada
27601 Reference Manual. The static model is generally preferable, since it
27602 is clearly safer to rely on compile and link time checks rather than
27603 run-time checks. However, in the case of legacy code, it may be
27604 difficult to meet the requirements of the static model. This
27605 issue is further discussed in
27606 @ref{What to Do If the Default Elaboration Behavior Fails}.
27608 Note that the static model provides a strict subset of the allowed
27609 behavior and programs of the Ada Reference Manual, so if you do
27610 adhere to the static model and no circularities exist,
27611 then you are assured that your program will
27612 work using the dynamic model, providing that you remove any
27613 pragma Elaborate statements from the source.
27615 @node Treatment of Pragma Elaborate
27616 @section Treatment of Pragma Elaborate
27617 @cindex Pragma Elaborate
27620 The use of @code{pragma Elaborate}
27621 should generally be avoided in Ada 95 and Ada 2005 programs,
27622 since there is no guarantee that transitive calls
27623 will be properly handled. Indeed at one point, this pragma was placed
27624 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27626 Now that's a bit restrictive. In practice, the case in which
27627 @code{pragma Elaborate} is useful is when the caller knows that there
27628 are no transitive calls, or that the called unit contains all necessary
27629 transitive @code{pragma Elaborate} statements, and legacy code often
27630 contains such uses.
27632 Strictly speaking the static mode in GNAT should ignore such pragmas,
27633 since there is no assurance at compile time that the necessary safety
27634 conditions are met. In practice, this would cause GNAT to be incompatible
27635 with correctly written Ada 83 code that had all necessary
27636 @code{pragma Elaborate} statements in place. Consequently, we made the
27637 decision that GNAT in its default mode will believe that if it encounters
27638 a @code{pragma Elaborate} then the programmer knows what they are doing,
27639 and it will trust that no elaboration errors can occur.
27641 The result of this decision is two-fold. First to be safe using the
27642 static mode, you should remove all @code{pragma Elaborate} statements.
27643 Second, when fixing circularities in existing code, you can selectively
27644 use @code{pragma Elaborate} statements to convince the static mode of
27645 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
27648 When using the static mode with @option{-gnatwl}, any use of
27649 @code{pragma Elaborate} will generate a warning about possible
27652 @node Elaboration Issues for Library Tasks
27653 @section Elaboration Issues for Library Tasks
27654 @cindex Library tasks, elaboration issues
27655 @cindex Elaboration of library tasks
27658 In this section we examine special elaboration issues that arise for
27659 programs that declare library level tasks.
27661 Generally the model of execution of an Ada program is that all units are
27662 elaborated, and then execution of the program starts. However, the
27663 declaration of library tasks definitely does not fit this model. The
27664 reason for this is that library tasks start as soon as they are declared
27665 (more precisely, as soon as the statement part of the enclosing package
27666 body is reached), that is to say before elaboration
27667 of the program is complete. This means that if such a task calls a
27668 subprogram, or an entry in another task, the callee may or may not be
27669 elaborated yet, and in the standard
27670 Reference Manual model of dynamic elaboration checks, you can even
27671 get timing dependent Program_Error exceptions, since there can be
27672 a race between the elaboration code and the task code.
27674 The static model of elaboration in GNAT seeks to avoid all such
27675 dynamic behavior, by being conservative, and the conservative
27676 approach in this particular case is to assume that all the code
27677 in a task body is potentially executed at elaboration time if
27678 a task is declared at the library level.
27680 This can definitely result in unexpected circularities. Consider
27681 the following example
27683 @smallexample @c ada
27689 type My_Int is new Integer;
27691 function Ident (M : My_Int) return My_Int;
27695 package body Decls is
27696 task body Lib_Task is
27702 function Ident (M : My_Int) return My_Int is
27710 procedure Put_Val (Arg : Decls.My_Int);
27714 package body Utils is
27715 procedure Put_Val (Arg : Decls.My_Int) is
27717 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27724 Decls.Lib_Task.Start;
27729 If the above example is compiled in the default static elaboration
27730 mode, then a circularity occurs. The circularity comes from the call
27731 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
27732 this call occurs in elaboration code, we need an implicit pragma
27733 @code{Elaborate_All} for @code{Utils}. This means that not only must
27734 the spec and body of @code{Utils} be elaborated before the body
27735 of @code{Decls}, but also the spec and body of any unit that is
27736 @code{with'ed} by the body of @code{Utils} must also be elaborated before
27737 the body of @code{Decls}. This is the transitive implication of
27738 pragma @code{Elaborate_All} and it makes sense, because in general
27739 the body of @code{Put_Val} might have a call to something in a
27740 @code{with'ed} unit.
27742 In this case, the body of Utils (actually its spec) @code{with's}
27743 @code{Decls}. Unfortunately this means that the body of @code{Decls}
27744 must be elaborated before itself, in case there is a call from the
27745 body of @code{Utils}.
27747 Here is the exact chain of events we are worrying about:
27751 In the body of @code{Decls} a call is made from within the body of a library
27752 task to a subprogram in the package @code{Utils}. Since this call may
27753 occur at elaboration time (given that the task is activated at elaboration
27754 time), we have to assume the worst, i.e., that the
27755 call does happen at elaboration time.
27758 This means that the body and spec of @code{Util} must be elaborated before
27759 the body of @code{Decls} so that this call does not cause an access before
27763 Within the body of @code{Util}, specifically within the body of
27764 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
27768 One such @code{with}'ed package is package @code{Decls}, so there
27769 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
27770 In fact there is such a call in this example, but we would have to
27771 assume that there was such a call even if it were not there, since
27772 we are not supposed to write the body of @code{Decls} knowing what
27773 is in the body of @code{Utils}; certainly in the case of the
27774 static elaboration model, the compiler does not know what is in
27775 other bodies and must assume the worst.
27778 This means that the spec and body of @code{Decls} must also be
27779 elaborated before we elaborate the unit containing the call, but
27780 that unit is @code{Decls}! This means that the body of @code{Decls}
27781 must be elaborated before itself, and that's a circularity.
27785 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
27786 the body of @code{Decls} you will get a true Ada Reference Manual
27787 circularity that makes the program illegal.
27789 In practice, we have found that problems with the static model of
27790 elaboration in existing code often arise from library tasks, so
27791 we must address this particular situation.
27793 Note that if we compile and run the program above, using the dynamic model of
27794 elaboration (that is to say use the @option{-gnatE} switch),
27795 then it compiles, binds,
27796 links, and runs, printing the expected result of 2. Therefore in some sense
27797 the circularity here is only apparent, and we need to capture
27798 the properties of this program that distinguish it from other library-level
27799 tasks that have real elaboration problems.
27801 We have four possible answers to this question:
27806 Use the dynamic model of elaboration.
27808 If we use the @option{-gnatE} switch, then as noted above, the program works.
27809 Why is this? If we examine the task body, it is apparent that the task cannot
27811 @code{accept} statement until after elaboration has been completed, because
27812 the corresponding entry call comes from the main program, not earlier.
27813 This is why the dynamic model works here. But that's really giving
27814 up on a precise analysis, and we prefer to take this approach only if we cannot
27816 problem in any other manner. So let us examine two ways to reorganize
27817 the program to avoid the potential elaboration problem.
27820 Split library tasks into separate packages.
27822 Write separate packages, so that library tasks are isolated from
27823 other declarations as much as possible. Let us look at a variation on
27826 @smallexample @c ada
27834 package body Decls1 is
27835 task body Lib_Task is
27843 type My_Int is new Integer;
27844 function Ident (M : My_Int) return My_Int;
27848 package body Decls2 is
27849 function Ident (M : My_Int) return My_Int is
27857 procedure Put_Val (Arg : Decls2.My_Int);
27861 package body Utils is
27862 procedure Put_Val (Arg : Decls2.My_Int) is
27864 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
27871 Decls1.Lib_Task.Start;
27876 All we have done is to split @code{Decls} into two packages, one
27877 containing the library task, and one containing everything else. Now
27878 there is no cycle, and the program compiles, binds, links and executes
27879 using the default static model of elaboration.
27882 Declare separate task types.
27884 A significant part of the problem arises because of the use of the
27885 single task declaration form. This means that the elaboration of
27886 the task type, and the elaboration of the task itself (i.e.@: the
27887 creation of the task) happen at the same time. A good rule
27888 of style in Ada is to always create explicit task types. By
27889 following the additional step of placing task objects in separate
27890 packages from the task type declaration, many elaboration problems
27891 are avoided. Here is another modified example of the example program:
27893 @smallexample @c ada
27895 task type Lib_Task_Type is
27899 type My_Int is new Integer;
27901 function Ident (M : My_Int) return My_Int;
27905 package body Decls is
27906 task body Lib_Task_Type is
27912 function Ident (M : My_Int) return My_Int is
27920 procedure Put_Val (Arg : Decls.My_Int);
27924 package body Utils is
27925 procedure Put_Val (Arg : Decls.My_Int) is
27927 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27933 Lib_Task : Decls.Lib_Task_Type;
27939 Declst.Lib_Task.Start;
27944 What we have done here is to replace the @code{task} declaration in
27945 package @code{Decls} with a @code{task type} declaration. Then we
27946 introduce a separate package @code{Declst} to contain the actual
27947 task object. This separates the elaboration issues for
27948 the @code{task type}
27949 declaration, which causes no trouble, from the elaboration issues
27950 of the task object, which is also unproblematic, since it is now independent
27951 of the elaboration of @code{Utils}.
27952 This separation of concerns also corresponds to
27953 a generally sound engineering principle of separating declarations
27954 from instances. This version of the program also compiles, binds, links,
27955 and executes, generating the expected output.
27958 Use No_Entry_Calls_In_Elaboration_Code restriction.
27959 @cindex No_Entry_Calls_In_Elaboration_Code
27961 The previous two approaches described how a program can be restructured
27962 to avoid the special problems caused by library task bodies. in practice,
27963 however, such restructuring may be difficult to apply to existing legacy code,
27964 so we must consider solutions that do not require massive rewriting.
27966 Let us consider more carefully why our original sample program works
27967 under the dynamic model of elaboration. The reason is that the code
27968 in the task body blocks immediately on the @code{accept}
27969 statement. Now of course there is nothing to prohibit elaboration
27970 code from making entry calls (for example from another library level task),
27971 so we cannot tell in isolation that
27972 the task will not execute the accept statement during elaboration.
27974 However, in practice it is very unusual to see elaboration code
27975 make any entry calls, and the pattern of tasks starting
27976 at elaboration time and then immediately blocking on @code{accept} or
27977 @code{select} statements is very common. What this means is that
27978 the compiler is being too pessimistic when it analyzes the
27979 whole package body as though it might be executed at elaboration
27982 If we know that the elaboration code contains no entry calls, (a very safe
27983 assumption most of the time, that could almost be made the default
27984 behavior), then we can compile all units of the program under control
27985 of the following configuration pragma:
27988 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
27992 This pragma can be placed in the @file{gnat.adc} file in the usual
27993 manner. If we take our original unmodified program and compile it
27994 in the presence of a @file{gnat.adc} containing the above pragma,
27995 then once again, we can compile, bind, link, and execute, obtaining
27996 the expected result. In the presence of this pragma, the compiler does
27997 not trace calls in a task body, that appear after the first @code{accept}
27998 or @code{select} statement, and therefore does not report a potential
27999 circularity in the original program.
28001 The compiler will check to the extent it can that the above
28002 restriction is not violated, but it is not always possible to do a
28003 complete check at compile time, so it is important to use this
28004 pragma only if the stated restriction is in fact met, that is to say
28005 no task receives an entry call before elaboration of all units is completed.
28009 @node Mixing Elaboration Models
28010 @section Mixing Elaboration Models
28012 So far, we have assumed that the entire program is either compiled
28013 using the dynamic model or static model, ensuring consistency. It
28014 is possible to mix the two models, but rules have to be followed
28015 if this mixing is done to ensure that elaboration checks are not
28018 The basic rule is that @emph{a unit compiled with the static model cannot
28019 be @code{with'ed} by a unit compiled with the dynamic model}. The
28020 reason for this is that in the static model, a unit assumes that
28021 its clients guarantee to use (the equivalent of) pragma
28022 @code{Elaborate_All} so that no elaboration checks are required
28023 in inner subprograms, and this assumption is violated if the
28024 client is compiled with dynamic checks.
28026 The precise rule is as follows. A unit that is compiled with dynamic
28027 checks can only @code{with} a unit that meets at least one of the
28028 following criteria:
28033 The @code{with'ed} unit is itself compiled with dynamic elaboration
28034 checks (that is with the @option{-gnatE} switch.
28037 The @code{with'ed} unit is an internal GNAT implementation unit from
28038 the System, Interfaces, Ada, or GNAT hierarchies.
28041 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28044 The @code{with'ing} unit (that is the client) has an explicit pragma
28045 @code{Elaborate_All} for the @code{with'ed} unit.
28050 If this rule is violated, that is if a unit with dynamic elaboration
28051 checks @code{with's} a unit that does not meet one of the above four
28052 criteria, then the binder (@code{gnatbind}) will issue a warning
28053 similar to that in the following example:
28056 warning: "x.ads" has dynamic elaboration checks and with's
28057 warning: "y.ads" which has static elaboration checks
28061 These warnings indicate that the rule has been violated, and that as a result
28062 elaboration checks may be missed in the resulting executable file.
28063 This warning may be suppressed using the @option{-ws} binder switch
28064 in the usual manner.
28066 One useful application of this mixing rule is in the case of a subsystem
28067 which does not itself @code{with} units from the remainder of the
28068 application. In this case, the entire subsystem can be compiled with
28069 dynamic checks to resolve a circularity in the subsystem, while
28070 allowing the main application that uses this subsystem to be compiled
28071 using the more reliable default static model.
28073 @node What to Do If the Default Elaboration Behavior Fails
28074 @section What to Do If the Default Elaboration Behavior Fails
28077 If the binder cannot find an acceptable order, it outputs detailed
28078 diagnostics. For example:
28084 error: elaboration circularity detected
28085 info: "proc (body)" must be elaborated before "pack (body)"
28086 info: reason: Elaborate_All probably needed in unit "pack (body)"
28087 info: recompile "pack (body)" with -gnatwl
28088 info: for full details
28089 info: "proc (body)"
28090 info: is needed by its spec:
28091 info: "proc (spec)"
28092 info: which is withed by:
28093 info: "pack (body)"
28094 info: "pack (body)" must be elaborated before "proc (body)"
28095 info: reason: pragma Elaborate in unit "proc (body)"
28101 In this case we have a cycle that the binder cannot break. On the one
28102 hand, there is an explicit pragma Elaborate in @code{proc} for
28103 @code{pack}. This means that the body of @code{pack} must be elaborated
28104 before the body of @code{proc}. On the other hand, there is elaboration
28105 code in @code{pack} that calls a subprogram in @code{proc}. This means
28106 that for maximum safety, there should really be a pragma
28107 Elaborate_All in @code{pack} for @code{proc} which would require that
28108 the body of @code{proc} be elaborated before the body of
28109 @code{pack}. Clearly both requirements cannot be satisfied.
28110 Faced with a circularity of this kind, you have three different options.
28113 @item Fix the program
28114 The most desirable option from the point of view of long-term maintenance
28115 is to rearrange the program so that the elaboration problems are avoided.
28116 One useful technique is to place the elaboration code into separate
28117 child packages. Another is to move some of the initialization code to
28118 explicitly called subprograms, where the program controls the order
28119 of initialization explicitly. Although this is the most desirable option,
28120 it may be impractical and involve too much modification, especially in
28121 the case of complex legacy code.
28123 @item Perform dynamic checks
28124 If the compilations are done using the
28126 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28127 manner. Dynamic checks are generated for all calls that could possibly result
28128 in raising an exception. With this switch, the compiler does not generate
28129 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28130 exactly as specified in the @cite{Ada Reference Manual}.
28131 The binder will generate
28132 an executable program that may or may not raise @code{Program_Error}, and then
28133 it is the programmer's job to ensure that it does not raise an exception. Note
28134 that it is important to compile all units with the switch, it cannot be used
28137 @item Suppress checks
28138 The drawback of dynamic checks is that they generate a
28139 significant overhead at run time, both in space and time. If you
28140 are absolutely sure that your program cannot raise any elaboration
28141 exceptions, and you still want to use the dynamic elaboration model,
28142 then you can use the configuration pragma
28143 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28144 example this pragma could be placed in the @file{gnat.adc} file.
28146 @item Suppress checks selectively
28147 When you know that certain calls or instantiations in elaboration code cannot
28148 possibly lead to an elaboration error, and the binder nevertheless complains
28149 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28150 elaboration circularities, it is possible to remove those warnings locally and
28151 obtain a program that will bind. Clearly this can be unsafe, and it is the
28152 responsibility of the programmer to make sure that the resulting program has no
28153 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28154 used with different granularity to suppress warnings and break elaboration
28159 Place the pragma that names the called subprogram in the declarative part
28160 that contains the call.
28163 Place the pragma in the declarative part, without naming an entity. This
28164 disables warnings on all calls in the corresponding declarative region.
28167 Place the pragma in the package spec that declares the called subprogram,
28168 and name the subprogram. This disables warnings on all elaboration calls to
28172 Place the pragma in the package spec that declares the called subprogram,
28173 without naming any entity. This disables warnings on all elaboration calls to
28174 all subprograms declared in this spec.
28176 @item Use Pragma Elaborate
28177 As previously described in section @xref{Treatment of Pragma Elaborate},
28178 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28179 that no elaboration checks are required on calls to the designated unit.
28180 There may be cases in which the caller knows that no transitive calls
28181 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28182 case where @code{pragma Elaborate_All} would cause a circularity.
28186 These five cases are listed in order of decreasing safety, and therefore
28187 require increasing programmer care in their application. Consider the
28190 @smallexample @c adanocomment
28192 function F1 return Integer;
28197 function F2 return Integer;
28198 function Pure (x : integer) return integer;
28199 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
28200 -- pragma Suppress (Elaboration_Check); -- (4)
28204 package body Pack1 is
28205 function F1 return Integer is
28209 Val : integer := Pack2.Pure (11); -- Elab. call (1)
28212 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
28213 -- pragma Suppress(Elaboration_Check); -- (2)
28215 X1 := Pack2.F2 + 1; -- Elab. call (2)
28220 package body Pack2 is
28221 function F2 return Integer is
28225 function Pure (x : integer) return integer is
28227 return x ** 3 - 3 * x;
28231 with Pack1, Ada.Text_IO;
28234 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28237 In the absence of any pragmas, an attempt to bind this program produces
28238 the following diagnostics:
28244 error: elaboration circularity detected
28245 info: "pack1 (body)" must be elaborated before "pack1 (body)"
28246 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
28247 info: recompile "pack1 (body)" with -gnatwl for full details
28248 info: "pack1 (body)"
28249 info: must be elaborated along with its spec:
28250 info: "pack1 (spec)"
28251 info: which is withed by:
28252 info: "pack2 (body)"
28253 info: which must be elaborated along with its spec:
28254 info: "pack2 (spec)"
28255 info: which is withed by:
28256 info: "pack1 (body)"
28259 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28260 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28261 F2 is safe, even though F2 calls F1, because the call appears after the
28262 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28263 remove the warning on the call. It is also possible to use pragma (2)
28264 because there are no other potentially unsafe calls in the block.
28267 The call to @code{Pure} is safe because this function does not depend on the
28268 state of @code{Pack2}. Therefore any call to this function is safe, and it
28269 is correct to place pragma (3) in the corresponding package spec.
28272 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28273 warnings on all calls to functions declared therein. Note that this is not
28274 necessarily safe, and requires more detailed examination of the subprogram
28275 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28276 be already elaborated.
28280 It is hard to generalize on which of these four approaches should be
28281 taken. Obviously if it is possible to fix the program so that the default
28282 treatment works, this is preferable, but this may not always be practical.
28283 It is certainly simple enough to use
28285 but the danger in this case is that, even if the GNAT binder
28286 finds a correct elaboration order, it may not always do so,
28287 and certainly a binder from another Ada compiler might not. A
28288 combination of testing and analysis (for which the warnings generated
28291 switch can be useful) must be used to ensure that the program is free
28292 of errors. One switch that is useful in this testing is the
28293 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28296 Normally the binder tries to find an order that has the best chance
28297 of avoiding elaboration problems. However, if this switch is used, the binder
28298 plays a devil's advocate role, and tries to choose the order that
28299 has the best chance of failing. If your program works even with this
28300 switch, then it has a better chance of being error free, but this is still
28303 For an example of this approach in action, consider the C-tests (executable
28304 tests) from the ACVC suite. If these are compiled and run with the default
28305 treatment, then all but one of them succeed without generating any error
28306 diagnostics from the binder. However, there is one test that fails, and
28307 this is not surprising, because the whole point of this test is to ensure
28308 that the compiler can handle cases where it is impossible to determine
28309 a correct order statically, and it checks that an exception is indeed
28310 raised at run time.
28312 This one test must be compiled and run using the
28314 switch, and then it passes. Alternatively, the entire suite can
28315 be run using this switch. It is never wrong to run with the dynamic
28316 elaboration switch if your code is correct, and we assume that the
28317 C-tests are indeed correct (it is less efficient, but efficiency is
28318 not a factor in running the ACVC tests.)
28320 @node Elaboration for Access-to-Subprogram Values
28321 @section Elaboration for Access-to-Subprogram Values
28322 @cindex Access-to-subprogram
28325 Access-to-subprogram types (introduced in Ada 95) complicate
28326 the handling of elaboration. The trouble is that it becomes
28327 impossible to tell at compile time which procedure
28328 is being called. This means that it is not possible for the binder
28329 to analyze the elaboration requirements in this case.
28331 If at the point at which the access value is created
28332 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28333 the body of the subprogram is
28334 known to have been elaborated, then the access value is safe, and its use
28335 does not require a check. This may be achieved by appropriate arrangement
28336 of the order of declarations if the subprogram is in the current unit,
28337 or, if the subprogram is in another unit, by using pragma
28338 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28339 on the referenced unit.
28341 If the referenced body is not known to have been elaborated at the point
28342 the access value is created, then any use of the access value must do a
28343 dynamic check, and this dynamic check will fail and raise a
28344 @code{Program_Error} exception if the body has not been elaborated yet.
28345 GNAT will generate the necessary checks, and in addition, if the
28347 switch is set, will generate warnings that such checks are required.
28349 The use of dynamic dispatching for tagged types similarly generates
28350 a requirement for dynamic checks, and premature calls to any primitive
28351 operation of a tagged type before the body of the operation has been
28352 elaborated, will result in the raising of @code{Program_Error}.
28354 @node Summary of Procedures for Elaboration Control
28355 @section Summary of Procedures for Elaboration Control
28356 @cindex Elaboration control
28359 First, compile your program with the default options, using none of
28360 the special elaboration control switches. If the binder successfully
28361 binds your program, then you can be confident that, apart from issues
28362 raised by the use of access-to-subprogram types and dynamic dispatching,
28363 the program is free of elaboration errors. If it is important that the
28364 program be portable, then use the
28366 switch to generate warnings about missing @code{Elaborate} or
28367 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28369 If the program fails to bind using the default static elaboration
28370 handling, then you can fix the program to eliminate the binder
28371 message, or recompile the entire program with the
28372 @option{-gnatE} switch to generate dynamic elaboration checks,
28373 and, if you are sure there really are no elaboration problems,
28374 use a global pragma @code{Suppress (Elaboration_Check)}.
28376 @node Other Elaboration Order Considerations
28377 @section Other Elaboration Order Considerations
28379 This section has been entirely concerned with the issue of finding a valid
28380 elaboration order, as defined by the Ada Reference Manual. In a case
28381 where several elaboration orders are valid, the task is to find one
28382 of the possible valid elaboration orders (and the static model in GNAT
28383 will ensure that this is achieved).
28385 The purpose of the elaboration rules in the Ada Reference Manual is to
28386 make sure that no entity is accessed before it has been elaborated. For
28387 a subprogram, this means that the spec and body must have been elaborated
28388 before the subprogram is called. For an object, this means that the object
28389 must have been elaborated before its value is read or written. A violation
28390 of either of these two requirements is an access before elaboration order,
28391 and this section has been all about avoiding such errors.
28393 In the case where more than one order of elaboration is possible, in the
28394 sense that access before elaboration errors are avoided, then any one of
28395 the orders is ``correct'' in the sense that it meets the requirements of
28396 the Ada Reference Manual, and no such error occurs.
28398 However, it may be the case for a given program, that there are
28399 constraints on the order of elaboration that come not from consideration
28400 of avoiding elaboration errors, but rather from extra-lingual logic
28401 requirements. Consider this example:
28403 @smallexample @c ada
28404 with Init_Constants;
28405 package Constants is
28410 package Init_Constants is
28411 procedure P; -- require a body
28412 end Init_Constants;
28415 package body Init_Constants is
28416 procedure P is begin null; end;
28420 end Init_Constants;
28424 Z : Integer := Constants.X + Constants.Y;
28428 with Text_IO; use Text_IO;
28431 Put_Line (Calc.Z'Img);
28436 In this example, there is more than one valid order of elaboration. For
28437 example both the following are correct orders:
28440 Init_Constants spec
28443 Init_Constants body
28448 Init_Constants spec
28449 Init_Constants body
28456 There is no language rule to prefer one or the other, both are correct
28457 from an order of elaboration point of view. But the programmatic effects
28458 of the two orders are very different. In the first, the elaboration routine
28459 of @code{Calc} initializes @code{Z} to zero, and then the main program
28460 runs with this value of zero. But in the second order, the elaboration
28461 routine of @code{Calc} runs after the body of Init_Constants has set
28462 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
28465 One could perhaps by applying pretty clever non-artificial intelligence
28466 to the situation guess that it is more likely that the second order of
28467 elaboration is the one desired, but there is no formal linguistic reason
28468 to prefer one over the other. In fact in this particular case, GNAT will
28469 prefer the second order, because of the rule that bodies are elaborated
28470 as soon as possible, but it's just luck that this is what was wanted
28471 (if indeed the second order was preferred).
28473 If the program cares about the order of elaboration routines in a case like
28474 this, it is important to specify the order required. In this particular
28475 case, that could have been achieved by adding to the spec of Calc:
28477 @smallexample @c ada
28478 pragma Elaborate_All (Constants);
28482 which requires that the body (if any) and spec of @code{Constants},
28483 as well as the body and spec of any unit @code{with}'ed by
28484 @code{Constants} be elaborated before @code{Calc} is elaborated.
28486 Clearly no automatic method can always guess which alternative you require,
28487 and if you are working with legacy code that had constraints of this kind
28488 which were not properly specified by adding @code{Elaborate} or
28489 @code{Elaborate_All} pragmas, then indeed it is possible that two different
28490 compilers can choose different orders.
28492 However, GNAT does attempt to diagnose the common situation where there
28493 are uninitialized variables in the visible part of a package spec, and the
28494 corresponding package body has an elaboration block that directly or
28495 indirectly initialized one or more of these variables. This is the situation
28496 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28497 a warning that suggests this addition if it detects this situation.
28499 The @code{gnatbind}
28500 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
28501 out problems. This switch causes bodies to be elaborated as late as possible
28502 instead of as early as possible. In the example above, it would have forced
28503 the choice of the first elaboration order. If you get different results
28504 when using this switch, and particularly if one set of results is right,
28505 and one is wrong as far as you are concerned, it shows that you have some
28506 missing @code{Elaborate} pragmas. For the example above, we have the
28510 gnatmake -f -q main
28513 gnatmake -f -q main -bargs -p
28519 It is of course quite unlikely that both these results are correct, so
28520 it is up to you in a case like this to investigate the source of the
28521 difference, by looking at the two elaboration orders that are chosen,
28522 and figuring out which is correct, and then adding the necessary
28523 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
28527 @c *******************************
28528 @node Conditional Compilation
28529 @appendix Conditional Compilation
28530 @c *******************************
28531 @cindex Conditional compilation
28534 It is often necessary to arrange for a single source program
28535 to serve multiple purposes, where it is compiled in different
28536 ways to achieve these different goals. Some examples of the
28537 need for this feature are
28540 @item Adapting a program to a different hardware environment
28541 @item Adapting a program to a different target architecture
28542 @item Turning debugging features on and off
28543 @item Arranging for a program to compile with different compilers
28547 In C, or C++, the typical approach would be to use the preprocessor
28548 that is defined as part of the language. The Ada language does not
28549 contain such a feature. This is not an oversight, but rather a very
28550 deliberate design decision, based on the experience that overuse of
28551 the preprocessing features in C and C++ can result in programs that
28552 are extremely difficult to maintain. For example, if we have ten
28553 switches that can be on or off, this means that there are a thousand
28554 separate programs, any one of which might not even be syntactically
28555 correct, and even if syntactically correct, the resulting program
28556 might not work correctly. Testing all combinations can quickly become
28559 Nevertheless, the need to tailor programs certainly exists, and in
28560 this Appendix we will discuss how this can
28561 be achieved using Ada in general, and GNAT in particular.
28564 * Use of Boolean Constants::
28565 * Debugging - A Special Case::
28566 * Conditionalizing Declarations::
28567 * Use of Alternative Implementations::
28571 @node Use of Boolean Constants
28572 @section Use of Boolean Constants
28575 In the case where the difference is simply which code
28576 sequence is executed, the cleanest solution is to use Boolean
28577 constants to control which code is executed.
28579 @smallexample @c ada
28581 FP_Initialize_Required : constant Boolean := True;
28583 if FP_Initialize_Required then
28590 Not only will the code inside the @code{if} statement not be executed if
28591 the constant Boolean is @code{False}, but it will also be completely
28592 deleted from the program.
28593 However, the code is only deleted after the @code{if} statement
28594 has been checked for syntactic and semantic correctness.
28595 (In contrast, with preprocessors the code is deleted before the
28596 compiler ever gets to see it, so it is not checked until the switch
28598 @cindex Preprocessors (contrasted with conditional compilation)
28600 Typically the Boolean constants will be in a separate package,
28603 @smallexample @c ada
28606 FP_Initialize_Required : constant Boolean := True;
28607 Reset_Available : constant Boolean := False;
28614 The @code{Config} package exists in multiple forms for the various targets,
28615 with an appropriate script selecting the version of @code{Config} needed.
28616 Then any other unit requiring conditional compilation can do a @code{with}
28617 of @code{Config} to make the constants visible.
28620 @node Debugging - A Special Case
28621 @section Debugging - A Special Case
28624 A common use of conditional code is to execute statements (for example
28625 dynamic checks, or output of intermediate results) under control of a
28626 debug switch, so that the debugging behavior can be turned on and off.
28627 This can be done using a Boolean constant to control whether the code
28630 @smallexample @c ada
28633 Put_Line ("got to the first stage!");
28641 @smallexample @c ada
28643 if Debugging and then Temperature > 999.0 then
28644 raise Temperature_Crazy;
28650 Since this is a common case, there are special features to deal with
28651 this in a convenient manner. For the case of tests, Ada 2005 has added
28652 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
28653 @cindex pragma @code{Assert}
28654 on the @code{Assert} pragma that has always been available in GNAT, so this
28655 feature may be used with GNAT even if you are not using Ada 2005 features.
28656 The use of pragma @code{Assert} is described in
28657 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
28658 example, the last test could be written:
28660 @smallexample @c ada
28661 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
28667 @smallexample @c ada
28668 pragma Assert (Temperature <= 999.0);
28672 In both cases, if assertions are active and the temperature is excessive,
28673 the exception @code{Assert_Failure} will be raised, with the given string in
28674 the first case or a string indicating the location of the pragma in the second
28675 case used as the exception message.
28677 You can turn assertions on and off by using the @code{Assertion_Policy}
28679 @cindex pragma @code{Assertion_Policy}
28680 This is an Ada 2005 pragma which is implemented in all modes by
28681 GNAT, but only in the latest versions of GNAT which include Ada 2005
28682 capability. Alternatively, you can use the @option{-gnata} switch
28683 @cindex @option{-gnata} switch
28684 to enable assertions from the command line (this is recognized by all versions
28687 For the example above with the @code{Put_Line}, the GNAT-specific pragma
28688 @code{Debug} can be used:
28689 @cindex pragma @code{Debug}
28691 @smallexample @c ada
28692 pragma Debug (Put_Line ("got to the first stage!"));
28696 If debug pragmas are enabled, the argument, which must be of the form of
28697 a procedure call, is executed (in this case, @code{Put_Line} will be called).
28698 Only one call can be present, but of course a special debugging procedure
28699 containing any code you like can be included in the program and then
28700 called in a pragma @code{Debug} argument as needed.
28702 One advantage of pragma @code{Debug} over the @code{if Debugging then}
28703 construct is that pragma @code{Debug} can appear in declarative contexts,
28704 such as at the very beginning of a procedure, before local declarations have
28707 Debug pragmas are enabled using either the @option{-gnata} switch that also
28708 controls assertions, or with a separate Debug_Policy pragma.
28709 @cindex pragma @code{Debug_Policy}
28710 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
28711 in Ada 95 and Ada 83 programs as well), and is analogous to
28712 pragma @code{Assertion_Policy} to control assertions.
28714 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
28715 and thus they can appear in @file{gnat.adc} if you are not using a
28716 project file, or in the file designated to contain configuration pragmas
28718 They then apply to all subsequent compilations. In practice the use of
28719 the @option{-gnata} switch is often the most convenient method of controlling
28720 the status of these pragmas.
28722 Note that a pragma is not a statement, so in contexts where a statement
28723 sequence is required, you can't just write a pragma on its own. You have
28724 to add a @code{null} statement.
28726 @smallexample @c ada
28729 @dots{} -- some statements
28731 pragma Assert (Num_Cases < 10);
28738 @node Conditionalizing Declarations
28739 @section Conditionalizing Declarations
28742 In some cases, it may be necessary to conditionalize declarations to meet
28743 different requirements. For example we might want a bit string whose length
28744 is set to meet some hardware message requirement.
28746 In some cases, it may be possible to do this using declare blocks controlled
28747 by conditional constants:
28749 @smallexample @c ada
28751 if Small_Machine then
28753 X : Bit_String (1 .. 10);
28759 X : Large_Bit_String (1 .. 1000);
28768 Note that in this approach, both declarations are analyzed by the
28769 compiler so this can only be used where both declarations are legal,
28770 even though one of them will not be used.
28772 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
28773 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
28774 that are parameterized by these constants. For example
28776 @smallexample @c ada
28779 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
28785 If @code{Bits_Per_Word} is set to 32, this generates either
28787 @smallexample @c ada
28790 Field1 at 0 range 0 .. 32;
28796 for the big endian case, or
28798 @smallexample @c ada
28801 Field1 at 0 range 10 .. 32;
28807 for the little endian case. Since a powerful subset of Ada expression
28808 notation is usable for creating static constants, clever use of this
28809 feature can often solve quite difficult problems in conditionalizing
28810 compilation (note incidentally that in Ada 95, the little endian
28811 constant was introduced as @code{System.Default_Bit_Order}, so you do not
28812 need to define this one yourself).
28815 @node Use of Alternative Implementations
28816 @section Use of Alternative Implementations
28819 In some cases, none of the approaches described above are adequate. This
28820 can occur for example if the set of declarations required is radically
28821 different for two different configurations.
28823 In this situation, the official Ada way of dealing with conditionalizing
28824 such code is to write separate units for the different cases. As long as
28825 this does not result in excessive duplication of code, this can be done
28826 without creating maintenance problems. The approach is to share common
28827 code as far as possible, and then isolate the code and declarations
28828 that are different. Subunits are often a convenient method for breaking
28829 out a piece of a unit that is to be conditionalized, with separate files
28830 for different versions of the subunit for different targets, where the
28831 build script selects the right one to give to the compiler.
28832 @cindex Subunits (and conditional compilation)
28834 As an example, consider a situation where a new feature in Ada 2005
28835 allows something to be done in a really nice way. But your code must be able
28836 to compile with an Ada 95 compiler. Conceptually you want to say:
28838 @smallexample @c ada
28841 @dots{} neat Ada 2005 code
28843 @dots{} not quite as neat Ada 95 code
28849 where @code{Ada_2005} is a Boolean constant.
28851 But this won't work when @code{Ada_2005} is set to @code{False},
28852 since the @code{then} clause will be illegal for an Ada 95 compiler.
28853 (Recall that although such unreachable code would eventually be deleted
28854 by the compiler, it still needs to be legal. If it uses features
28855 introduced in Ada 2005, it will be illegal in Ada 95.)
28857 So instead we write
28859 @smallexample @c ada
28860 procedure Insert is separate;
28864 Then we have two files for the subunit @code{Insert}, with the two sets of
28866 If the package containing this is called @code{File_Queries}, then we might
28870 @item @file{file_queries-insert-2005.adb}
28871 @item @file{file_queries-insert-95.adb}
28875 and the build script renames the appropriate file to
28878 file_queries-insert.adb
28882 and then carries out the compilation.
28884 This can also be done with project files' naming schemes. For example:
28886 @smallexample @c project
28887 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
28891 Note also that with project files it is desirable to use a different extension
28892 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
28893 conflict may arise through another commonly used feature: to declare as part
28894 of the project a set of directories containing all the sources obeying the
28895 default naming scheme.
28897 The use of alternative units is certainly feasible in all situations,
28898 and for example the Ada part of the GNAT run-time is conditionalized
28899 based on the target architecture using this approach. As a specific example,
28900 consider the implementation of the AST feature in VMS. There is one
28908 which is the same for all architectures, and three bodies:
28912 used for all non-VMS operating systems
28913 @item s-asthan-vms-alpha.adb
28914 used for VMS on the Alpha
28915 @item s-asthan-vms-ia64.adb
28916 used for VMS on the ia64
28920 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28921 this operating system feature is not available, and the two remaining
28922 versions interface with the corresponding versions of VMS to provide
28923 VMS-compatible AST handling. The GNAT build script knows the architecture
28924 and operating system, and automatically selects the right version,
28925 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28927 Another style for arranging alternative implementations is through Ada's
28928 access-to-subprogram facility.
28929 In case some functionality is to be conditionally included,
28930 you can declare an access-to-procedure variable @code{Ref} that is initialized
28931 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28933 In some library package, set @code{Ref} to @code{Proc'Access} for some
28934 procedure @code{Proc} that performs the relevant processing.
28935 The initialization only occurs if the library package is included in the
28937 The same idea can also be implemented using tagged types and dispatching
28941 @node Preprocessing
28942 @section Preprocessing
28943 @cindex Preprocessing
28946 Although it is quite possible to conditionalize code without the use of
28947 C-style preprocessing, as described earlier in this section, it is
28948 nevertheless convenient in some cases to use the C approach. Moreover,
28949 older Ada compilers have often provided some preprocessing capability,
28950 so legacy code may depend on this approach, even though it is not
28953 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28954 extent on the various preprocessors that have been used
28955 with legacy code on other compilers, to enable easier transition).
28957 The preprocessor may be used in two separate modes. It can be used quite
28958 separately from the compiler, to generate a separate output source file
28959 that is then fed to the compiler as a separate step. This is the
28960 @code{gnatprep} utility, whose use is fully described in
28961 @ref{Preprocessing Using gnatprep}.
28962 @cindex @code{gnatprep}
28964 The preprocessing language allows such constructs as
28968 #if DEBUG or PRIORITY > 4 then
28969 bunch of declarations
28971 completely different bunch of declarations
28977 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28978 defined either on the command line or in a separate file.
28980 The other way of running the preprocessor is even closer to the C style and
28981 often more convenient. In this approach the preprocessing is integrated into
28982 the compilation process. The compiler is fed the preprocessor input which
28983 includes @code{#if} lines etc, and then the compiler carries out the
28984 preprocessing internally and processes the resulting output.
28985 For more details on this approach, see @ref{Integrated Preprocessing}.
28988 @c *******************************
28989 @node Inline Assembler
28990 @appendix Inline Assembler
28991 @c *******************************
28994 If you need to write low-level software that interacts directly
28995 with the hardware, Ada provides two ways to incorporate assembly
28996 language code into your program. First, you can import and invoke
28997 external routines written in assembly language, an Ada feature fully
28998 supported by GNAT@. However, for small sections of code it may be simpler
28999 or more efficient to include assembly language statements directly
29000 in your Ada source program, using the facilities of the implementation-defined
29001 package @code{System.Machine_Code}, which incorporates the gcc
29002 Inline Assembler. The Inline Assembler approach offers a number of advantages,
29003 including the following:
29006 @item No need to use non-Ada tools
29007 @item Consistent interface over different targets
29008 @item Automatic usage of the proper calling conventions
29009 @item Access to Ada constants and variables
29010 @item Definition of intrinsic routines
29011 @item Possibility of inlining a subprogram comprising assembler code
29012 @item Code optimizer can take Inline Assembler code into account
29015 This chapter presents a series of examples to show you how to use
29016 the Inline Assembler. Although it focuses on the Intel x86,
29017 the general approach applies also to other processors.
29018 It is assumed that you are familiar with Ada
29019 and with assembly language programming.
29022 * Basic Assembler Syntax::
29023 * A Simple Example of Inline Assembler::
29024 * Output Variables in Inline Assembler::
29025 * Input Variables in Inline Assembler::
29026 * Inlining Inline Assembler Code::
29027 * Other Asm Functionality::
29030 @c ---------------------------------------------------------------------------
29031 @node Basic Assembler Syntax
29032 @section Basic Assembler Syntax
29035 The assembler used by GNAT and gcc is based not on the Intel assembly
29036 language, but rather on a language that descends from the AT&T Unix
29037 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29038 The following table summarizes the main features of @emph{as} syntax
29039 and points out the differences from the Intel conventions.
29040 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29041 pre-processor) documentation for further information.
29044 @item Register names
29045 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29047 Intel: No extra punctuation; for example @code{eax}
29049 @item Immediate operand
29050 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29052 Intel: No extra punctuation; for example @code{4}
29055 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29057 Intel: No extra punctuation; for example @code{loc}
29059 @item Memory contents
29060 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29062 Intel: Square brackets; for example @code{[loc]}
29064 @item Register contents
29065 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29067 Intel: Square brackets; for example @code{[eax]}
29069 @item Hexadecimal numbers
29070 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29072 Intel: Trailing ``h''; for example @code{A0h}
29075 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29078 Intel: Implicit, deduced by assembler; for example @code{mov}
29080 @item Instruction repetition
29081 gcc / @emph{as}: Split into two lines; for example
29087 Intel: Keep on one line; for example @code{rep stosl}
29089 @item Order of operands
29090 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29092 Intel: Destination first; for example @code{mov eax, 4}
29095 @c ---------------------------------------------------------------------------
29096 @node A Simple Example of Inline Assembler
29097 @section A Simple Example of Inline Assembler
29100 The following example will generate a single assembly language statement,
29101 @code{nop}, which does nothing. Despite its lack of run-time effect,
29102 the example will be useful in illustrating the basics of
29103 the Inline Assembler facility.
29105 @smallexample @c ada
29107 with System.Machine_Code; use System.Machine_Code;
29108 procedure Nothing is
29115 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29116 here it takes one parameter, a @emph{template string} that must be a static
29117 expression and that will form the generated instruction.
29118 @code{Asm} may be regarded as a compile-time procedure that parses
29119 the template string and additional parameters (none here),
29120 from which it generates a sequence of assembly language instructions.
29122 The examples in this chapter will illustrate several of the forms
29123 for invoking @code{Asm}; a complete specification of the syntax
29124 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29127 Under the standard GNAT conventions, the @code{Nothing} procedure
29128 should be in a file named @file{nothing.adb}.
29129 You can build the executable in the usual way:
29133 However, the interesting aspect of this example is not its run-time behavior
29134 but rather the generated assembly code.
29135 To see this output, invoke the compiler as follows:
29137 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29139 where the options are:
29143 compile only (no bind or link)
29145 generate assembler listing
29146 @item -fomit-frame-pointer
29147 do not set up separate stack frames
29149 do not add runtime checks
29152 This gives a human-readable assembler version of the code. The resulting
29153 file will have the same name as the Ada source file, but with a @code{.s}
29154 extension. In our example, the file @file{nothing.s} has the following
29159 .file "nothing.adb"
29161 ___gnu_compiled_ada:
29164 .globl __ada_nothing
29176 The assembly code you included is clearly indicated by
29177 the compiler, between the @code{#APP} and @code{#NO_APP}
29178 delimiters. The character before the 'APP' and 'NOAPP'
29179 can differ on different targets. For example, GNU/Linux uses '#APP' while
29180 on NT you will see '/APP'.
29182 If you make a mistake in your assembler code (such as using the
29183 wrong size modifier, or using a wrong operand for the instruction) GNAT
29184 will report this error in a temporary file, which will be deleted when
29185 the compilation is finished. Generating an assembler file will help
29186 in such cases, since you can assemble this file separately using the
29187 @emph{as} assembler that comes with gcc.
29189 Assembling the file using the command
29192 as @file{nothing.s}
29195 will give you error messages whose lines correspond to the assembler
29196 input file, so you can easily find and correct any mistakes you made.
29197 If there are no errors, @emph{as} will generate an object file
29198 @file{nothing.out}.
29200 @c ---------------------------------------------------------------------------
29201 @node Output Variables in Inline Assembler
29202 @section Output Variables in Inline Assembler
29205 The examples in this section, showing how to access the processor flags,
29206 illustrate how to specify the destination operands for assembly language
29209 @smallexample @c ada
29211 with Interfaces; use Interfaces;
29212 with Ada.Text_IO; use Ada.Text_IO;
29213 with System.Machine_Code; use System.Machine_Code;
29214 procedure Get_Flags is
29215 Flags : Unsigned_32;
29218 Asm ("pushfl" & LF & HT & -- push flags on stack
29219 "popl %%eax" & LF & HT & -- load eax with flags
29220 "movl %%eax, %0", -- store flags in variable
29221 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29222 Put_Line ("Flags register:" & Flags'Img);
29227 In order to have a nicely aligned assembly listing, we have separated
29228 multiple assembler statements in the Asm template string with linefeed
29229 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29230 The resulting section of the assembly output file is:
29237 movl %eax, -40(%ebp)
29242 It would have been legal to write the Asm invocation as:
29245 Asm ("pushfl popl %%eax movl %%eax, %0")
29248 but in the generated assembler file, this would come out as:
29252 pushfl popl %eax movl %eax, -40(%ebp)
29256 which is not so convenient for the human reader.
29258 We use Ada comments
29259 at the end of each line to explain what the assembler instructions
29260 actually do. This is a useful convention.
29262 When writing Inline Assembler instructions, you need to precede each register
29263 and variable name with a percent sign. Since the assembler already requires
29264 a percent sign at the beginning of a register name, you need two consecutive
29265 percent signs for such names in the Asm template string, thus @code{%%eax}.
29266 In the generated assembly code, one of the percent signs will be stripped off.
29268 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29269 variables: operands you later define using @code{Input} or @code{Output}
29270 parameters to @code{Asm}.
29271 An output variable is illustrated in
29272 the third statement in the Asm template string:
29276 The intent is to store the contents of the eax register in a variable that can
29277 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
29278 necessarily work, since the compiler might optimize by using a register
29279 to hold Flags, and the expansion of the @code{movl} instruction would not be
29280 aware of this optimization. The solution is not to store the result directly
29281 but rather to advise the compiler to choose the correct operand form;
29282 that is the purpose of the @code{%0} output variable.
29284 Information about the output variable is supplied in the @code{Outputs}
29285 parameter to @code{Asm}:
29287 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29290 The output is defined by the @code{Asm_Output} attribute of the target type;
29291 the general format is
29293 Type'Asm_Output (constraint_string, variable_name)
29296 The constraint string directs the compiler how
29297 to store/access the associated variable. In the example
29299 Unsigned_32'Asm_Output ("=m", Flags);
29301 the @code{"m"} (memory) constraint tells the compiler that the variable
29302 @code{Flags} should be stored in a memory variable, thus preventing
29303 the optimizer from keeping it in a register. In contrast,
29305 Unsigned_32'Asm_Output ("=r", Flags);
29307 uses the @code{"r"} (register) constraint, telling the compiler to
29308 store the variable in a register.
29310 If the constraint is preceded by the equal character (@strong{=}), it tells
29311 the compiler that the variable will be used to store data into it.
29313 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29314 allowing the optimizer to choose whatever it deems best.
29316 There are a fairly large number of constraints, but the ones that are
29317 most useful (for the Intel x86 processor) are the following:
29323 global (i.e.@: can be stored anywhere)
29341 use one of eax, ebx, ecx or edx
29343 use one of eax, ebx, ecx, edx, esi or edi
29346 The full set of constraints is described in the gcc and @emph{as}
29347 documentation; note that it is possible to combine certain constraints
29348 in one constraint string.
29350 You specify the association of an output variable with an assembler operand
29351 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29353 @smallexample @c ada
29355 Asm ("pushfl" & LF & HT & -- push flags on stack
29356 "popl %%eax" & LF & HT & -- load eax with flags
29357 "movl %%eax, %0", -- store flags in variable
29358 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29362 @code{%0} will be replaced in the expanded code by the appropriate operand,
29364 the compiler decided for the @code{Flags} variable.
29366 In general, you may have any number of output variables:
29369 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29371 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29372 of @code{Asm_Output} attributes
29376 @smallexample @c ada
29378 Asm ("movl %%eax, %0" & LF & HT &
29379 "movl %%ebx, %1" & LF & HT &
29381 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
29382 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
29383 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
29387 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29388 in the Ada program.
29390 As a variation on the @code{Get_Flags} example, we can use the constraints
29391 string to direct the compiler to store the eax register into the @code{Flags}
29392 variable, instead of including the store instruction explicitly in the
29393 @code{Asm} template string:
29395 @smallexample @c ada
29397 with Interfaces; use Interfaces;
29398 with Ada.Text_IO; use Ada.Text_IO;
29399 with System.Machine_Code; use System.Machine_Code;
29400 procedure Get_Flags_2 is
29401 Flags : Unsigned_32;
29404 Asm ("pushfl" & LF & HT & -- push flags on stack
29405 "popl %%eax", -- save flags in eax
29406 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29407 Put_Line ("Flags register:" & Flags'Img);
29413 The @code{"a"} constraint tells the compiler that the @code{Flags}
29414 variable will come from the eax register. Here is the resulting code:
29422 movl %eax,-40(%ebp)
29427 The compiler generated the store of eax into Flags after
29428 expanding the assembler code.
29430 Actually, there was no need to pop the flags into the eax register;
29431 more simply, we could just pop the flags directly into the program variable:
29433 @smallexample @c ada
29435 with Interfaces; use Interfaces;
29436 with Ada.Text_IO; use Ada.Text_IO;
29437 with System.Machine_Code; use System.Machine_Code;
29438 procedure Get_Flags_3 is
29439 Flags : Unsigned_32;
29442 Asm ("pushfl" & LF & HT & -- push flags on stack
29443 "pop %0", -- save flags in Flags
29444 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29445 Put_Line ("Flags register:" & Flags'Img);
29450 @c ---------------------------------------------------------------------------
29451 @node Input Variables in Inline Assembler
29452 @section Input Variables in Inline Assembler
29455 The example in this section illustrates how to specify the source operands
29456 for assembly language statements.
29457 The program simply increments its input value by 1:
29459 @smallexample @c ada
29461 with Interfaces; use Interfaces;
29462 with Ada.Text_IO; use Ada.Text_IO;
29463 with System.Machine_Code; use System.Machine_Code;
29464 procedure Increment is
29466 function Incr (Value : Unsigned_32) return Unsigned_32 is
29467 Result : Unsigned_32;
29470 Inputs => Unsigned_32'Asm_Input ("a", Value),
29471 Outputs => Unsigned_32'Asm_Output ("=a", Result));
29475 Value : Unsigned_32;
29479 Put_Line ("Value before is" & Value'Img);
29480 Value := Incr (Value);
29481 Put_Line ("Value after is" & Value'Img);
29486 The @code{Outputs} parameter to @code{Asm} specifies
29487 that the result will be in the eax register and that it is to be stored
29488 in the @code{Result} variable.
29490 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29491 but with an @code{Asm_Input} attribute.
29492 The @code{"="} constraint, indicating an output value, is not present.
29494 You can have multiple input variables, in the same way that you can have more
29495 than one output variable.
29497 The parameter count (%0, %1) etc, now starts at the first input
29498 statement, and continues with the output statements.
29499 When both parameters use the same variable, the
29500 compiler will treat them as the same %n operand, which is the case here.
29502 Just as the @code{Outputs} parameter causes the register to be stored into the
29503 target variable after execution of the assembler statements, so does the
29504 @code{Inputs} parameter cause its variable to be loaded into the register
29505 before execution of the assembler statements.
29507 Thus the effect of the @code{Asm} invocation is:
29509 @item load the 32-bit value of @code{Value} into eax
29510 @item execute the @code{incl %eax} instruction
29511 @item store the contents of eax into the @code{Result} variable
29514 The resulting assembler file (with @option{-O2} optimization) contains:
29517 _increment__incr.1:
29530 @c ---------------------------------------------------------------------------
29531 @node Inlining Inline Assembler Code
29532 @section Inlining Inline Assembler Code
29535 For a short subprogram such as the @code{Incr} function in the previous
29536 section, the overhead of the call and return (creating / deleting the stack
29537 frame) can be significant, compared to the amount of code in the subprogram
29538 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29539 which directs the compiler to expand invocations of the subprogram at the
29540 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29541 Here is the resulting program:
29543 @smallexample @c ada
29545 with Interfaces; use Interfaces;
29546 with Ada.Text_IO; use Ada.Text_IO;
29547 with System.Machine_Code; use System.Machine_Code;
29548 procedure Increment_2 is
29550 function Incr (Value : Unsigned_32) return Unsigned_32 is
29551 Result : Unsigned_32;
29554 Inputs => Unsigned_32'Asm_Input ("a", Value),
29555 Outputs => Unsigned_32'Asm_Output ("=a", Result));
29558 pragma Inline (Increment);
29560 Value : Unsigned_32;
29564 Put_Line ("Value before is" & Value'Img);
29565 Value := Increment (Value);
29566 Put_Line ("Value after is" & Value'Img);
29571 Compile the program with both optimization (@option{-O2}) and inlining
29572 (@option{-gnatn}) enabled.
29574 The @code{Incr} function is still compiled as usual, but at the
29575 point in @code{Increment} where our function used to be called:
29580 call _increment__incr.1
29585 the code for the function body directly appears:
29598 thus saving the overhead of stack frame setup and an out-of-line call.
29600 @c ---------------------------------------------------------------------------
29601 @node Other Asm Functionality
29602 @section Other @code{Asm} Functionality
29605 This section describes two important parameters to the @code{Asm}
29606 procedure: @code{Clobber}, which identifies register usage;
29607 and @code{Volatile}, which inhibits unwanted optimizations.
29610 * The Clobber Parameter::
29611 * The Volatile Parameter::
29614 @c ---------------------------------------------------------------------------
29615 @node The Clobber Parameter
29616 @subsection The @code{Clobber} Parameter
29619 One of the dangers of intermixing assembly language and a compiled language
29620 such as Ada is that the compiler needs to be aware of which registers are
29621 being used by the assembly code. In some cases, such as the earlier examples,
29622 the constraint string is sufficient to indicate register usage (e.g.,
29624 the eax register). But more generally, the compiler needs an explicit
29625 identification of the registers that are used by the Inline Assembly
29628 Using a register that the compiler doesn't know about
29629 could be a side effect of an instruction (like @code{mull}
29630 storing its result in both eax and edx).
29631 It can also arise from explicit register usage in your
29632 assembly code; for example:
29635 Asm ("movl %0, %%ebx" & LF & HT &
29637 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29638 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
29642 where the compiler (since it does not analyze the @code{Asm} template string)
29643 does not know you are using the ebx register.
29645 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29646 to identify the registers that will be used by your assembly code:
29650 Asm ("movl %0, %%ebx" & LF & HT &
29652 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29653 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29658 The Clobber parameter is a static string expression specifying the
29659 register(s) you are using. Note that register names are @emph{not} prefixed
29660 by a percent sign. Also, if more than one register is used then their names
29661 are separated by commas; e.g., @code{"eax, ebx"}
29663 The @code{Clobber} parameter has several additional uses:
29665 @item Use ``register'' name @code{cc} to indicate that flags might have changed
29666 @item Use ``register'' name @code{memory} if you changed a memory location
29669 @c ---------------------------------------------------------------------------
29670 @node The Volatile Parameter
29671 @subsection The @code{Volatile} Parameter
29672 @cindex Volatile parameter
29675 Compiler optimizations in the presence of Inline Assembler may sometimes have
29676 unwanted effects. For example, when an @code{Asm} invocation with an input
29677 variable is inside a loop, the compiler might move the loading of the input
29678 variable outside the loop, regarding it as a one-time initialization.
29680 If this effect is not desired, you can disable such optimizations by setting
29681 the @code{Volatile} parameter to @code{True}; for example:
29683 @smallexample @c ada
29685 Asm ("movl %0, %%ebx" & LF & HT &
29687 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29688 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29694 By default, @code{Volatile} is set to @code{False} unless there is no
29695 @code{Outputs} parameter.
29697 Although setting @code{Volatile} to @code{True} prevents unwanted
29698 optimizations, it will also disable other optimizations that might be
29699 important for efficiency. In general, you should set @code{Volatile}
29700 to @code{True} only if the compiler's optimizations have created
29702 @c END OF INLINE ASSEMBLER CHAPTER
29703 @c ===============================
29705 @c ***********************************
29706 @c * Compatibility and Porting Guide *
29707 @c ***********************************
29708 @node Compatibility and Porting Guide
29709 @appendix Compatibility and Porting Guide
29712 This chapter describes the compatibility issues that may arise between
29713 GNAT and other Ada compilation systems (including those for Ada 83),
29714 and shows how GNAT can expedite porting
29715 applications developed in other Ada environments.
29718 * Compatibility with Ada 83::
29719 * Compatibility between Ada 95 and Ada 2005::
29720 * Implementation-dependent characteristics::
29721 * Compatibility with Other Ada Systems::
29722 * Representation Clauses::
29724 @c Brief section is only in non-VMS version
29725 @c Full chapter is in VMS version
29726 * Compatibility with HP Ada 83::
29729 * Transitioning to 64-Bit GNAT for OpenVMS::
29733 @node Compatibility with Ada 83
29734 @section Compatibility with Ada 83
29735 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
29738 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
29739 particular, the design intention was that the difficulties associated
29740 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
29741 that occur when moving from one Ada 83 system to another.
29743 However, there are a number of points at which there are minor
29744 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
29745 full details of these issues,
29746 and should be consulted for a complete treatment.
29748 following subsections treat the most likely issues to be encountered.
29751 * Legal Ada 83 programs that are illegal in Ada 95::
29752 * More deterministic semantics::
29753 * Changed semantics::
29754 * Other language compatibility issues::
29757 @node Legal Ada 83 programs that are illegal in Ada 95
29758 @subsection Legal Ada 83 programs that are illegal in Ada 95
29760 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
29761 Ada 95 and thus also in Ada 2005:
29764 @item Character literals
29765 Some uses of character literals are ambiguous. Since Ada 95 has introduced
29766 @code{Wide_Character} as a new predefined character type, some uses of
29767 character literals that were legal in Ada 83 are illegal in Ada 95.
29769 @smallexample @c ada
29770 for Char in 'A' .. 'Z' loop @dots{} end loop;
29774 The problem is that @code{'A'} and @code{'Z'} could be from either
29775 @code{Character} or @code{Wide_Character}. The simplest correction
29776 is to make the type explicit; e.g.:
29777 @smallexample @c ada
29778 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
29781 @item New reserved words
29782 The identifiers @code{abstract}, @code{aliased}, @code{protected},
29783 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
29784 Existing Ada 83 code using any of these identifiers must be edited to
29785 use some alternative name.
29787 @item Freezing rules
29788 The rules in Ada 95 are slightly different with regard to the point at
29789 which entities are frozen, and representation pragmas and clauses are
29790 not permitted past the freeze point. This shows up most typically in
29791 the form of an error message complaining that a representation item
29792 appears too late, and the appropriate corrective action is to move
29793 the item nearer to the declaration of the entity to which it refers.
29795 A particular case is that representation pragmas
29798 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
29800 cannot be applied to a subprogram body. If necessary, a separate subprogram
29801 declaration must be introduced to which the pragma can be applied.
29803 @item Optional bodies for library packages
29804 In Ada 83, a package that did not require a package body was nevertheless
29805 allowed to have one. This lead to certain surprises in compiling large
29806 systems (situations in which the body could be unexpectedly ignored by the
29807 binder). In Ada 95, if a package does not require a body then it is not
29808 permitted to have a body. To fix this problem, simply remove a redundant
29809 body if it is empty, or, if it is non-empty, introduce a dummy declaration
29810 into the spec that makes the body required. One approach is to add a private
29811 part to the package declaration (if necessary), and define a parameterless
29812 procedure called @code{Requires_Body}, which must then be given a dummy
29813 procedure body in the package body, which then becomes required.
29814 Another approach (assuming that this does not introduce elaboration
29815 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
29816 since one effect of this pragma is to require the presence of a package body.
29818 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
29819 In Ada 95, the exception @code{Numeric_Error} is a renaming of
29820 @code{Constraint_Error}.
29821 This means that it is illegal to have separate exception handlers for
29822 the two exceptions. The fix is simply to remove the handler for the
29823 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
29824 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
29826 @item Indefinite subtypes in generics
29827 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
29828 as the actual for a generic formal private type, but then the instantiation
29829 would be illegal if there were any instances of declarations of variables
29830 of this type in the generic body. In Ada 95, to avoid this clear violation
29831 of the methodological principle known as the ``contract model'',
29832 the generic declaration explicitly indicates whether
29833 or not such instantiations are permitted. If a generic formal parameter
29834 has explicit unknown discriminants, indicated by using @code{(<>)} after the
29835 type name, then it can be instantiated with indefinite types, but no
29836 stand-alone variables can be declared of this type. Any attempt to declare
29837 such a variable will result in an illegality at the time the generic is
29838 declared. If the @code{(<>)} notation is not used, then it is illegal
29839 to instantiate the generic with an indefinite type.
29840 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
29841 It will show up as a compile time error, and
29842 the fix is usually simply to add the @code{(<>)} to the generic declaration.
29845 @node More deterministic semantics
29846 @subsection More deterministic semantics
29850 Conversions from real types to integer types round away from 0. In Ada 83
29851 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
29852 implementation freedom was intended to support unbiased rounding in
29853 statistical applications, but in practice it interfered with portability.
29854 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
29855 is required. Numeric code may be affected by this change in semantics.
29856 Note, though, that this issue is no worse than already existed in Ada 83
29857 when porting code from one vendor to another.
29860 The Real-Time Annex introduces a set of policies that define the behavior of
29861 features that were implementation dependent in Ada 83, such as the order in
29862 which open select branches are executed.
29865 @node Changed semantics
29866 @subsection Changed semantics
29869 The worst kind of incompatibility is one where a program that is legal in
29870 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
29871 possible in Ada 83. Fortunately this is extremely rare, but the one
29872 situation that you should be alert to is the change in the predefined type
29873 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
29876 @item Range of type @code{Character}
29877 The range of @code{Standard.Character} is now the full 256 characters
29878 of Latin-1, whereas in most Ada 83 implementations it was restricted
29879 to 128 characters. Although some of the effects of
29880 this change will be manifest in compile-time rejection of legal
29881 Ada 83 programs it is possible for a working Ada 83 program to have
29882 a different effect in Ada 95, one that was not permitted in Ada 83.
29883 As an example, the expression
29884 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
29885 delivers @code{255} as its value.
29886 In general, you should look at the logic of any
29887 character-processing Ada 83 program and see whether it needs to be adapted
29888 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
29889 character handling package that may be relevant if code needs to be adapted
29890 to account for the additional Latin-1 elements.
29891 The desirable fix is to
29892 modify the program to accommodate the full character set, but in some cases
29893 it may be convenient to define a subtype or derived type of Character that
29894 covers only the restricted range.
29898 @node Other language compatibility issues
29899 @subsection Other language compatibility issues
29902 @item @option{-gnat83} switch
29903 All implementations of GNAT provide a switch that causes GNAT to operate
29904 in Ada 83 mode. In this mode, some but not all compatibility problems
29905 of the type described above are handled automatically. For example, the
29906 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
29907 as identifiers as in Ada 83.
29909 in practice, it is usually advisable to make the necessary modifications
29910 to the program to remove the need for using this switch.
29911 See @ref{Compiling Different Versions of Ada}.
29913 @item Support for removed Ada 83 pragmas and attributes
29914 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
29915 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
29916 compilers are allowed, but not required, to implement these missing
29917 elements. In contrast with some other compilers, GNAT implements all
29918 such pragmas and attributes, eliminating this compatibility concern. These
29919 include @code{pragma Interface} and the floating point type attributes
29920 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29924 @node Compatibility between Ada 95 and Ada 2005
29925 @section Compatibility between Ada 95 and Ada 2005
29926 @cindex Compatibility between Ada 95 and Ada 2005
29929 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29930 a number of incompatibilities. Several are enumerated below;
29931 for a complete description please see the
29932 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29933 @cite{Rationale for Ada 2005}.
29936 @item New reserved words.
29937 The words @code{interface}, @code{overriding} and @code{synchronized} are
29938 reserved in Ada 2005.
29939 A pre-Ada 2005 program that uses any of these as an identifier will be
29942 @item New declarations in predefined packages.
29943 A number of packages in the predefined environment contain new declarations:
29944 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29945 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29946 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29947 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29948 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29949 If an Ada 95 program does a @code{with} and @code{use} of any of these
29950 packages, the new declarations may cause name clashes.
29952 @item Access parameters.
29953 A nondispatching subprogram with an access parameter cannot be renamed
29954 as a dispatching operation. This was permitted in Ada 95.
29956 @item Access types, discriminants, and constraints.
29957 Rule changes in this area have led to some incompatibilities; for example,
29958 constrained subtypes of some access types are not permitted in Ada 2005.
29960 @item Aggregates for limited types.
29961 The allowance of aggregates for limited types in Ada 2005 raises the
29962 possibility of ambiguities in legal Ada 95 programs, since additional types
29963 now need to be considered in expression resolution.
29965 @item Fixed-point multiplication and division.
29966 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29967 were legal in Ada 95 and invoked the predefined versions of these operations,
29969 The ambiguity may be resolved either by applying a type conversion to the
29970 expression, or by explicitly invoking the operation from package
29973 @item Return-by-reference types.
29974 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
29975 can declare a function returning a value from an anonymous access type.
29979 @node Implementation-dependent characteristics
29980 @section Implementation-dependent characteristics
29982 Although the Ada language defines the semantics of each construct as
29983 precisely as practical, in some situations (for example for reasons of
29984 efficiency, or where the effect is heavily dependent on the host or target
29985 platform) the implementation is allowed some freedom. In porting Ada 83
29986 code to GNAT, you need to be aware of whether / how the existing code
29987 exercised such implementation dependencies. Such characteristics fall into
29988 several categories, and GNAT offers specific support in assisting the
29989 transition from certain Ada 83 compilers.
29992 * Implementation-defined pragmas::
29993 * Implementation-defined attributes::
29995 * Elaboration order::
29996 * Target-specific aspects::
29999 @node Implementation-defined pragmas
30000 @subsection Implementation-defined pragmas
30003 Ada compilers are allowed to supplement the language-defined pragmas, and
30004 these are a potential source of non-portability. All GNAT-defined pragmas
30005 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30006 Reference Manual}, and these include several that are specifically
30007 intended to correspond to other vendors' Ada 83 pragmas.
30008 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30009 For compatibility with HP Ada 83, GNAT supplies the pragmas
30010 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30011 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30012 and @code{Volatile}.
30013 Other relevant pragmas include @code{External} and @code{Link_With}.
30014 Some vendor-specific
30015 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30017 avoiding compiler rejection of units that contain such pragmas; they are not
30018 relevant in a GNAT context and hence are not otherwise implemented.
30020 @node Implementation-defined attributes
30021 @subsection Implementation-defined attributes
30023 Analogous to pragmas, the set of attributes may be extended by an
30024 implementation. All GNAT-defined attributes are described in
30025 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30026 Manual}, and these include several that are specifically intended
30027 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
30028 the attribute @code{VADS_Size} may be useful. For compatibility with HP
30029 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30033 @subsection Libraries
30035 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
30036 code uses vendor-specific libraries then there are several ways to manage
30037 this in Ada 95 or Ada 2005:
30040 If the source code for the libraries (specs and bodies) are
30041 available, then the libraries can be migrated in the same way as the
30044 If the source code for the specs but not the bodies are
30045 available, then you can reimplement the bodies.
30047 Some features introduced by Ada 95 obviate the need for library support. For
30048 example most Ada 83 vendors supplied a package for unsigned integers. The
30049 Ada 95 modular type feature is the preferred way to handle this need, so
30050 instead of migrating or reimplementing the unsigned integer package it may
30051 be preferable to retrofit the application using modular types.
30054 @node Elaboration order
30055 @subsection Elaboration order
30057 The implementation can choose any elaboration order consistent with the unit
30058 dependency relationship. This freedom means that some orders can result in
30059 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30060 to invoke a subprogram its body has been elaborated, or to instantiate a
30061 generic before the generic body has been elaborated. By default GNAT
30062 attempts to choose a safe order (one that will not encounter access before
30063 elaboration problems) by implicitly inserting @code{Elaborate} or
30064 @code{Elaborate_All} pragmas where
30065 needed. However, this can lead to the creation of elaboration circularities
30066 and a resulting rejection of the program by gnatbind. This issue is
30067 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30068 In brief, there are several
30069 ways to deal with this situation:
30073 Modify the program to eliminate the circularities, e.g.@: by moving
30074 elaboration-time code into explicitly-invoked procedures
30076 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30077 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30078 @code{Elaborate_All}
30079 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30080 (by selectively suppressing elaboration checks via pragma
30081 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30084 @node Target-specific aspects
30085 @subsection Target-specific aspects
30087 Low-level applications need to deal with machine addresses, data
30088 representations, interfacing with assembler code, and similar issues. If
30089 such an Ada 83 application is being ported to different target hardware (for
30090 example where the byte endianness has changed) then you will need to
30091 carefully examine the program logic; the porting effort will heavily depend
30092 on the robustness of the original design. Moreover, Ada 95 (and thus
30093 Ada 2005) are sometimes
30094 incompatible with typical Ada 83 compiler practices regarding implicit
30095 packing, the meaning of the Size attribute, and the size of access values.
30096 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30098 @node Compatibility with Other Ada Systems
30099 @section Compatibility with Other Ada Systems
30102 If programs avoid the use of implementation dependent and
30103 implementation defined features, as documented in the @cite{Ada
30104 Reference Manual}, there should be a high degree of portability between
30105 GNAT and other Ada systems. The following are specific items which
30106 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30107 compilers, but do not affect porting code to GNAT@.
30108 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30109 the following issues may or may not arise for Ada 2005 programs
30110 when other compilers appear.)
30113 @item Ada 83 Pragmas and Attributes
30114 Ada 95 compilers are allowed, but not required, to implement the missing
30115 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30116 GNAT implements all such pragmas and attributes, eliminating this as
30117 a compatibility concern, but some other Ada 95 compilers reject these
30118 pragmas and attributes.
30120 @item Specialized Needs Annexes
30121 GNAT implements the full set of special needs annexes. At the
30122 current time, it is the only Ada 95 compiler to do so. This means that
30123 programs making use of these features may not be portable to other Ada
30124 95 compilation systems.
30126 @item Representation Clauses
30127 Some other Ada 95 compilers implement only the minimal set of
30128 representation clauses required by the Ada 95 reference manual. GNAT goes
30129 far beyond this minimal set, as described in the next section.
30132 @node Representation Clauses
30133 @section Representation Clauses
30136 The Ada 83 reference manual was quite vague in describing both the minimal
30137 required implementation of representation clauses, and also their precise
30138 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
30139 minimal set of capabilities required is still quite limited.
30141 GNAT implements the full required set of capabilities in
30142 Ada 95 and Ada 2005, but also goes much further, and in particular
30143 an effort has been made to be compatible with existing Ada 83 usage to the
30144 greatest extent possible.
30146 A few cases exist in which Ada 83 compiler behavior is incompatible with
30147 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
30148 intentional or accidental dependence on specific implementation dependent
30149 characteristics of these Ada 83 compilers. The following is a list of
30150 the cases most likely to arise in existing Ada 83 code.
30153 @item Implicit Packing
30154 Some Ada 83 compilers allowed a Size specification to cause implicit
30155 packing of an array or record. This could cause expensive implicit
30156 conversions for change of representation in the presence of derived
30157 types, and the Ada design intends to avoid this possibility.
30158 Subsequent AI's were issued to make it clear that such implicit
30159 change of representation in response to a Size clause is inadvisable,
30160 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30161 Reference Manuals as implementation advice that is followed by GNAT@.
30162 The problem will show up as an error
30163 message rejecting the size clause. The fix is simply to provide
30164 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30165 a Component_Size clause.
30167 @item Meaning of Size Attribute
30168 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30169 the minimal number of bits required to hold values of the type. For example,
30170 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30171 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
30172 some 32 in this situation. This problem will usually show up as a compile
30173 time error, but not always. It is a good idea to check all uses of the
30174 'Size attribute when porting Ada 83 code. The GNAT specific attribute
30175 Object_Size can provide a useful way of duplicating the behavior of
30176 some Ada 83 compiler systems.
30178 @item Size of Access Types
30179 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30180 and that therefore it will be the same size as a System.Address value. This
30181 assumption is true for GNAT in most cases with one exception. For the case of
30182 a pointer to an unconstrained array type (where the bounds may vary from one
30183 value of the access type to another), the default is to use a ``fat pointer'',
30184 which is represented as two separate pointers, one to the bounds, and one to
30185 the array. This representation has a number of advantages, including improved
30186 efficiency. However, it may cause some difficulties in porting existing Ada 83
30187 code which makes the assumption that, for example, pointers fit in 32 bits on
30188 a machine with 32-bit addressing.
30190 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30191 access types in this case (where the designated type is an unconstrained array
30192 type). These thin pointers are indeed the same size as a System.Address value.
30193 To specify a thin pointer, use a size clause for the type, for example:
30195 @smallexample @c ada
30196 type X is access all String;
30197 for X'Size use Standard'Address_Size;
30201 which will cause the type X to be represented using a single pointer.
30202 When using this representation, the bounds are right behind the array.
30203 This representation is slightly less efficient, and does not allow quite
30204 such flexibility in the use of foreign pointers or in using the
30205 Unrestricted_Access attribute to create pointers to non-aliased objects.
30206 But for any standard portable use of the access type it will work in
30207 a functionally correct manner and allow porting of existing code.
30208 Note that another way of forcing a thin pointer representation
30209 is to use a component size clause for the element size in an array,
30210 or a record representation clause for an access field in a record.
30214 @c This brief section is only in the non-VMS version
30215 @c The complete chapter on HP Ada is in the VMS version
30216 @node Compatibility with HP Ada 83
30217 @section Compatibility with HP Ada 83
30220 The VMS version of GNAT fully implements all the pragmas and attributes
30221 provided by HP Ada 83, as well as providing the standard HP Ada 83
30222 libraries, including Starlet. In addition, data layouts and parameter
30223 passing conventions are highly compatible. This means that porting
30224 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30225 most other porting efforts. The following are some of the most
30226 significant differences between GNAT and HP Ada 83.
30229 @item Default floating-point representation
30230 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30231 it is VMS format. GNAT does implement the necessary pragmas
30232 (Long_Float, Float_Representation) for changing this default.
30235 The package System in GNAT exactly corresponds to the definition in the
30236 Ada 95 reference manual, which means that it excludes many of the
30237 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
30238 that contains the additional definitions, and a special pragma,
30239 Extend_System allows this package to be treated transparently as an
30240 extension of package System.
30243 The definitions provided by Aux_DEC are exactly compatible with those
30244 in the HP Ada 83 version of System, with one exception.
30245 HP Ada provides the following declarations:
30247 @smallexample @c ada
30248 TO_ADDRESS (INTEGER)
30249 TO_ADDRESS (UNSIGNED_LONGWORD)
30250 TO_ADDRESS (@i{universal_integer})
30254 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30255 an extension to Ada 83 not strictly compatible with the reference manual.
30256 In GNAT, we are constrained to be exactly compatible with the standard,
30257 and this means we cannot provide this capability. In HP Ada 83, the
30258 point of this definition is to deal with a call like:
30260 @smallexample @c ada
30261 TO_ADDRESS (16#12777#);
30265 Normally, according to the Ada 83 standard, one would expect this to be
30266 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30267 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
30268 definition using @i{universal_integer} takes precedence.
30270 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30271 is not possible to be 100% compatible. Since there are many programs using
30272 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30273 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30274 declarations provided in the GNAT version of AUX_Dec are:
30276 @smallexample @c ada
30277 function To_Address (X : Integer) return Address;
30278 pragma Pure_Function (To_Address);
30280 function To_Address_Long (X : Unsigned_Longword)
30282 pragma Pure_Function (To_Address_Long);
30286 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30287 change the name to TO_ADDRESS_LONG@.
30289 @item Task_Id values
30290 The Task_Id values assigned will be different in the two systems, and GNAT
30291 does not provide a specified value for the Task_Id of the environment task,
30292 which in GNAT is treated like any other declared task.
30296 For full details on these and other less significant compatibility issues,
30297 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30298 Overview and Comparison on HP Platforms}.
30300 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30301 attributes are recognized, although only a subset of them can sensibly
30302 be implemented. The description of pragmas in @ref{Implementation
30303 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30304 indicates whether or not they are applicable to non-VMS systems.
30308 @node Transitioning to 64-Bit GNAT for OpenVMS
30309 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30312 This section is meant to assist users of pre-2006 @value{EDITION}
30313 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30314 the version of the GNAT technology supplied in 2006 and later for
30315 OpenVMS on both Alpha and I64.
30318 * Introduction to transitioning::
30319 * Migration of 32 bit code::
30320 * Taking advantage of 64 bit addressing::
30321 * Technical details::
30324 @node Introduction to transitioning
30325 @subsection Introduction
30328 64-bit @value{EDITION} for Open VMS has been designed to meet
30333 Providing a full conforming implementation of Ada 95 and Ada 2005
30336 Allowing maximum backward compatibility, thus easing migration of existing
30340 Supplying a path for exploiting the full 64-bit address range
30344 Ada's strong typing semantics has made it
30345 impractical to have different 32-bit and 64-bit modes. As soon as
30346 one object could possibly be outside the 32-bit address space, this
30347 would make it necessary for the @code{System.Address} type to be 64 bits.
30348 In particular, this would cause inconsistencies if 32-bit code is
30349 called from 64-bit code that raises an exception.
30351 This issue has been resolved by always using 64-bit addressing
30352 at the system level, but allowing for automatic conversions between
30353 32-bit and 64-bit addresses where required. Thus users who
30354 do not currently require 64-bit addressing capabilities, can
30355 recompile their code with only minimal changes (and indeed
30356 if the code is written in portable Ada, with no assumptions about
30357 the size of the @code{Address} type, then no changes at all are necessary).
30359 this approach provides a simple, gradual upgrade path to future
30360 use of larger memories than available for 32-bit systems.
30361 Also, newly written applications or libraries will by default
30362 be fully compatible with future systems exploiting 64-bit
30363 addressing capabilities.
30365 @ref{Migration of 32 bit code}, will focus on porting applications
30366 that do not require more than 2 GB of
30367 addressable memory. This code will be referred to as
30368 @emph{32-bit code}.
30369 For applications intending to exploit the full 64-bit address space,
30370 @ref{Taking advantage of 64 bit addressing},
30371 will consider further changes that may be required.
30372 Such code will be referred to below as @emph{64-bit code}.
30374 @node Migration of 32 bit code
30375 @subsection Migration of 32-bit code
30380 * Unchecked conversions::
30381 * Predefined constants::
30382 * Interfacing with C::
30383 * Experience with source compatibility::
30386 @node Address types
30387 @subsubsection Address types
30390 To solve the problem of mixing 64-bit and 32-bit addressing,
30391 while maintaining maximum backward compatibility, the following
30392 approach has been taken:
30396 @code{System.Address} always has a size of 64 bits
30399 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30403 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30404 a @code{Short_Address}
30405 may be used where an @code{Address} is required, and vice versa, without
30406 needing explicit type conversions.
30407 By virtue of the Open VMS parameter passing conventions,
30409 and exported subprograms that have 32-bit address parameters are
30410 compatible with those that have 64-bit address parameters.
30411 (See @ref{Making code 64 bit clean} for details.)
30413 The areas that may need attention are those where record types have
30414 been defined that contain components of the type @code{System.Address}, and
30415 where objects of this type are passed to code expecting a record layout with
30418 Different compilers on different platforms cannot be
30419 expected to represent the same type in the same way,
30420 since alignment constraints
30421 and other system-dependent properties affect the compiler's decision.
30422 For that reason, Ada code
30423 generally uses representation clauses to specify the expected
30424 layout where required.
30426 If such a representation clause uses 32 bits for a component having
30427 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30428 will detect that error and produce a specific diagnostic message.
30429 The developer should then determine whether the representation
30430 should be 64 bits or not and make either of two changes:
30431 change the size to 64 bits and leave the type as @code{System.Address}, or
30432 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30433 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30434 required in any code setting or accessing the field; the compiler will
30435 automatically perform any needed conversions between address
30439 @subsubsection Access types
30442 By default, objects designated by access values are always
30443 allocated in the 32-bit
30444 address space. Thus legacy code will never contain
30445 any objects that are not addressable with 32-bit addresses, and
30446 the compiler will never raise exceptions as result of mixing
30447 32-bit and 64-bit addresses.
30449 However, the access values themselves are represented in 64 bits, for optimum
30450 performance and future compatibility with 64-bit code. As was
30451 the case with @code{System.Address}, the compiler will give an error message
30452 if an object or record component has a representation clause that
30453 requires the access value to fit in 32 bits. In such a situation,
30454 an explicit size clause for the access type, specifying 32 bits,
30455 will have the desired effect.
30457 General access types (declared with @code{access all}) can never be
30458 32 bits, as values of such types must be able to refer to any object
30459 of the designated type,
30460 including objects residing outside the 32-bit address range.
30461 Existing Ada 83 code will not contain such type definitions,
30462 however, since general access types were introduced in Ada 95.
30464 @node Unchecked conversions
30465 @subsubsection Unchecked conversions
30468 In the case of an @code{Unchecked_Conversion} where the source type is a
30469 64-bit access type or the type @code{System.Address}, and the target
30470 type is a 32-bit type, the compiler will generate a warning.
30471 Even though the generated code will still perform the required
30472 conversions, it is highly recommended in these cases to use
30473 respectively a 32-bit access type or @code{System.Short_Address}
30474 as the source type.
30476 @node Predefined constants
30477 @subsubsection Predefined constants
30480 The following table shows the correspondence between pre-2006 versions of
30481 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
30484 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
30485 @item @b{Constant} @tab @b{Old} @tab @b{New}
30486 @item @code{System.Word_Size} @tab 32 @tab 64
30487 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
30488 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
30489 @item @code{System.Address_Size} @tab 32 @tab 64
30493 If you need to refer to the specific
30494 memory size of a 32-bit implementation, instead of the
30495 actual memory size, use @code{System.Short_Memory_Size}
30496 rather than @code{System.Memory_Size}.
30497 Similarly, references to @code{System.Address_Size} may need
30498 to be replaced by @code{System.Short_Address'Size}.
30499 The program @command{gnatfind} may be useful for locating
30500 references to the above constants, so that you can verify that they
30503 @node Interfacing with C
30504 @subsubsection Interfacing with C
30507 In order to minimize the impact of the transition to 64-bit addresses on
30508 legacy programs, some fundamental types in the @code{Interfaces.C}
30509 package hierarchy continue to be represented in 32 bits.
30510 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
30511 This eases integration with the default HP C layout choices, for example
30512 as found in the system routines in @code{DECC$SHR.EXE}.
30513 Because of this implementation choice, the type fully compatible with
30514 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
30515 Depending on the context the compiler will issue a
30516 warning or an error when type @code{Address} is used, alerting the user to a
30517 potential problem. Otherwise 32-bit programs that use
30518 @code{Interfaces.C} should normally not require code modifications
30520 The other issue arising with C interfacing concerns pragma @code{Convention}.
30521 For VMS 64-bit systems, there is an issue of the appropriate default size
30522 of C convention pointers in the absence of an explicit size clause. The HP
30523 C compiler can choose either 32 or 64 bits depending on compiler options.
30524 GNAT chooses 32-bits rather than 64-bits in the default case where no size
30525 clause is given. This proves a better choice for porting 32-bit legacy
30526 applications. In order to have a 64-bit representation, it is necessary to
30527 specify a size representation clause. For example:
30529 @smallexample @c ada
30530 type int_star is access Interfaces.C.int;
30531 pragma Convention(C, int_star);
30532 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
30535 @node Experience with source compatibility
30536 @subsubsection Experience with source compatibility
30539 The Security Server and STARLET on I64 provide an interesting ``test case''
30540 for source compatibility issues, since it is in such system code
30541 where assumptions about @code{Address} size might be expected to occur.
30542 Indeed, there were a small number of occasions in the Security Server
30543 file @file{jibdef.ads}
30544 where a representation clause for a record type specified
30545 32 bits for a component of type @code{Address}.
30546 All of these errors were detected by the compiler.
30547 The repair was obvious and immediate; to simply replace @code{Address} by
30548 @code{Short_Address}.
30550 In the case of STARLET, there were several record types that should
30551 have had representation clauses but did not. In these record types
30552 there was an implicit assumption that an @code{Address} value occupied
30554 These compiled without error, but their usage resulted in run-time error
30555 returns from STARLET system calls.
30556 Future GNAT technology enhancements may include a tool that detects and flags
30557 these sorts of potential source code porting problems.
30559 @c ****************************************
30560 @node Taking advantage of 64 bit addressing
30561 @subsection Taking advantage of 64-bit addressing
30564 * Making code 64 bit clean::
30565 * Allocating memory from the 64 bit storage pool::
30566 * Restrictions on use of 64 bit objects::
30567 * Using 64 bit storage pools by default::
30568 * General access types::
30569 * STARLET and other predefined libraries::
30572 @node Making code 64 bit clean
30573 @subsubsection Making code 64-bit clean
30576 In order to prevent problems that may occur when (parts of) a
30577 system start using memory outside the 32-bit address range,
30578 we recommend some additional guidelines:
30582 For imported subprograms that take parameters of the
30583 type @code{System.Address}, ensure that these subprograms can
30584 indeed handle 64-bit addresses. If not, or when in doubt,
30585 change the subprogram declaration to specify
30586 @code{System.Short_Address} instead.
30589 Resolve all warnings related to size mismatches in
30590 unchecked conversions. Failing to do so causes
30591 erroneous execution if the source object is outside
30592 the 32-bit address space.
30595 (optional) Explicitly use the 32-bit storage pool
30596 for access types used in a 32-bit context, or use
30597 generic access types where possible
30598 (@pxref{Restrictions on use of 64 bit objects}).
30602 If these rules are followed, the compiler will automatically insert
30603 any necessary checks to ensure that no addresses or access values
30604 passed to 32-bit code ever refer to objects outside the 32-bit
30606 Any attempt to do this will raise @code{Constraint_Error}.
30608 @node Allocating memory from the 64 bit storage pool
30609 @subsubsection Allocating memory from the 64-bit storage pool
30612 For any access type @code{T} that potentially requires memory allocations
30613 beyond the 32-bit address space,
30614 use the following representation clause:
30616 @smallexample @c ada
30617 for T'Storage_Pool use System.Pool_64;
30620 @node Restrictions on use of 64 bit objects
30621 @subsubsection Restrictions on use of 64-bit objects
30624 Taking the address of an object allocated from a 64-bit storage pool,
30625 and then passing this address to a subprogram expecting
30626 @code{System.Short_Address},
30627 or assigning it to a variable of type @code{Short_Address}, will cause
30628 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
30629 (@pxref{Making code 64 bit clean}), or checks are suppressed,
30630 no exception is raised and execution
30631 will become erroneous.
30633 @node Using 64 bit storage pools by default
30634 @subsubsection Using 64-bit storage pools by default
30637 In some cases it may be desirable to have the compiler allocate
30638 from 64-bit storage pools by default. This may be the case for
30639 libraries that are 64-bit clean, but may be used in both 32-bit
30640 and 64-bit contexts. For these cases the following configuration
30641 pragma may be specified:
30643 @smallexample @c ada
30644 pragma Pool_64_Default;
30648 Any code compiled in the context of this pragma will by default
30649 use the @code{System.Pool_64} storage pool. This default may be overridden
30650 for a specific access type @code{T} by the representation clause:
30652 @smallexample @c ada
30653 for T'Storage_Pool use System.Pool_32;
30657 Any object whose address may be passed to a subprogram with a
30658 @code{Short_Address} argument, or assigned to a variable of type
30659 @code{Short_Address}, needs to be allocated from this pool.
30661 @node General access types
30662 @subsubsection General access types
30665 Objects designated by access values from a
30666 general access type (declared with @code{access all}) are never allocated
30667 from a 64-bit storage pool. Code that uses general access types will
30668 accept objects allocated in either 32-bit or 64-bit address spaces,
30669 but never allocate objects outside the 32-bit address space.
30670 Using general access types ensures maximum compatibility with both
30671 32-bit and 64-bit code.
30673 @node STARLET and other predefined libraries
30674 @subsubsection STARLET and other predefined libraries
30677 All code that comes as part of GNAT is 64-bit clean, but the
30678 restrictions given in @ref{Restrictions on use of 64 bit objects},
30679 still apply. Look at the package
30680 specs to see in which contexts objects allocated
30681 in 64-bit address space are acceptable.
30683 @node Technical details
30684 @subsection Technical details
30687 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
30688 Ada standard with respect to the type of @code{System.Address}. Previous
30689 versions of GNAT Pro have defined this type as private and implemented it as a
30692 In order to allow defining @code{System.Short_Address} as a proper subtype,
30693 and to match the implicit sign extension in parameter passing,
30694 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
30695 visible (i.e., non-private) integer type.
30696 Standard operations on the type, such as the binary operators ``+'', ``-'',
30697 etc., that take @code{Address} operands and return an @code{Address} result,
30698 have been hidden by declaring these
30699 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
30700 ambiguities that would otherwise result from overloading.
30701 (Note that, although @code{Address} is a visible integer type,
30702 good programming practice dictates against exploiting the type's
30703 integer properties such as literals, since this will compromise
30706 Defining @code{Address} as a visible integer type helps achieve
30707 maximum compatibility for existing Ada code,
30708 without sacrificing the capabilities of the 64-bit architecture.
30711 @c ************************************************
30713 @node Microsoft Windows Topics
30714 @appendix Microsoft Windows Topics
30720 This chapter describes topics that are specific to the Microsoft Windows
30721 platforms (NT, 2000, and XP Professional).
30724 * Using GNAT on Windows::
30725 * Using a network installation of GNAT::
30726 * CONSOLE and WINDOWS subsystems::
30727 * Temporary Files::
30728 * Mixed-Language Programming on Windows::
30729 * Windows Calling Conventions::
30730 * Introduction to Dynamic Link Libraries (DLLs)::
30731 * Using DLLs with GNAT::
30732 * Building DLLs with GNAT::
30733 * Building DLLs with GNAT Project files::
30734 * Building DLLs with gnatdll::
30735 * GNAT and Windows Resources::
30736 * Debugging a DLL::
30737 * Setting Stack Size from gnatlink::
30738 * Setting Heap Size from gnatlink::
30741 @node Using GNAT on Windows
30742 @section Using GNAT on Windows
30745 One of the strengths of the GNAT technology is that its tool set
30746 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
30747 @code{gdb} debugger, etc.) is used in the same way regardless of the
30750 On Windows this tool set is complemented by a number of Microsoft-specific
30751 tools that have been provided to facilitate interoperability with Windows
30752 when this is required. With these tools:
30757 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
30761 You can use any Dynamically Linked Library (DLL) in your Ada code (both
30762 relocatable and non-relocatable DLLs are supported).
30765 You can build Ada DLLs for use in other applications. These applications
30766 can be written in a language other than Ada (e.g., C, C++, etc). Again both
30767 relocatable and non-relocatable Ada DLLs are supported.
30770 You can include Windows resources in your Ada application.
30773 You can use or create COM/DCOM objects.
30777 Immediately below are listed all known general GNAT-for-Windows restrictions.
30778 Other restrictions about specific features like Windows Resources and DLLs
30779 are listed in separate sections below.
30784 It is not possible to use @code{GetLastError} and @code{SetLastError}
30785 when tasking, protected records, or exceptions are used. In these
30786 cases, in order to implement Ada semantics, the GNAT run-time system
30787 calls certain Win32 routines that set the last error variable to 0 upon
30788 success. It should be possible to use @code{GetLastError} and
30789 @code{SetLastError} when tasking, protected record, and exception
30790 features are not used, but it is not guaranteed to work.
30793 It is not possible to link against Microsoft libraries except for
30794 import libraries. The library must be built to be compatible with
30795 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
30796 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
30797 not be compatible with the GNAT runtime. Even if the library is
30798 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
30801 When the compilation environment is located on FAT32 drives, users may
30802 experience recompilations of the source files that have not changed if
30803 Daylight Saving Time (DST) state has changed since the last time files
30804 were compiled. NTFS drives do not have this problem.
30807 No components of the GNAT toolset use any entries in the Windows
30808 registry. The only entries that can be created are file associations and
30809 PATH settings, provided the user has chosen to create them at installation
30810 time, as well as some minimal book-keeping information needed to correctly
30811 uninstall or integrate different GNAT products.
30814 @node Using a network installation of GNAT
30815 @section Using a network installation of GNAT
30818 Make sure the system on which GNAT is installed is accessible from the
30819 current machine, i.e., the install location is shared over the network.
30820 Shared resources are accessed on Windows by means of UNC paths, which
30821 have the format @code{\\server\sharename\path}
30823 In order to use such a network installation, simply add the UNC path of the
30824 @file{bin} directory of your GNAT installation in front of your PATH. For
30825 example, if GNAT is installed in @file{\GNAT} directory of a share location
30826 called @file{c-drive} on a machine @file{LOKI}, the following command will
30829 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
30831 Be aware that every compilation using the network installation results in the
30832 transfer of large amounts of data across the network and will likely cause
30833 serious performance penalty.
30835 @node CONSOLE and WINDOWS subsystems
30836 @section CONSOLE and WINDOWS subsystems
30837 @cindex CONSOLE Subsystem
30838 @cindex WINDOWS Subsystem
30842 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
30843 (which is the default subsystem) will always create a console when
30844 launching the application. This is not something desirable when the
30845 application has a Windows GUI. To get rid of this console the
30846 application must be using the @code{WINDOWS} subsystem. To do so
30847 the @option{-mwindows} linker option must be specified.
30850 $ gnatmake winprog -largs -mwindows
30853 @node Temporary Files
30854 @section Temporary Files
30855 @cindex Temporary files
30858 It is possible to control where temporary files gets created by setting
30859 the @env{TMP} environment variable. The file will be created:
30862 @item Under the directory pointed to by the @env{TMP} environment variable if
30863 this directory exists.
30865 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
30866 set (or not pointing to a directory) and if this directory exists.
30868 @item Under the current working directory otherwise.
30872 This allows you to determine exactly where the temporary
30873 file will be created. This is particularly useful in networked
30874 environments where you may not have write access to some
30877 @node Mixed-Language Programming on Windows
30878 @section Mixed-Language Programming on Windows
30881 Developing pure Ada applications on Windows is no different than on
30882 other GNAT-supported platforms. However, when developing or porting an
30883 application that contains a mix of Ada and C/C++, the choice of your
30884 Windows C/C++ development environment conditions your overall
30885 interoperability strategy.
30887 If you use @command{gcc} to compile the non-Ada part of your application,
30888 there are no Windows-specific restrictions that affect the overall
30889 interoperability with your Ada code. If you plan to use
30890 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
30891 the following limitations:
30895 You cannot link your Ada code with an object or library generated with
30896 Microsoft tools if these use the @code{.tls} section (Thread Local
30897 Storage section) since the GNAT linker does not yet support this section.
30900 You cannot link your Ada code with an object or library generated with
30901 Microsoft tools if these use I/O routines other than those provided in
30902 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
30903 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
30904 libraries can cause a conflict with @code{msvcrt.dll} services. For
30905 instance Visual C++ I/O stream routines conflict with those in
30910 If you do want to use the Microsoft tools for your non-Ada code and hit one
30911 of the above limitations, you have two choices:
30915 Encapsulate your non-Ada code in a DLL to be linked with your Ada
30916 application. In this case, use the Microsoft or whatever environment to
30917 build the DLL and use GNAT to build your executable
30918 (@pxref{Using DLLs with GNAT}).
30921 Or you can encapsulate your Ada code in a DLL to be linked with the
30922 other part of your application. In this case, use GNAT to build the DLL
30923 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
30924 environment to build your executable.
30927 @node Windows Calling Conventions
30928 @section Windows Calling Conventions
30933 * C Calling Convention::
30934 * Stdcall Calling Convention::
30935 * Win32 Calling Convention::
30936 * DLL Calling Convention::
30940 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30941 (callee), there are several ways to push @code{G}'s parameters on the
30942 stack and there are several possible scenarios to clean up the stack
30943 upon @code{G}'s return. A calling convention is an agreed upon software
30944 protocol whereby the responsibilities between the caller (@code{F}) and
30945 the callee (@code{G}) are clearly defined. Several calling conventions
30946 are available for Windows:
30950 @code{C} (Microsoft defined)
30953 @code{Stdcall} (Microsoft defined)
30956 @code{Win32} (GNAT specific)
30959 @code{DLL} (GNAT specific)
30962 @node C Calling Convention
30963 @subsection @code{C} Calling Convention
30966 This is the default calling convention used when interfacing to C/C++
30967 routines compiled with either @command{gcc} or Microsoft Visual C++.
30969 In the @code{C} calling convention subprogram parameters are pushed on the
30970 stack by the caller from right to left. The caller itself is in charge of
30971 cleaning up the stack after the call. In addition, the name of a routine
30972 with @code{C} calling convention is mangled by adding a leading underscore.
30974 The name to use on the Ada side when importing (or exporting) a routine
30975 with @code{C} calling convention is the name of the routine. For
30976 instance the C function:
30979 int get_val (long);
30983 should be imported from Ada as follows:
30985 @smallexample @c ada
30987 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30988 pragma Import (C, Get_Val, External_Name => "get_val");
30993 Note that in this particular case the @code{External_Name} parameter could
30994 have been omitted since, when missing, this parameter is taken to be the
30995 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30996 is missing, as in the above example, this parameter is set to be the
30997 @code{External_Name} with a leading underscore.
30999 When importing a variable defined in C, you should always use the @code{C}
31000 calling convention unless the object containing the variable is part of a
31001 DLL (in which case you should use the @code{Stdcall} calling
31002 convention, @pxref{Stdcall Calling Convention}).
31004 @node Stdcall Calling Convention
31005 @subsection @code{Stdcall} Calling Convention
31008 This convention, which was the calling convention used for Pascal
31009 programs, is used by Microsoft for all the routines in the Win32 API for
31010 efficiency reasons. It must be used to import any routine for which this
31011 convention was specified.
31013 In the @code{Stdcall} calling convention subprogram parameters are pushed
31014 on the stack by the caller from right to left. The callee (and not the
31015 caller) is in charge of cleaning the stack on routine exit. In addition,
31016 the name of a routine with @code{Stdcall} calling convention is mangled by
31017 adding a leading underscore (as for the @code{C} calling convention) and a
31018 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31019 bytes) of the parameters passed to the routine.
31021 The name to use on the Ada side when importing a C routine with a
31022 @code{Stdcall} calling convention is the name of the C routine. The leading
31023 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31024 the compiler. For instance the Win32 function:
31027 @b{APIENTRY} int get_val (long);
31031 should be imported from Ada as follows:
31033 @smallexample @c ada
31035 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31036 pragma Import (Stdcall, Get_Val);
31037 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31042 As for the @code{C} calling convention, when the @code{External_Name}
31043 parameter is missing, it is taken to be the name of the Ada entity in lower
31044 case. If instead of writing the above import pragma you write:
31046 @smallexample @c ada
31048 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31049 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31054 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31055 of specifying the @code{External_Name} parameter you specify the
31056 @code{Link_Name} as in the following example:
31058 @smallexample @c ada
31060 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31061 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31066 then the imported routine is @code{retrieve_val}, that is, there is no
31067 decoration at all. No leading underscore and no Stdcall suffix
31068 @code{@@}@code{@var{nn}}.
31071 This is especially important as in some special cases a DLL's entry
31072 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31073 name generated for a call has it.
31076 It is also possible to import variables defined in a DLL by using an
31077 import pragma for a variable. As an example, if a DLL contains a
31078 variable defined as:
31085 then, to access this variable from Ada you should write:
31087 @smallexample @c ada
31089 My_Var : Interfaces.C.int;
31090 pragma Import (Stdcall, My_Var);
31095 Note that to ease building cross-platform bindings this convention
31096 will be handled as a @code{C} calling convention on non-Windows platforms.
31098 @node Win32 Calling Convention
31099 @subsection @code{Win32} Calling Convention
31102 This convention, which is GNAT-specific is fully equivalent to the
31103 @code{Stdcall} calling convention described above.
31105 @node DLL Calling Convention
31106 @subsection @code{DLL} Calling Convention
31109 This convention, which is GNAT-specific is fully equivalent to the
31110 @code{Stdcall} calling convention described above.
31112 @node Introduction to Dynamic Link Libraries (DLLs)
31113 @section Introduction to Dynamic Link Libraries (DLLs)
31117 A Dynamically Linked Library (DLL) is a library that can be shared by
31118 several applications running under Windows. A DLL can contain any number of
31119 routines and variables.
31121 One advantage of DLLs is that you can change and enhance them without
31122 forcing all the applications that depend on them to be relinked or
31123 recompiled. However, you should be aware than all calls to DLL routines are
31124 slower since, as you will understand below, such calls are indirect.
31126 To illustrate the remainder of this section, suppose that an application
31127 wants to use the services of a DLL @file{API.dll}. To use the services
31128 provided by @file{API.dll} you must statically link against the DLL or
31129 an import library which contains a jump table with an entry for each
31130 routine and variable exported by the DLL. In the Microsoft world this
31131 import library is called @file{API.lib}. When using GNAT this import
31132 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31133 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31135 After you have linked your application with the DLL or the import library
31136 and you run your application, here is what happens:
31140 Your application is loaded into memory.
31143 The DLL @file{API.dll} is mapped into the address space of your
31144 application. This means that:
31148 The DLL will use the stack of the calling thread.
31151 The DLL will use the virtual address space of the calling process.
31154 The DLL will allocate memory from the virtual address space of the calling
31158 Handles (pointers) can be safely exchanged between routines in the DLL
31159 routines and routines in the application using the DLL.
31163 The entries in the jump table (from the import library @file{libAPI.dll.a}
31164 or @file{API.lib} or automatically created when linking against a DLL)
31165 which is part of your application are initialized with the addresses
31166 of the routines and variables in @file{API.dll}.
31169 If present in @file{API.dll}, routines @code{DllMain} or
31170 @code{DllMainCRTStartup} are invoked. These routines typically contain
31171 the initialization code needed for the well-being of the routines and
31172 variables exported by the DLL.
31176 There is an additional point which is worth mentioning. In the Windows
31177 world there are two kind of DLLs: relocatable and non-relocatable
31178 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31179 in the target application address space. If the addresses of two
31180 non-relocatable DLLs overlap and these happen to be used by the same
31181 application, a conflict will occur and the application will run
31182 incorrectly. Hence, when possible, it is always preferable to use and
31183 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31184 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31185 User's Guide) removes the debugging symbols from the DLL but the DLL can
31186 still be relocated.
31188 As a side note, an interesting difference between Microsoft DLLs and
31189 Unix shared libraries, is the fact that on most Unix systems all public
31190 routines are exported by default in a Unix shared library, while under
31191 Windows it is possible (but not required) to list exported routines in
31192 a definition file (@pxref{The Definition File}).
31194 @node Using DLLs with GNAT
31195 @section Using DLLs with GNAT
31198 * Creating an Ada Spec for the DLL Services::
31199 * Creating an Import Library::
31203 To use the services of a DLL, say @file{API.dll}, in your Ada application
31208 The Ada spec for the routines and/or variables you want to access in
31209 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31210 header files provided with the DLL.
31213 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31214 mentioned an import library is a statically linked library containing the
31215 import table which will be filled at load time to point to the actual
31216 @file{API.dll} routines. Sometimes you don't have an import library for the
31217 DLL you want to use. The following sections will explain how to build
31218 one. Note that this is optional.
31221 The actual DLL, @file{API.dll}.
31225 Once you have all the above, to compile an Ada application that uses the
31226 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31227 you simply issue the command
31230 $ gnatmake my_ada_app -largs -lAPI
31234 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31235 tells the GNAT linker to look first for a library named @file{API.lib}
31236 (Microsoft-style name) and if not found for a libraries named
31237 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31238 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31239 contains the following pragma
31241 @smallexample @c ada
31242 pragma Linker_Options ("-lAPI");
31246 you do not have to add @option{-largs -lAPI} at the end of the
31247 @command{gnatmake} command.
31249 If any one of the items above is missing you will have to create it
31250 yourself. The following sections explain how to do so using as an
31251 example a fictitious DLL called @file{API.dll}.
31253 @node Creating an Ada Spec for the DLL Services
31254 @subsection Creating an Ada Spec for the DLL Services
31257 A DLL typically comes with a C/C++ header file which provides the
31258 definitions of the routines and variables exported by the DLL. The Ada
31259 equivalent of this header file is a package spec that contains definitions
31260 for the imported entities. If the DLL you intend to use does not come with
31261 an Ada spec you have to generate one such spec yourself. For example if
31262 the header file of @file{API.dll} is a file @file{api.h} containing the
31263 following two definitions:
31275 then the equivalent Ada spec could be:
31277 @smallexample @c ada
31280 with Interfaces.C.Strings;
31285 function Get (Str : C.Strings.Chars_Ptr) return C.int;
31288 pragma Import (C, Get);
31289 pragma Import (DLL, Some_Var);
31296 Note that a variable is
31297 @strong{always imported with a Stdcall convention}. A function
31298 can have @code{C} or @code{Stdcall} convention.
31299 (@pxref{Windows Calling Conventions}).
31301 @node Creating an Import Library
31302 @subsection Creating an Import Library
31303 @cindex Import library
31306 * The Definition File::
31307 * GNAT-Style Import Library::
31308 * Microsoft-Style Import Library::
31312 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31313 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31314 with @file{API.dll} you can skip this section. You can also skip this
31315 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31316 as in this case it is possible to link directly against the
31317 DLL. Otherwise read on.
31319 @node The Definition File
31320 @subsubsection The Definition File
31321 @cindex Definition file
31325 As previously mentioned, and unlike Unix systems, the list of symbols
31326 that are exported from a DLL must be provided explicitly in Windows.
31327 The main goal of a definition file is precisely that: list the symbols
31328 exported by a DLL. A definition file (usually a file with a @code{.def}
31329 suffix) has the following structure:
31334 @r{[}LIBRARY @var{name}@r{]}
31335 @r{[}DESCRIPTION @var{string}@r{]}
31345 @item LIBRARY @var{name}
31346 This section, which is optional, gives the name of the DLL.
31348 @item DESCRIPTION @var{string}
31349 This section, which is optional, gives a description string that will be
31350 embedded in the import library.
31353 This section gives the list of exported symbols (procedures, functions or
31354 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31355 section of @file{API.def} looks like:
31369 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
31370 (@pxref{Windows Calling Conventions}) for a Stdcall
31371 calling convention function in the exported symbols list.
31374 There can actually be other sections in a definition file, but these
31375 sections are not relevant to the discussion at hand.
31377 @node GNAT-Style Import Library
31378 @subsubsection GNAT-Style Import Library
31381 To create a static import library from @file{API.dll} with the GNAT tools
31382 you should proceed as follows:
31386 Create the definition file @file{API.def} (@pxref{The Definition File}).
31387 For that use the @code{dll2def} tool as follows:
31390 $ dll2def API.dll > API.def
31394 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31395 to standard output the list of entry points in the DLL. Note that if
31396 some routines in the DLL have the @code{Stdcall} convention
31397 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
31398 suffix then you'll have to edit @file{api.def} to add it, and specify
31399 @option{-k} to @command{gnatdll} when creating the import library.
31402 Here are some hints to find the right @code{@@}@var{nn} suffix.
31406 If you have the Microsoft import library (.lib), it is possible to get
31407 the right symbols by using Microsoft @code{dumpbin} tool (see the
31408 corresponding Microsoft documentation for further details).
31411 $ dumpbin /exports api.lib
31415 If you have a message about a missing symbol at link time the compiler
31416 tells you what symbol is expected. You just have to go back to the
31417 definition file and add the right suffix.
31421 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31422 (@pxref{Using gnatdll}) as follows:
31425 $ gnatdll -e API.def -d API.dll
31429 @code{gnatdll} takes as input a definition file @file{API.def} and the
31430 name of the DLL containing the services listed in the definition file
31431 @file{API.dll}. The name of the static import library generated is
31432 computed from the name of the definition file as follows: if the
31433 definition file name is @var{xyz}@code{.def}, the import library name will
31434 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
31435 @option{-e} could have been removed because the name of the definition
31436 file (before the ``@code{.def}'' suffix) is the same as the name of the
31437 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
31440 @node Microsoft-Style Import Library
31441 @subsubsection Microsoft-Style Import Library
31444 With GNAT you can either use a GNAT-style or Microsoft-style import
31445 library. A Microsoft import library is needed only if you plan to make an
31446 Ada DLL available to applications developed with Microsoft
31447 tools (@pxref{Mixed-Language Programming on Windows}).
31449 To create a Microsoft-style import library for @file{API.dll} you
31450 should proceed as follows:
31454 Create the definition file @file{API.def} from the DLL. For this use either
31455 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
31456 tool (see the corresponding Microsoft documentation for further details).
31459 Build the actual import library using Microsoft's @code{lib} utility:
31462 $ lib -machine:IX86 -def:API.def -out:API.lib
31466 If you use the above command the definition file @file{API.def} must
31467 contain a line giving the name of the DLL:
31474 See the Microsoft documentation for further details about the usage of
31478 @node Building DLLs with GNAT
31479 @section Building DLLs with GNAT
31480 @cindex DLLs, building
31483 This section explain how to build DLLs using the GNAT built-in DLL
31484 support. With the following procedure it is straight forward to build
31485 and use DLLs with GNAT.
31489 @item building object files
31491 The first step is to build all objects files that are to be included
31492 into the DLL. This is done by using the standard @command{gnatmake} tool.
31494 @item building the DLL
31496 To build the DLL you must use @command{gcc}'s @option{-shared}
31497 option. It is quite simple to use this method:
31500 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
31503 It is important to note that in this case all symbols found in the
31504 object files are automatically exported. It is possible to restrict
31505 the set of symbols to export by passing to @command{gcc} a definition
31506 file, @pxref{The Definition File}. For example:
31509 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
31512 If you use a definition file you must export the elaboration procedures
31513 for every package that required one. Elaboration procedures are named
31514 using the package name followed by "_E".
31516 @item preparing DLL to be used
31518 For the DLL to be used by client programs the bodies must be hidden
31519 from it and the .ali set with read-only attribute. This is very important
31520 otherwise GNAT will recompile all packages and will not actually use
31521 the code in the DLL. For example:
31525 $ copy *.ads *.ali api.dll apilib
31526 $ attrib +R apilib\*.ali
31531 At this point it is possible to use the DLL by directly linking
31532 against it. Note that you must use the GNAT shared runtime when using
31533 GNAT shared libraries. This is achieved by using @option{-shared} binder's
31537 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
31540 @node Building DLLs with GNAT Project files
31541 @section Building DLLs with GNAT Project files
31542 @cindex DLLs, building
31545 There is nothing specific to Windows in the build process.
31546 @pxref{Library Projects}.
31549 Due to a system limitation, it is not possible under Windows to create threads
31550 when inside the @code{DllMain} routine which is used for auto-initialization
31551 of shared libraries, so it is not possible to have library level tasks in SALs.
31553 @node Building DLLs with gnatdll
31554 @section Building DLLs with gnatdll
31555 @cindex DLLs, building
31558 * Limitations When Using Ada DLLs from Ada::
31559 * Exporting Ada Entities::
31560 * Ada DLLs and Elaboration::
31561 * Ada DLLs and Finalization::
31562 * Creating a Spec for Ada DLLs::
31563 * Creating the Definition File::
31568 Note that it is preferred to use the built-in GNAT DLL support
31569 (@pxref{Building DLLs with GNAT}) or GNAT Project files
31570 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
31572 This section explains how to build DLLs containing Ada code using
31573 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
31574 remainder of this section.
31576 The steps required to build an Ada DLL that is to be used by Ada as well as
31577 non-Ada applications are as follows:
31581 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
31582 @code{Stdcall} calling convention to avoid any Ada name mangling for the
31583 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
31584 skip this step if you plan to use the Ada DLL only from Ada applications.
31587 Your Ada code must export an initialization routine which calls the routine
31588 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
31589 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
31590 routine exported by the Ada DLL must be invoked by the clients of the DLL
31591 to initialize the DLL.
31594 When useful, the DLL should also export a finalization routine which calls
31595 routine @code{adafinal} generated by @command{gnatbind} to perform the
31596 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
31597 The finalization routine exported by the Ada DLL must be invoked by the
31598 clients of the DLL when the DLL services are no further needed.
31601 You must provide a spec for the services exported by the Ada DLL in each
31602 of the programming languages to which you plan to make the DLL available.
31605 You must provide a definition file listing the exported entities
31606 (@pxref{The Definition File}).
31609 Finally you must use @code{gnatdll} to produce the DLL and the import
31610 library (@pxref{Using gnatdll}).
31614 Note that a relocatable DLL stripped using the @code{strip}
31615 binutils tool will not be relocatable anymore. To build a DLL without
31616 debug information pass @code{-largs -s} to @code{gnatdll}. This
31617 restriction does not apply to a DLL built using a Library Project.
31618 @pxref{Library Projects}.
31620 @node Limitations When Using Ada DLLs from Ada
31621 @subsection Limitations When Using Ada DLLs from Ada
31624 When using Ada DLLs from Ada applications there is a limitation users
31625 should be aware of. Because on Windows the GNAT run time is not in a DLL of
31626 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
31627 each Ada DLL includes the services of the GNAT run time that are necessary
31628 to the Ada code inside the DLL. As a result, when an Ada program uses an
31629 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
31630 one in the main program.
31632 It is therefore not possible to exchange GNAT run-time objects between the
31633 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
31634 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
31637 It is completely safe to exchange plain elementary, array or record types,
31638 Windows object handles, etc.
31640 @node Exporting Ada Entities
31641 @subsection Exporting Ada Entities
31642 @cindex Export table
31645 Building a DLL is a way to encapsulate a set of services usable from any
31646 application. As a result, the Ada entities exported by a DLL should be
31647 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
31648 any Ada name mangling. As an example here is an Ada package
31649 @code{API}, spec and body, exporting two procedures, a function, and a
31652 @smallexample @c ada
31655 with Interfaces.C; use Interfaces;
31657 Count : C.int := 0;
31658 function Factorial (Val : C.int) return C.int;
31660 procedure Initialize_API;
31661 procedure Finalize_API;
31662 -- Initialization & Finalization routines. More in the next section.
31664 pragma Export (C, Initialize_API);
31665 pragma Export (C, Finalize_API);
31666 pragma Export (C, Count);
31667 pragma Export (C, Factorial);
31673 @smallexample @c ada
31676 package body API is
31677 function Factorial (Val : C.int) return C.int is
31680 Count := Count + 1;
31681 for K in 1 .. Val loop
31687 procedure Initialize_API is
31689 pragma Import (C, Adainit);
31692 end Initialize_API;
31694 procedure Finalize_API is
31695 procedure Adafinal;
31696 pragma Import (C, Adafinal);
31706 If the Ada DLL you are building will only be used by Ada applications
31707 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
31708 convention. As an example, the previous package could be written as
31711 @smallexample @c ada
31715 Count : Integer := 0;
31716 function Factorial (Val : Integer) return Integer;
31718 procedure Initialize_API;
31719 procedure Finalize_API;
31720 -- Initialization and Finalization routines.
31726 @smallexample @c ada
31729 package body API is
31730 function Factorial (Val : Integer) return Integer is
31731 Fact : Integer := 1;
31733 Count := Count + 1;
31734 for K in 1 .. Val loop
31741 -- The remainder of this package body is unchanged.
31748 Note that if you do not export the Ada entities with a @code{C} or
31749 @code{Stdcall} convention you will have to provide the mangled Ada names
31750 in the definition file of the Ada DLL
31751 (@pxref{Creating the Definition File}).
31753 @node Ada DLLs and Elaboration
31754 @subsection Ada DLLs and Elaboration
31755 @cindex DLLs and elaboration
31758 The DLL that you are building contains your Ada code as well as all the
31759 routines in the Ada library that are needed by it. The first thing a
31760 user of your DLL must do is elaborate the Ada code
31761 (@pxref{Elaboration Order Handling in GNAT}).
31763 To achieve this you must export an initialization routine
31764 (@code{Initialize_API} in the previous example), which must be invoked
31765 before using any of the DLL services. This elaboration routine must call
31766 the Ada elaboration routine @code{adainit} generated by the GNAT binder
31767 (@pxref{Binding with Non-Ada Main Programs}). See the body of
31768 @code{Initialize_Api} for an example. Note that the GNAT binder is
31769 automatically invoked during the DLL build process by the @code{gnatdll}
31770 tool (@pxref{Using gnatdll}).
31772 When a DLL is loaded, Windows systematically invokes a routine called
31773 @code{DllMain}. It would therefore be possible to call @code{adainit}
31774 directly from @code{DllMain} without having to provide an explicit
31775 initialization routine. Unfortunately, it is not possible to call
31776 @code{adainit} from the @code{DllMain} if your program has library level
31777 tasks because access to the @code{DllMain} entry point is serialized by
31778 the system (that is, only a single thread can execute ``through'' it at a
31779 time), which means that the GNAT run time will deadlock waiting for the
31780 newly created task to complete its initialization.
31782 @node Ada DLLs and Finalization
31783 @subsection Ada DLLs and Finalization
31784 @cindex DLLs and finalization
31787 When the services of an Ada DLL are no longer needed, the client code should
31788 invoke the DLL finalization routine, if available. The DLL finalization
31789 routine is in charge of releasing all resources acquired by the DLL. In the
31790 case of the Ada code contained in the DLL, this is achieved by calling
31791 routine @code{adafinal} generated by the GNAT binder
31792 (@pxref{Binding with Non-Ada Main Programs}).
31793 See the body of @code{Finalize_Api} for an
31794 example. As already pointed out the GNAT binder is automatically invoked
31795 during the DLL build process by the @code{gnatdll} tool
31796 (@pxref{Using gnatdll}).
31798 @node Creating a Spec for Ada DLLs
31799 @subsection Creating a Spec for Ada DLLs
31802 To use the services exported by the Ada DLL from another programming
31803 language (e.g.@: C), you have to translate the specs of the exported Ada
31804 entities in that language. For instance in the case of @code{API.dll},
31805 the corresponding C header file could look like:
31810 extern int *_imp__count;
31811 #define count (*_imp__count)
31812 int factorial (int);
31818 It is important to understand that when building an Ada DLL to be used by
31819 other Ada applications, you need two different specs for the packages
31820 contained in the DLL: one for building the DLL and the other for using
31821 the DLL. This is because the @code{DLL} calling convention is needed to
31822 use a variable defined in a DLL, but when building the DLL, the variable
31823 must have either the @code{Ada} or @code{C} calling convention. As an
31824 example consider a DLL comprising the following package @code{API}:
31826 @smallexample @c ada
31830 Count : Integer := 0;
31832 -- Remainder of the package omitted.
31839 After producing a DLL containing package @code{API}, the spec that
31840 must be used to import @code{API.Count} from Ada code outside of the
31843 @smallexample @c ada
31848 pragma Import (DLL, Count);
31854 @node Creating the Definition File
31855 @subsection Creating the Definition File
31858 The definition file is the last file needed to build the DLL. It lists
31859 the exported symbols. As an example, the definition file for a DLL
31860 containing only package @code{API} (where all the entities are exported
31861 with a @code{C} calling convention) is:
31876 If the @code{C} calling convention is missing from package @code{API},
31877 then the definition file contains the mangled Ada names of the above
31878 entities, which in this case are:
31887 api__initialize_api
31892 @node Using gnatdll
31893 @subsection Using @code{gnatdll}
31897 * gnatdll Example::
31898 * gnatdll behind the Scenes::
31903 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
31904 and non-Ada sources that make up your DLL have been compiled.
31905 @code{gnatdll} is actually in charge of two distinct tasks: build the
31906 static import library for the DLL and the actual DLL. The form of the
31907 @code{gnatdll} command is
31911 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31916 where @var{list-of-files} is a list of ALI and object files. The object
31917 file list must be the exact list of objects corresponding to the non-Ada
31918 sources whose services are to be included in the DLL. The ALI file list
31919 must be the exact list of ALI files for the corresponding Ada sources
31920 whose services are to be included in the DLL. If @var{list-of-files} is
31921 missing, only the static import library is generated.
31924 You may specify any of the following switches to @code{gnatdll}:
31927 @item -a@ovar{address}
31928 @cindex @option{-a} (@code{gnatdll})
31929 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31930 specified the default address @var{0x11000000} will be used. By default,
31931 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31932 advise the reader to build relocatable DLL.
31934 @item -b @var{address}
31935 @cindex @option{-b} (@code{gnatdll})
31936 Set the relocatable DLL base address. By default the address is
31939 @item -bargs @var{opts}
31940 @cindex @option{-bargs} (@code{gnatdll})
31941 Binder options. Pass @var{opts} to the binder.
31943 @item -d @var{dllfile}
31944 @cindex @option{-d} (@code{gnatdll})
31945 @var{dllfile} is the name of the DLL. This switch must be present for
31946 @code{gnatdll} to do anything. The name of the generated import library is
31947 obtained algorithmically from @var{dllfile} as shown in the following
31948 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31949 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31950 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31951 as shown in the following example:
31952 if @var{dllfile} is @code{xyz.dll}, the definition
31953 file used is @code{xyz.def}.
31955 @item -e @var{deffile}
31956 @cindex @option{-e} (@code{gnatdll})
31957 @var{deffile} is the name of the definition file.
31960 @cindex @option{-g} (@code{gnatdll})
31961 Generate debugging information. This information is stored in the object
31962 file and copied from there to the final DLL file by the linker,
31963 where it can be read by the debugger. You must use the
31964 @option{-g} switch if you plan on using the debugger or the symbolic
31968 @cindex @option{-h} (@code{gnatdll})
31969 Help mode. Displays @code{gnatdll} switch usage information.
31972 @cindex @option{-I} (@code{gnatdll})
31973 Direct @code{gnatdll} to search the @var{dir} directory for source and
31974 object files needed to build the DLL.
31975 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31978 @cindex @option{-k} (@code{gnatdll})
31979 Removes the @code{@@}@var{nn} suffix from the import library's exported
31980 names, but keeps them for the link names. You must specify this
31981 option if you want to use a @code{Stdcall} function in a DLL for which
31982 the @code{@@}@var{nn} suffix has been removed. This is the case for most
31983 of the Windows NT DLL for example. This option has no effect when
31984 @option{-n} option is specified.
31986 @item -l @var{file}
31987 @cindex @option{-l} (@code{gnatdll})
31988 The list of ALI and object files used to build the DLL are listed in
31989 @var{file}, instead of being given in the command line. Each line in
31990 @var{file} contains the name of an ALI or object file.
31993 @cindex @option{-n} (@code{gnatdll})
31994 No Import. Do not create the import library.
31997 @cindex @option{-q} (@code{gnatdll})
31998 Quiet mode. Do not display unnecessary messages.
32001 @cindex @option{-v} (@code{gnatdll})
32002 Verbose mode. Display extra information.
32004 @item -largs @var{opts}
32005 @cindex @option{-largs} (@code{gnatdll})
32006 Linker options. Pass @var{opts} to the linker.
32009 @node gnatdll Example
32010 @subsubsection @code{gnatdll} Example
32013 As an example the command to build a relocatable DLL from @file{api.adb}
32014 once @file{api.adb} has been compiled and @file{api.def} created is
32017 $ gnatdll -d api.dll api.ali
32021 The above command creates two files: @file{libapi.dll.a} (the import
32022 library) and @file{api.dll} (the actual DLL). If you want to create
32023 only the DLL, just type:
32026 $ gnatdll -d api.dll -n api.ali
32030 Alternatively if you want to create just the import library, type:
32033 $ gnatdll -d api.dll
32036 @node gnatdll behind the Scenes
32037 @subsubsection @code{gnatdll} behind the Scenes
32040 This section details the steps involved in creating a DLL. @code{gnatdll}
32041 does these steps for you. Unless you are interested in understanding what
32042 goes on behind the scenes, you should skip this section.
32044 We use the previous example of a DLL containing the Ada package @code{API},
32045 to illustrate the steps necessary to build a DLL. The starting point is a
32046 set of objects that will make up the DLL and the corresponding ALI
32047 files. In the case of this example this means that @file{api.o} and
32048 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32053 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32054 the information necessary to generate relocation information for the
32060 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32065 In addition to the base file, the @command{gnatlink} command generates an
32066 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32067 asks @command{gnatlink} to generate the routines @code{DllMain} and
32068 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32069 is loaded into memory.
32072 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32073 export table (@file{api.exp}). The export table contains the relocation
32074 information in a form which can be used during the final link to ensure
32075 that the Windows loader is able to place the DLL anywhere in memory.
32079 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32080 --output-exp api.exp
32085 @code{gnatdll} builds the base file using the new export table. Note that
32086 @command{gnatbind} must be called once again since the binder generated file
32087 has been deleted during the previous call to @command{gnatlink}.
32092 $ gnatlink api -o api.jnk api.exp -mdll
32093 -Wl,--base-file,api.base
32098 @code{gnatdll} builds the new export table using the new base file and
32099 generates the DLL import library @file{libAPI.dll.a}.
32103 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32104 --output-exp api.exp --output-lib libAPI.a
32109 Finally @code{gnatdll} builds the relocatable DLL using the final export
32115 $ gnatlink api api.exp -o api.dll -mdll
32120 @node Using dlltool
32121 @subsubsection Using @code{dlltool}
32124 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32125 DLLs and static import libraries. This section summarizes the most
32126 common @code{dlltool} switches. The form of the @code{dlltool} command
32130 $ dlltool @ovar{switches}
32134 @code{dlltool} switches include:
32137 @item --base-file @var{basefile}
32138 @cindex @option{--base-file} (@command{dlltool})
32139 Read the base file @var{basefile} generated by the linker. This switch
32140 is used to create a relocatable DLL.
32142 @item --def @var{deffile}
32143 @cindex @option{--def} (@command{dlltool})
32144 Read the definition file.
32146 @item --dllname @var{name}
32147 @cindex @option{--dllname} (@command{dlltool})
32148 Gives the name of the DLL. This switch is used to embed the name of the
32149 DLL in the static import library generated by @code{dlltool} with switch
32150 @option{--output-lib}.
32153 @cindex @option{-k} (@command{dlltool})
32154 Kill @code{@@}@var{nn} from exported names
32155 (@pxref{Windows Calling Conventions}
32156 for a discussion about @code{Stdcall}-style symbols.
32159 @cindex @option{--help} (@command{dlltool})
32160 Prints the @code{dlltool} switches with a concise description.
32162 @item --output-exp @var{exportfile}
32163 @cindex @option{--output-exp} (@command{dlltool})
32164 Generate an export file @var{exportfile}. The export file contains the
32165 export table (list of symbols in the DLL) and is used to create the DLL.
32167 @item --output-lib @var{libfile}
32168 @cindex @option{--output-lib} (@command{dlltool})
32169 Generate a static import library @var{libfile}.
32172 @cindex @option{-v} (@command{dlltool})
32175 @item --as @var{assembler-name}
32176 @cindex @option{--as} (@command{dlltool})
32177 Use @var{assembler-name} as the assembler. The default is @code{as}.
32180 @node GNAT and Windows Resources
32181 @section GNAT and Windows Resources
32182 @cindex Resources, windows
32185 * Building Resources::
32186 * Compiling Resources::
32187 * Using Resources::
32191 Resources are an easy way to add Windows specific objects to your
32192 application. The objects that can be added as resources include:
32221 This section explains how to build, compile and use resources.
32223 @node Building Resources
32224 @subsection Building Resources
32225 @cindex Resources, building
32228 A resource file is an ASCII file. By convention resource files have an
32229 @file{.rc} extension.
32230 The easiest way to build a resource file is to use Microsoft tools
32231 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32232 @code{dlgedit.exe} to build dialogs.
32233 It is always possible to build an @file{.rc} file yourself by writing a
32236 It is not our objective to explain how to write a resource file. A
32237 complete description of the resource script language can be found in the
32238 Microsoft documentation.
32240 @node Compiling Resources
32241 @subsection Compiling Resources
32244 @cindex Resources, compiling
32247 This section describes how to build a GNAT-compatible (COFF) object file
32248 containing the resources. This is done using the Resource Compiler
32249 @code{windres} as follows:
32252 $ windres -i myres.rc -o myres.o
32256 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32257 file. You can specify an alternate preprocessor (usually named
32258 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32259 parameter. A list of all possible options may be obtained by entering
32260 the command @code{windres} @option{--help}.
32262 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32263 to produce a @file{.res} file (binary resource file). See the
32264 corresponding Microsoft documentation for further details. In this case
32265 you need to use @code{windres} to translate the @file{.res} file to a
32266 GNAT-compatible object file as follows:
32269 $ windres -i myres.res -o myres.o
32272 @node Using Resources
32273 @subsection Using Resources
32274 @cindex Resources, using
32277 To include the resource file in your program just add the
32278 GNAT-compatible object file for the resource(s) to the linker
32279 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32283 $ gnatmake myprog -largs myres.o
32286 @node Debugging a DLL
32287 @section Debugging a DLL
32288 @cindex DLL debugging
32291 * Program and DLL Both Built with GCC/GNAT::
32292 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32296 Debugging a DLL is similar to debugging a standard program. But
32297 we have to deal with two different executable parts: the DLL and the
32298 program that uses it. We have the following four possibilities:
32302 The program and the DLL are built with @code{GCC/GNAT}.
32304 The program is built with foreign tools and the DLL is built with
32307 The program is built with @code{GCC/GNAT} and the DLL is built with
32313 In this section we address only cases one and two above.
32314 There is no point in trying to debug
32315 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32316 information in it. To do so you must use a debugger compatible with the
32317 tools suite used to build the DLL.
32319 @node Program and DLL Both Built with GCC/GNAT
32320 @subsection Program and DLL Both Built with GCC/GNAT
32323 This is the simplest case. Both the DLL and the program have @code{GDB}
32324 compatible debugging information. It is then possible to break anywhere in
32325 the process. Let's suppose here that the main procedure is named
32326 @code{ada_main} and that in the DLL there is an entry point named
32330 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32331 program must have been built with the debugging information (see GNAT -g
32332 switch). Here are the step-by-step instructions for debugging it:
32335 @item Launch @code{GDB} on the main program.
32341 @item Start the program and stop at the beginning of the main procedure
32348 This step is required to be able to set a breakpoint inside the DLL. As long
32349 as the program is not run, the DLL is not loaded. This has the
32350 consequence that the DLL debugging information is also not loaded, so it is not
32351 possible to set a breakpoint in the DLL.
32353 @item Set a breakpoint inside the DLL
32356 (gdb) break ada_dll
32363 At this stage a breakpoint is set inside the DLL. From there on
32364 you can use the standard approach to debug the whole program
32365 (@pxref{Running and Debugging Ada Programs}).
32368 @c This used to work, probably because the DLLs were non-relocatable
32369 @c keep this section around until the problem is sorted out.
32371 To break on the @code{DllMain} routine it is not possible to follow
32372 the procedure above. At the time the program stop on @code{ada_main}
32373 the @code{DllMain} routine as already been called. Either you can use
32374 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32377 @item Launch @code{GDB} on the main program.
32383 @item Load DLL symbols
32386 (gdb) add-sym api.dll
32389 @item Set a breakpoint inside the DLL
32392 (gdb) break ada_dll.adb:45
32395 Note that at this point it is not possible to break using the routine symbol
32396 directly as the program is not yet running. The solution is to break
32397 on the proper line (break in @file{ada_dll.adb} line 45).
32399 @item Start the program
32408 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32409 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32412 * Debugging the DLL Directly::
32413 * Attaching to a Running Process::
32417 In this case things are slightly more complex because it is not possible to
32418 start the main program and then break at the beginning to load the DLL and the
32419 associated DLL debugging information. It is not possible to break at the
32420 beginning of the program because there is no @code{GDB} debugging information,
32421 and therefore there is no direct way of getting initial control. This
32422 section addresses this issue by describing some methods that can be used
32423 to break somewhere in the DLL to debug it.
32426 First suppose that the main procedure is named @code{main} (this is for
32427 example some C code built with Microsoft Visual C) and that there is a
32428 DLL named @code{test.dll} containing an Ada entry point named
32432 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32433 been built with debugging information (see GNAT -g option).
32435 @node Debugging the DLL Directly
32436 @subsubsection Debugging the DLL Directly
32440 Find out the executable starting address
32443 $ objdump --file-header main.exe
32446 The starting address is reported on the last line. For example:
32449 main.exe: file format pei-i386
32450 architecture: i386, flags 0x0000010a:
32451 EXEC_P, HAS_DEBUG, D_PAGED
32452 start address 0x00401010
32456 Launch the debugger on the executable.
32463 Set a breakpoint at the starting address, and launch the program.
32466 $ (gdb) break *0x00401010
32470 The program will stop at the given address.
32473 Set a breakpoint on a DLL subroutine.
32476 (gdb) break ada_dll.adb:45
32479 Or if you want to break using a symbol on the DLL, you need first to
32480 select the Ada language (language used by the DLL).
32483 (gdb) set language ada
32484 (gdb) break ada_dll
32488 Continue the program.
32495 This will run the program until it reaches the breakpoint that has been
32496 set. From that point you can use the standard way to debug a program
32497 as described in (@pxref{Running and Debugging Ada Programs}).
32502 It is also possible to debug the DLL by attaching to a running process.
32504 @node Attaching to a Running Process
32505 @subsubsection Attaching to a Running Process
32506 @cindex DLL debugging, attach to process
32509 With @code{GDB} it is always possible to debug a running process by
32510 attaching to it. It is possible to debug a DLL this way. The limitation
32511 of this approach is that the DLL must run long enough to perform the
32512 attach operation. It may be useful for instance to insert a time wasting
32513 loop in the code of the DLL to meet this criterion.
32517 @item Launch the main program @file{main.exe}.
32523 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
32524 that the process PID for @file{main.exe} is 208.
32532 @item Attach to the running process to be debugged.
32538 @item Load the process debugging information.
32541 (gdb) symbol-file main.exe
32544 @item Break somewhere in the DLL.
32547 (gdb) break ada_dll
32550 @item Continue process execution.
32559 This last step will resume the process execution, and stop at
32560 the breakpoint we have set. From there you can use the standard
32561 approach to debug a program as described in
32562 (@pxref{Running and Debugging Ada Programs}).
32564 @node Setting Stack Size from gnatlink
32565 @section Setting Stack Size from @command{gnatlink}
32568 It is possible to specify the program stack size at link time. On modern
32569 versions of Windows, starting with XP, this is mostly useful to set the size of
32570 the main stack (environment task). The other task stacks are set with pragma
32571 Storage_Size or with the @command{gnatbind -d} command.
32573 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
32574 reserve size of individual tasks, the link-time stack size applies to all
32575 tasks, and pragma Storage_Size has no effect.
32576 In particular, Stack Overflow checks are made against this
32577 link-time specified size.
32579 This setting can be done with
32580 @command{gnatlink} using either:
32584 @item using @option{-Xlinker} linker option
32587 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
32590 This sets the stack reserve size to 0x10000 bytes and the stack commit
32591 size to 0x1000 bytes.
32593 @item using @option{-Wl} linker option
32596 $ gnatlink hello -Wl,--stack=0x1000000
32599 This sets the stack reserve size to 0x1000000 bytes. Note that with
32600 @option{-Wl} option it is not possible to set the stack commit size
32601 because the coma is a separator for this option.
32605 @node Setting Heap Size from gnatlink
32606 @section Setting Heap Size from @command{gnatlink}
32609 Under Windows systems, it is possible to specify the program heap size from
32610 @command{gnatlink} using either:
32614 @item using @option{-Xlinker} linker option
32617 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
32620 This sets the heap reserve size to 0x10000 bytes and the heap commit
32621 size to 0x1000 bytes.
32623 @item using @option{-Wl} linker option
32626 $ gnatlink hello -Wl,--heap=0x1000000
32629 This sets the heap reserve size to 0x1000000 bytes. Note that with
32630 @option{-Wl} option it is not possible to set the heap commit size
32631 because the coma is a separator for this option.
32637 @c **********************************
32638 @c * GNU Free Documentation License *
32639 @c **********************************
32641 @c GNU Free Documentation License
32643 @node Index,,GNU Free Documentation License, Top
32649 @c Put table of contents at end, otherwise it precedes the "title page" in
32650 @c the .txt version
32651 @c Edit the pdf file to move the contents to the beginning, after the title