* testsuite/libgomp.fortran/vla7.f90: Add -w to options.
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blobc49473b2cdb0deb32c41ff7faf9b0378f26db9fc
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c                     Copyright (C) 1992-2005, AdaCore                       o
11 @c                                                                            o
12 @c  GNAT is free software;  you can  redistribute it  and/or modify it under  o
13 @c  terms of the  GNU General Public License as published  by the Free Soft-  o
14 @c  ware  Foundation;  either version 2,  or (at your option) any later ver-  o
15 @c  sion.  GNAT is distributed in the hope that it will be useful, but WITH-  o
16 @c  OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY  o
17 @c  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License  o
18 @c  for  more details.  You should have  received  a copy of the GNU General  o
19 @c  Public License  distributed with GNAT;  see file COPYING.  If not, write  o
20 @c  to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor,  o
21 @c  Boston, MA 02110-1301, USA.                                               o
22 @c                                                                            o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c                           GNAT_UGN Style Guide
29 @c  1. Always put a @noindent on the line before the first paragraph
30 @c     after any of these commands:
32 @c          @chapter
33 @c          @section
34 @c          @subsection
35 @c          @subsubsection
36 @c          @subsubsubsection
38 @c          @end smallexample
39 @c          @end itemize
40 @c          @end enumerate
42 @c  2. DO NOT use @example. Use @smallexample instead.
43 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c        context.  These can interfere with the readability of the texi
45 @c        source file.  Instead, use one of the following annotated
46 @c        @smallexample commands, and preprocess the texi file with the
47 @c        ada2texi tool (which generates appropriate highlighting):
48 @c        @smallexample @c ada
49 @c        @smallexample @c adanocomment
50 @c        @smallexample @c projectfile
51 @c     b) The "@c ada" markup will result in boldface for reserved words
52 @c        and italics for comments
53 @c     c) The "@c adanocomment" markup will result only in boldface for
54 @c        reserved words (comments are left alone)
55 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c        of reserved words include the new reserved words for project files
58 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c     command must be preceded by two empty lines
61 @c  4. The @item command should be on a line of its own if it is in an
62 @c     @itemize or @enumerate command.
64 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
65 @c     or "ali".
67 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
68 @c     cause the document build to fail.
70 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c     This command inhibits page breaks, so long examples in a @cartouche can
72 @c     lead to large, ugly patches of empty space on a page.
74 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c        or the unw flag set.  The unw flag covers topics for both Unix and
76 @c        Windows.
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
80 @ifset vms
81 @setfilename gnat_ugn_vms.info
82 @end ifset
84 @ifset unw
85 @setfilename gnat_ugn_unw.info
86 @end ifset
88 @set FSFEDITION
89 @set EDITION GNAT
91 @ifset unw
92 @set PLATFORM
93 @set FILE gnat_ugn_unw
94 @end ifset
96 @ifset vms
97 @set PLATFORM OpenVMS
98 @set FILE gnat_ugn_vms
99 @end ifset
101 @settitle @value{EDITION} User's Guide @value{PLATFORM}
102 @dircategory GNU Ada tools
103 @direntry
104 * @value{EDITION} User's Guide (@value{FILE}) @value{PLATFORM}
105 @end direntry
107 @include gcc-common.texi
109 @setchapternewpage odd
110 @syncodeindex fn cp
111 @c %**end of header
113 @copying
114 Copyright @copyright{} 1995-2005, Free Software Foundation
116 Permission is granted to copy, distribute and/or modify this document
117 under the terms of the GNU Free Documentation License, Version 1.2
118 or any later version published by the Free Software Foundation;
119 with the Invariant Sections being ``GNU Free Documentation License'', with the
120 Front-Cover Texts being
121 ``@value{EDITION} User's Guide'',
122 and with no Back-Cover Texts.
123 A copy of the license is included in the section entitled
124 ``GNU Free Documentation License''.
125 @end copying
127 @titlepage
129 @title @value{EDITION} User's Guide
131 @ifset vms
132 @sp 1
133 @flushright
134 @titlefont{@i{@value{PLATFORM}}}
135 @end flushright
136 @end ifset
138 @sp 2
140 @subtitle GNAT, The GNU Ada 95 Compiler
141 @subtitle GCC version @value{version-GCC}
143 @author AdaCore
145 @page
146 @vskip 0pt plus 1filll
148 @insertcopying
150 @end titlepage
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
159 @noindent
160 GNAT, The GNU Ada 95 Compiler@*
161 GCC version @value{version-GCC}@*
163 @noindent
164 AdaCore@*
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * The Cross-Referencing Tools gnatxref and gnatfind::
180 * The GNAT Pretty-Printer gnatpp::
181 * The GNAT Metric Tool gnatmetric::
182 * File Name Krunching Using gnatkr::
183 * Preprocessing Using gnatprep::
184 @ifset vms
185 * The GNAT Run-Time Library Builder gnatlbr::
186 @end ifset
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Memory Management Issues::
194 * Stack Related Tools::
195 * Creating Sample Bodies Using gnatstub::
196 * Other Utility Programs::
197 * Running and Debugging Ada Programs::
198 @ifset vms
199 * Compatibility with HP Ada::
200 @end ifset
201 * Platform-Specific Information for the Run-Time Libraries::
202 * Example of Binder Output File::
203 * Elaboration Order Handling in GNAT::
204 * Inline Assembler::
205 * Compatibility and Porting Guide::
206 @ifset unw
207 * Microsoft Windows Topics::
208 @end ifset
209 * GNU Free Documentation License::
210 * Index::
212  --- The Detailed Node Listing ---
214 About This Guide
216 * What This Guide Contains::
217 * What You Should Know before Reading This Guide::
218 * Related Information::
219 * Conventions::
221 Getting Started with GNAT
223 * Running GNAT::
224 * Running a Simple Ada Program::
225 * Running a Program with Multiple Units::
226 * Using the gnatmake Utility::
227 @ifset vms
228 * Editing with Emacs::
229 @end ifset
230 @ifclear vms
231 * Introduction to GPS::
232 * Introduction to Glide and GVD::
233 @end ifclear
235 The GNAT Compilation Model
237 * Source Representation::
238 * Foreign Language Representation::
239 * File Naming Rules::
240 * Using Other File Names::
241 * Alternative File Naming Schemes::
242 * Generating Object Files::
243 * Source Dependencies::
244 * The Ada Library Information Files::
245 * Binding an Ada Program::
246 * Mixed Language Programming::
247 * Building Mixed Ada & C++ Programs::
248 * Comparison between GNAT and C/C++ Compilation Models::
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
254 Foreign Language Representation
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
260 Compiling Ada Programs With gcc
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
268 Switches for gcc
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
291 Binding Ada Programs With gnatbind
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
299 Switches for gnatbind
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
308 Linking Using gnatlink
310 * Running gnatlink::
311 * Switches for gnatlink::
312 * Setting Stack Size from gnatlink::
313 * Setting Heap Size from gnatlink::
315 The GNAT Make Program gnatmake
317 * Running gnatmake::
318 * Switches for gnatmake::
319 * Mode Switches for gnatmake::
320 * Notes on the Command Line::
321 * How gnatmake Works::
322 * Examples of gnatmake Usage::
324 Improving Performance
325 * Performance Considerations::
326 * Reducing the Size of Ada Executables with gnatelim::
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
340 Reducing the Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
347 Renaming Files Using gnatchop
349 * Handling Files with Multiple Units::
350 * Operating gnatchop in Compilation Mode::
351 * Command Line for gnatchop::
352 * Switches for gnatchop::
353 * Examples of gnatchop Usage::
355 Configuration Pragmas
357 * Handling of Configuration Pragmas::
358 * The Configuration Pragmas Files::
360 Handling Arbitrary File Naming Conventions Using gnatname
362 * Arbitrary File Naming Conventions::
363 * Running gnatname::
364 * Switches for gnatname::
365 * Examples of gnatname Usage::
367 GNAT Project Manager
369 * Introduction::
370 * Examples of Project Files::
371 * Project File Syntax::
372 * Objects and Sources in Project Files::
373 * Importing Projects::
374 * Project Extension::
375 * Project Hierarchy Extension::
376 * External References in Project Files::
377 * Packages in Project Files::
378 * Variables from Imported Projects::
379 * Naming Schemes::
380 * Library Projects::
381 * Stand-alone Library Projects::
382 * Switches Related to Project Files::
383 * Tools Supporting Project Files::
384 * An Extended Example::
385 * Project File Complete Syntax::
387 The Cross-Referencing Tools gnatxref and gnatfind
389 * gnatxref Switches::
390 * gnatfind Switches::
391 * Project Files for gnatxref and gnatfind::
392 * Regular Expressions in gnatfind and gnatxref::
393 * Examples of gnatxref Usage::
394 * Examples of gnatfind Usage::
396 The GNAT Pretty-Printer gnatpp
398 * Switches for gnatpp::
399 * Formatting Rules::
401 The GNAT Metrics Tool gnatmetric
403 * Switches for gnatmetric::
405 File Name Krunching Using gnatkr
407 * About gnatkr::
408 * Using gnatkr::
409 * Krunching Method::
410 * Examples of gnatkr Usage::
412 Preprocessing Using gnatprep
414 * Using gnatprep::
415 * Switches for gnatprep::
416 * Form of Definitions File::
417 * Form of Input Text for gnatprep::
419 @ifset vms
420 The GNAT Run-Time Library Builder gnatlbr
422 * Running gnatlbr::
423 * Switches for gnatlbr::
424 * Examples of gnatlbr Usage::
425 @end ifset
427 The GNAT Library Browser gnatls
429 * Running gnatls::
430 * Switches for gnatls::
431 * Examples of gnatls Usage::
433 Cleaning Up Using gnatclean
435 * Running gnatclean::
436 * Switches for gnatclean::
437 @c * Examples of gnatclean Usage::
439 @ifclear vms
441 GNAT and Libraries
443 * Introduction to Libraries in GNAT::
444 * General Ada Libraries::
445 * Stand-alone Ada Libraries::
446 * Rebuilding the GNAT Run-Time Library::
448 Using the GNU make Utility
450 * Using gnatmake in a Makefile::
451 * Automatically Creating a List of Directories::
452 * Generating the Command Line Switches::
453 * Overcoming Command Line Length Limits::
454 @end ifclear
456 Memory Management Issues
458 * Some Useful Memory Pools::
459 * The GNAT Debug Pool Facility::
460 @ifclear vms
461 * The gnatmem Tool::
462 @end ifclear
464 Stack Related Tools
466 * Stack Overflow Checking::
467 * Static Stack Usage Analysis::
468 * Dynamic Stack Usage Analysis::
470 Some Useful Memory Pools
472 The GNAT Debug Pool Facility
474 @ifclear vms
475 The gnatmem Tool
477 * Running gnatmem::
478 * Switches for gnatmem::
479 * Example of gnatmem Usage::
480 @end ifclear
482  Sample Bodies Using gnatstub
484 * Running gnatstub::
485 * Switches for gnatstub::
487 Other Utility Programs
489 * Using Other Utility Programs with GNAT::
490 * The External Symbol Naming Scheme of GNAT::
491 @ifclear vms
492 * Ada Mode for Glide::
493 @end ifclear
494 * Converting Ada Files to html with gnathtml::
496 Running and Debugging Ada Programs
498 * The GNAT Debugger GDB::
499 * Running GDB::
500 * Introduction to GDB Commands::
501 * Using Ada Expressions::
502 * Calling User-Defined Subprograms::
503 * Using the Next Command in a Function::
504 * Ada Exceptions::
505 * Ada Tasks::
506 * Debugging Generic Units::
507 * GNAT Abnormal Termination or Failure to Terminate::
508 * Naming Conventions for GNAT Source Files::
509 * Getting Internal Debugging Information::
510 * Stack Traceback::
512 @ifset vms
513 * LSE::
514 @end ifset
516 @ifset vms
517 Compatibility with HP Ada
519 * Ada 95 Compatibility::
520 * Differences in the Definition of Package System::
521 * Language-Related Features::
522 * The Package STANDARD::
523 * The Package SYSTEM::
524 * Tasking and Task-Related Features::
525 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
526 * Pragmas and Pragma-Related Features::
527 * Library of Predefined Units::
528 * Bindings::
529 * Main Program Definition::
530 * Implementation-Defined Attributes::
531 * Compiler and Run-Time Interfacing::
532 * Program Compilation and Library Management::
533 * Input-Output::
534 * Implementation Limits::
536 Language-Related Features
538 * Integer Types and Representations::
539 * Floating-Point Types and Representations::
540 * Pragmas Float_Representation and Long_Float::
541 * Fixed-Point Types and Representations::
542 * Record and Array Component Alignment::
543 * Address Clauses::
544 * Other Representation Clauses::
546 Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
548 * Assigning Task IDs::
549 * Task IDs and Delays::
550 * Task-Related Pragmas::
551 * Scheduling and Task Priority::
552 * The Task Stack::
553 * External Interrupts::
555 Pragmas and Pragma-Related Features
557 * Restrictions on the Pragma INLINE::
558 * Restrictions on the Pragma INTERFACE::
559 * Restrictions on the Pragma SYSTEM_NAME::
561 Library of Predefined Units
563 * Changes to DECLIB::
565 Bindings
567 * Shared Libraries and Options Files::
568 * Interfaces to C::
569 @end ifset
571 Platform-Specific Information for the Run-Time Libraries
573 * Summary of Run-Time Configurations::
574 * Specifying a Run-Time Library::
575 * Choosing the Scheduling Policy::
576 * Solaris-Specific Considerations::
577 * IRIX-Specific Considerations::
578 * Linux-Specific Considerations::
579 * AIX-Specific Considerations::
581 Example of Binder Output File
583 Elaboration Order Handling in GNAT
585 * Elaboration Code in Ada 95::
586 * Checking the Elaboration Order in Ada 95::
587 * Controlling the Elaboration Order in Ada 95::
588 * Controlling Elaboration in GNAT - Internal Calls::
589 * Controlling Elaboration in GNAT - External Calls::
590 * Default Behavior in GNAT - Ensuring Safety::
591 * Treatment of Pragma Elaborate::
592 * Elaboration Issues for Library Tasks::
593 * Mixing Elaboration Models::
594 * What to Do If the Default Elaboration Behavior Fails::
595 * Elaboration for Access-to-Subprogram Values::
596 * Summary of Procedures for Elaboration Control::
597 * Other Elaboration Order Considerations::
599 Inline Assembler
601 * Basic Assembler Syntax::
602 * A Simple Example of Inline Assembler::
603 * Output Variables in Inline Assembler::
604 * Input Variables in Inline Assembler::
605 * Inlining Inline Assembler Code::
606 * Other Asm Functionality::
608 Compatibility and Porting Guide
610 * Compatibility with Ada 83::
611 * Implementation-dependent characteristics::
612 * Compatibility with HP Ada 83::
613 * Compatibility with Other Ada 95 Systems::
614 * Representation Clauses::
615 @ifset vms
616 * Transitioning from Alpha to Integrity OpenVMS::
617 @end ifset
619 @ifset unw
620 Microsoft Windows Topics
622 * Using GNAT on Windows::
623 * CONSOLE and WINDOWS subsystems::
624 * Temporary Files::
625 * Mixed-Language Programming on Windows::
626 * Windows Calling Conventions::
627 * Introduction to Dynamic Link Libraries (DLLs)::
628 * Using DLLs with GNAT::
629 * Building DLLs with GNAT::
630 * GNAT and Windows Resources::
631 * Debugging a DLL::
632 * GNAT and COM/DCOM Objects::
633 @end ifset
635 * Index::
636 @end menu
637 @end ifnottex
639 @node About This Guide
640 @unnumbered About This Guide
642 @noindent
643 @ifset vms
644 This guide describes the use of @value{EDITION},
645 a full language compiler for the Ada
646 95 programming language, implemented on HP's Alpha and
647 Integrity (ia64) OpenVMS platforms.
648 @end ifset
649 @ifclear vms
650 This guide describes the use of @value{EDITION},
651 a compiler and software development
652 toolset for the full Ada 95 programming language.
653 @end ifclear
654 It describes the features of the compiler and tools, and details
655 how to use them to build Ada 95 applications.
657 @ifset PROEDITION
658 For ease of exposition, ``GNAT Pro'' will be referred to simply as
659 ``GNAT'' in the remainder of this document.
660 @end ifset
662 @menu
663 * What This Guide Contains::
664 * What You Should Know before Reading This Guide::
665 * Related Information::
666 * Conventions::
667 @end menu
669 @node What This Guide Contains
670 @unnumberedsec What This Guide Contains
672 @noindent
673 This guide contains the following chapters:
674 @itemize @bullet
676 @item
677 @ref{Getting Started with GNAT}, describes how to get started compiling
678 and running Ada programs with the GNAT Ada programming environment.
679 @item
680 @ref{The GNAT Compilation Model}, describes the compilation model used
681 by GNAT.
683 @item
684 @ref{Compiling Using gcc}, describes how to compile
685 Ada programs with @command{gcc}, the Ada compiler.
687 @item
688 @ref{Binding Using gnatbind}, describes how to
689 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
690 utility.
692 @item
693 @ref{Linking Using gnatlink},
694 describes @command{gnatlink}, a
695 program that provides for linking using the GNAT run-time library to
696 construct a program. @command{gnatlink} can also incorporate foreign language
697 object units into the executable.
699 @item
700 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
701 utility that automatically determines the set of sources
702 needed by an Ada compilation unit, and executes the necessary compilations
703 binding and link.
705 @item
706 @ref{Improving Performance}, shows various techniques for making your
707 Ada program run faster or take less space.
708 It discusses the effect of the compiler's optimization switch and
709 also describes the @command{gnatelim} tool.
711 @item
712 @ref{Renaming Files Using gnatchop}, describes
713 @code{gnatchop}, a utility that allows you to preprocess a file that
714 contains Ada source code, and split it into one or more new files, one
715 for each compilation unit.
717 @item
718 @ref{Configuration Pragmas}, describes the configuration pragmas
719 handled by GNAT.
721 @item
722 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
723 shows how to override the default GNAT file naming conventions,
724 either for an individual unit or globally.
726 @item
727 @ref{GNAT Project Manager}, describes how to use project files
728 to organize large projects.
730 @item
731 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
732 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
733 way to navigate through sources.
735 @item
736 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
737 version of an Ada source file with control over casing, indentation,
738 comment placement, and other elements of program presentation style.
740 @item
741 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
742 metrics for an Ada source file, such as the number of types and subprograms,
743 and assorted complexity measures.
745 @item
746 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
747 file name krunching utility, used to handle shortened
748 file names on operating systems with a limit on the length of names.
750 @item
751 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
752 preprocessor utility that allows a single source file to be used to
753 generate multiple or parameterized source files, by means of macro
754 substitution.
756 @ifset vms
757 @item
758 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
759 a tool for rebuilding the GNAT run time with user-supplied
760 configuration pragmas.
761 @end ifset
763 @item
764 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
765 utility that displays information about compiled units, including dependences
766 on the corresponding sources files, and consistency of compilations.
768 @item
769 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
770 to delete files that are produced by the compiler, binder and linker.
772 @ifclear vms
773 @item
774 @ref{GNAT and Libraries}, describes the process of creating and using
775 Libraries with GNAT. It also describes how to recompile the GNAT run-time
776 library.
778 @item
779 @ref{Using the GNU make Utility}, describes some techniques for using
780 the GNAT toolset in Makefiles.
781 @end ifclear
783 @item
784 @ref{Memory Management Issues}, describes some useful predefined storage pools
785 and in particular the GNAT Debug Pool facility, which helps detect incorrect
786 memory references.
787 @ifclear vms
788 It also describes @command{gnatmem}, a utility that monitors dynamic
789 allocation and deallocation and helps detect ``memory leaks''.
790 @end ifclear
792 @item
793 @ref{Stack Related Tools}, describes some useful tools associated to stack.
794 In particular, dynamic and statick usage measurements.
796 @item
797 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
798 a utility that generates empty but compilable bodies for library units.
800 @item
801 @ref{Other Utility Programs}, discusses several other GNAT utilities,
802 including @code{gnathtml}.
804 @item
805 @ref{Running and Debugging Ada Programs}, describes how to run and debug
806 Ada programs.
808 @ifset vms
809 @item
810 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
811 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
812 developed by Digital Equipment Corporation and currently supported by HP.}
813 for OpenVMS Alpha. This product was formerly known as DEC Ada, and for
814 historical compatibility reasons, the relevant libraries still use the
815 DEC prefix.
816 @end ifset
818 @item
819 @ref{Platform-Specific Information for the Run-Time Libraries},
820 describes the various run-time
821 libraries supported by GNAT on various platforms and explains how to
822 choose a particular library.
824 @item
825 @ref{Example of Binder Output File}, shows the source code for the binder
826 output file for a sample program.
828 @item
829 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
830 you deal with elaboration order issues.
832 @item
833 @ref{Inline Assembler}, shows how to use the inline assembly facility
834 in an Ada program.
836 @item
837 @ref{Compatibility and Porting Guide}, includes sections on compatibility
838 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
839 in porting code from other environments.
841 @ifset unw
842 @item
843 @ref{Microsoft Windows Topics}, presents information relevant to the
844 Microsoft Windows platform.
845 @end ifset
846 @end itemize
848 @c *************************************************
849 @node What You Should Know before Reading This Guide
850 @c *************************************************
851 @unnumberedsec What You Should Know before Reading This Guide
853 @cindex Ada 95 Language Reference Manual
854 @noindent
855 This user's guide assumes that you are familiar with Ada 95 language, as
856 described in the International Standard ANSI/ISO/IEC-8652:1995, January
857 1995.
859 @node Related Information
860 @unnumberedsec Related Information
862 @noindent
863 For further information about related tools, refer to the following
864 documents:
866 @itemize @bullet
867 @item
868 @cite{GNAT Reference Manual}, which contains all reference
869 material for the GNAT implementation of Ada 95.
871 @ifset unw
872 @item
873 @cite{Using the GNAT Programming System}, which describes the GPS
874 integrated development environment.
876 @item
877 @cite{GNAT Programming System Tutorial}, which introduces the
878 main GPS features through examples.
879 @end ifset
881 @item
882 @cite{Ada 95 Language Reference Manual}, which contains all reference
883 material for the Ada 95 programming language.
885 @item
886 @cite{Debugging with GDB}
887 @ifset vms
888 , located in the GNU:[DOCS] directory,
889 @end ifset
890 contains all details on the use of the GNU source-level debugger.
892 @item
893 @cite{GNU Emacs Manual}
894 @ifset vms
895 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
896 @end ifset
897 contains full information on the extensible editor and programming
898 environment Emacs.
900 @end itemize
902 @c **************
903 @node Conventions
904 @unnumberedsec Conventions
905 @cindex Conventions
906 @cindex Typographical conventions
908 @noindent
909 Following are examples of the typographical and graphic conventions used
910 in this guide:
912 @itemize @bullet
913 @item
914 @code{Functions}, @code{utility program names}, @code{standard names},
915 and @code{classes}.
917 @item
918 @samp{Option flags}
920 @item
921 @file{File Names}, @file{button names}, and @file{field names}.
923 @item
924 @var{Variables}.
926 @item
927 @emph{Emphasis}.
929 @item
930 [optional information or parameters]
932 @item
933 Examples are described by text
934 @smallexample
935 and then shown this way.
936 @end smallexample
937 @end itemize
939 @noindent
940 Commands that are entered by the user are preceded in this manual by the
941 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
942 uses this sequence as a prompt, then the commands will appear exactly as
943 you see them in the manual. If your system uses some other prompt, then
944 the command will appear with the @code{$} replaced by whatever prompt
945 character you are using.
947 @ifset unw
948 Full file names are shown with the ``@code{/}'' character
949 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
950 If you are using GNAT on a Windows platform, please note that
951 the ``@code{\}'' character should be used instead.
952 @end ifset
954 @c ****************************
955 @node Getting Started with GNAT
956 @chapter Getting Started with GNAT
958 @noindent
959 This chapter describes some simple ways of using GNAT to build
960 executable Ada programs.
961 @ifset unw
962 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
963 show how to use the command line environment.
964 @ref{Introduction to Glide and GVD}, provides a brief
965 introduction to the visually-oriented IDE for GNAT.
966 Supplementing Glide on some platforms is GPS, the
967 GNAT Programming System, which offers a richer graphical
968 ``look and feel'', enhanced configurability, support for
969 development in other programming language, comprehensive
970 browsing features, and many other capabilities.
971 For information on GPS please refer to
972 @cite{Using the GNAT Programming System}.
973 @end ifset
975 @menu
976 * Running GNAT::
977 * Running a Simple Ada Program::
978 * Running a Program with Multiple Units::
979 * Using the gnatmake Utility::
980 @ifset vms
981 * Editing with Emacs::
982 @end ifset
983 @ifclear vms
984 * Introduction to GPS::
985 * Introduction to Glide and GVD::
986 @end ifclear
987 @end menu
989 @node Running GNAT
990 @section Running GNAT
992 @noindent
993 Three steps are needed to create an executable file from an Ada source
994 file:
996 @enumerate
997 @item
998 The source file(s) must be compiled.
999 @item
1000 The file(s) must be bound using the GNAT binder.
1001 @item
1002 All appropriate object files must be linked to produce an executable.
1003 @end enumerate
1005 @noindent
1006 All three steps are most commonly handled by using the @command{gnatmake}
1007 utility program that, given the name of the main program, automatically
1008 performs the necessary compilation, binding and linking steps.
1010 @node Running a Simple Ada Program
1011 @section Running a Simple Ada Program
1013 @noindent
1014 Any text editor may be used to prepare an Ada program.
1015 @ifclear vms
1016 If @code{Glide} is
1017 used, the optional Ada mode may be helpful in laying out the program.
1018 @end ifclear
1020 program text is a normal text file. We will suppose in our initial
1021 example that you have used your editor to prepare the following
1022 standard format text file:
1024 @smallexample @c ada
1025 @cartouche
1026 with Ada.Text_IO; use Ada.Text_IO;
1027 procedure Hello is
1028 begin
1029    Put_Line ("Hello WORLD!");
1030 end Hello;
1031 @end cartouche
1032 @end smallexample
1034 @noindent
1035 This file should be named @file{hello.adb}.
1036 With the normal default file naming conventions, GNAT requires
1037 that each file
1038 contain a single compilation unit whose file name is the
1039 unit name,
1040 with periods replaced by hyphens; the
1041 extension is @file{ads} for a
1042 spec and @file{adb} for a body.
1043 You can override this default file naming convention by use of the
1044 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1045 Alternatively, if you want to rename your files according to this default
1046 convention, which is probably more convenient if you will be using GNAT
1047 for all your compilations, then the @code{gnatchop} utility
1048 can be used to generate correctly-named source files
1049 (@pxref{Renaming Files Using gnatchop}).
1051 You can compile the program using the following command (@code{$} is used
1052 as the command prompt in the examples in this document):
1054 @smallexample
1055 $ gcc -c hello.adb
1056 @end smallexample
1058 @noindent
1059 @command{gcc} is the command used to run the compiler. This compiler is
1060 capable of compiling programs in several languages, including Ada 95 and
1061 C. It assumes that you have given it an Ada program if the file extension is
1062 either @file{.ads} or @file{.adb}, and it will then call
1063 the GNAT compiler to compile the specified file.
1065 @ifclear vms
1066 The @option{-c} switch is required. It tells @command{gcc} to only do a
1067 compilation. (For C programs, @command{gcc} can also do linking, but this
1068 capability is not used directly for Ada programs, so the @option{-c}
1069 switch must always be present.)
1070 @end ifclear
1072 This compile command generates a file
1073 @file{hello.o}, which is the object
1074 file corresponding to your Ada program. It also generates
1075 an ``Ada Library Information'' file @file{hello.ali},
1076 which contains additional information used to check
1077 that an Ada program is consistent.
1078 To build an executable file,
1079 use @code{gnatbind} to bind the program
1080 and @command{gnatlink} to link it. The
1081 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1082 @file{ALI} file, but the default extension of @file{.ali} can
1083 be omitted. This means that in the most common case, the argument
1084 is simply the name of the main program:
1086 @smallexample
1087 $ gnatbind hello
1088 $ gnatlink hello
1089 @end smallexample
1091 @noindent
1092 A simpler method of carrying out these steps is to use
1093 @command{gnatmake},
1094 a master program that invokes all the required
1095 compilation, binding and linking tools in the correct order. In particular,
1096 @command{gnatmake} automatically recompiles any sources that have been
1097 modified since they were last compiled, or sources that depend
1098 on such modified sources, so that ``version skew'' is avoided.
1099 @cindex Version skew (avoided by @command{gnatmake})
1101 @smallexample
1102 $ gnatmake hello.adb
1103 @end smallexample
1105 @noindent
1106 The result is an executable program called @file{hello}, which can be
1107 run by entering:
1109 @smallexample
1110 $ ^hello^RUN HELLO^
1111 @end smallexample
1113 @noindent
1114 assuming that the current directory is on the search path
1115 for executable programs.
1117 @noindent
1118 and, if all has gone well, you will see
1120 @smallexample
1121 Hello WORLD!
1122 @end smallexample
1124 @noindent
1125 appear in response to this command.
1127 @c ****************************************
1128 @node Running a Program with Multiple Units
1129 @section Running a Program with Multiple Units
1131 @noindent
1132 Consider a slightly more complicated example that has three files: a
1133 main program, and the spec and body of a package:
1135 @smallexample @c ada
1136 @cartouche
1137 @group
1138 package Greetings is
1139    procedure Hello;
1140    procedure Goodbye;
1141 end Greetings;
1143 with Ada.Text_IO; use Ada.Text_IO;
1144 package body Greetings is
1145    procedure Hello is
1146    begin
1147       Put_Line ("Hello WORLD!");
1148    end Hello;
1150    procedure Goodbye is
1151    begin
1152       Put_Line ("Goodbye WORLD!");
1153    end Goodbye;
1154 end Greetings;
1155 @end group
1157 @group
1158 with Greetings;
1159 procedure Gmain is
1160 begin
1161    Greetings.Hello;
1162    Greetings.Goodbye;
1163 end Gmain;
1164 @end group
1165 @end cartouche
1166 @end smallexample
1168 @noindent
1169 Following the one-unit-per-file rule, place this program in the
1170 following three separate files:
1172 @table @file
1173 @item greetings.ads
1174 spec of package @code{Greetings}
1176 @item greetings.adb
1177 body of package @code{Greetings}
1179 @item gmain.adb
1180 body of main program
1181 @end table
1183 @noindent
1184 To build an executable version of
1185 this program, we could use four separate steps to compile, bind, and link
1186 the program, as follows:
1188 @smallexample
1189 $ gcc -c gmain.adb
1190 $ gcc -c greetings.adb
1191 $ gnatbind gmain
1192 $ gnatlink gmain
1193 @end smallexample
1195 @noindent
1196 Note that there is no required order of compilation when using GNAT.
1197 In particular it is perfectly fine to compile the main program first.
1198 Also, it is not necessary to compile package specs in the case where
1199 there is an accompanying body; you only need to compile the body. If you want
1200 to submit these files to the compiler for semantic checking and not code
1201 generation, then use the
1202 @option{-gnatc} switch:
1204 @smallexample
1205 $ gcc -c greetings.ads -gnatc
1206 @end smallexample
1208 @noindent
1209 Although the compilation can be done in separate steps as in the
1210 above example, in practice it is almost always more convenient
1211 to use the @command{gnatmake} tool. All you need to know in this case
1212 is the name of the main program's source file. The effect of the above four
1213 commands can be achieved with a single one:
1215 @smallexample
1216 $ gnatmake gmain.adb
1217 @end smallexample
1219 @noindent
1220 In the next section we discuss the advantages of using @command{gnatmake} in
1221 more detail.
1223 @c *****************************
1224 @node Using the gnatmake Utility
1225 @section Using the @command{gnatmake} Utility
1227 @noindent
1228 If you work on a program by compiling single components at a time using
1229 @command{gcc}, you typically keep track of the units you modify. In order to
1230 build a consistent system, you compile not only these units, but also any
1231 units that depend on the units you have modified.
1232 For example, in the preceding case,
1233 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1234 you edit @file{greetings.ads}, you must recompile both
1235 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1236 units that depend on @file{greetings.ads}.
1238 @code{gnatbind} will warn you if you forget one of these compilation
1239 steps, so that it is impossible to generate an inconsistent program as a
1240 result of forgetting to do a compilation. Nevertheless it is tedious and
1241 error-prone to keep track of dependencies among units.
1242 One approach to handle the dependency-bookkeeping is to use a
1243 makefile. However, makefiles present maintenance problems of their own:
1244 if the dependencies change as you change the program, you must make
1245 sure that the makefile is kept up-to-date manually, which is also an
1246 error-prone process.
1248 The @command{gnatmake} utility takes care of these details automatically.
1249 Invoke it using either one of the following forms:
1251 @smallexample
1252 $ gnatmake gmain.adb
1253 $ gnatmake ^gmain^GMAIN^
1254 @end smallexample
1256 @noindent
1257 The argument is the name of the file containing the main program;
1258 you may omit the extension. @command{gnatmake}
1259 examines the environment, automatically recompiles any files that need
1260 recompiling, and binds and links the resulting set of object files,
1261 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1262 In a large program, it
1263 can be extremely helpful to use @command{gnatmake}, because working out by hand
1264 what needs to be recompiled can be difficult.
1266 Note that @command{gnatmake}
1267 takes into account all the Ada 95 rules that
1268 establish dependencies among units. These include dependencies that result
1269 from inlining subprogram bodies, and from
1270 generic instantiation. Unlike some other
1271 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1272 found by the compiler on a previous compilation, which may possibly
1273 be wrong when sources change. @command{gnatmake} determines the exact set of
1274 dependencies from scratch each time it is run.
1276 @ifset vms
1277 @node Editing with Emacs
1278 @section Editing with Emacs
1279 @cindex Emacs
1281 @noindent
1282 Emacs is an extensible self-documenting text editor that is available in a
1283 separate VMSINSTAL kit.
1285 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1286 click on the Emacs Help menu and run the Emacs Tutorial.
1287 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1288 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1290 Documentation on Emacs and other tools is available in Emacs under the
1291 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1292 use the middle mouse button to select a topic (e.g. Emacs).
1294 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1295 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1296 get to the Emacs manual.
1297 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1298 prompt.
1300 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1301 which is sufficiently extensible to provide for a complete programming
1302 environment and shell for the sophisticated user.
1303 @end ifset
1305 @ifclear vms
1306 @node Introduction to GPS
1307 @section Introduction to GPS
1308 @cindex GPS (GNAT Programming System)
1309 @cindex GNAT Programming System (GPS)
1310 @noindent
1311 Although the command line interface (@command{gnatmake}, etc.) alone
1312 is sufficient, a graphical Interactive Development
1313 Environment can make it easier for you to compose, navigate, and debug
1314 programs.  This section describes the main features of GPS
1315 (``GNAT Programming System''), the GNAT graphical IDE.
1316 You will see how to use GPS to build and debug an executable, and
1317 you will also learn some of the basics of the GNAT ``project'' facility.
1319 GPS enables you to do much more than is presented here;
1320 e.g., you can produce a call graph, interface to a third-party
1321 Version Control System, and inspect the generated assembly language
1322 for a program.
1323 Indeed, GPS also supports languages other than Ada.
1324 Such additional information, and an explanation of all of the GPS menu
1325 items. may be found in the on-line help, which includes
1326 a user's guide and a tutorial (these are also accessible from the GNAT
1327 startup menu).
1329 @menu
1330 * Building a New Program with GPS::
1331 * Simple Debugging with GPS::
1332 @end menu
1334 @node Building a New Program with GPS
1335 @subsection Building a New Program with GPS
1336 @noindent
1337 GPS invokes the GNAT compilation tools using information
1338 contained in a @emph{project} (also known as a @emph{project file}):
1339 a collection of properties such
1340 as source directories, identities of main subprograms, tool switches, etc.,
1341 and their associated values.
1342 See @ref{GNAT Project Manager} for details.
1343 In order to run GPS, you will need to either create a new project
1344 or else open an existing one.
1346 This section will explain how you can use GPS to create a project,
1347 to associate Ada source files with a project, and to build and run
1348 programs.
1350 @enumerate
1351 @item @emph{Creating a project}
1353 Invoke GPS, either from the command line or the platform's IDE.
1354 After it starts, GPS will display a ``Welcome'' screen with three
1355 radio buttons:
1357 @itemize @bullet
1358 @item
1359 @code{Start with default project in directory}
1361 @item
1362 @code{Create new project with wizard}
1364 @item
1365 @code{Open existing project}
1366 @end itemize
1368 @noindent
1369 Select @code{Create new project with wizard} and press @code{OK}.
1370 A new window will appear.  In the text box labeled with
1371 @code{Enter the name of the project to create}, type @file{sample}
1372 as the project name.
1373 In the next box, browse to choose the directory in which you
1374 would like to create the project file.
1375 After selecting an appropriate directory, press @code{Forward}.
1377 A window will appear with the title
1378 @code{Version Control System Configuration}.
1379 Simply press @code{Forward}.
1381 A window will appear with the title
1382 @code{Please select the source directories for this project}.
1383 The directory that you specified for the project file will be selected
1384 by default as the one to use for sources; simply press @code{Forward}.
1386 A window will appear with the title
1387 @code{Please select the build directory for this project}.
1388 The directory that you specified for the project file will be selected
1389 by default for object files and executables;
1390 simply press @code{Forward}.
1392 A window will appear with the title
1393 @code{Please select the main units for this project}.
1394 You will supply this information later, after creating the source file.
1395 Simply press @code{Forward} for now.
1397 A window will appear with the title
1398 @code{Please select the switches to build the project}.
1399 Press @code{Apply}.  This will create a project file named
1400 @file{sample.prj} in the directory that you had specified.
1402 @item @emph{Creating and saving the source file}
1404 After you create the new project, a GPS window will appear, which is
1405 partitioned into two main sections:
1407 @itemize @bullet
1408 @item
1409 A @emph{Workspace area}, initially greyed out, which you will use for
1410 creating and editing source files
1412 @item
1413 Directly below, a @emph{Messages area}, which initially displays a
1414 ``Welcome'' message.
1415 (If the Messages area is not visible, drag its border upward to expand it.)
1416 @end itemize
1418 @noindent
1419 Select @code{File} on the menu bar, and then the @code{New} command.
1420 The Workspace area will become white, and you can now
1421 enter the source program explicitly.
1422 Type the following text
1424 @smallexample @c ada
1425 @group
1426 with Ada.Text_IO; use Ada.Text_IO;
1427 procedure Hello is
1428 begin
1429   Put_Line("Hello from GPS!");
1430 end Hello;
1431 @end group
1432 @end smallexample
1434 @noindent
1435 Select @code{File}, then @code{Save As}, and enter the source file name
1436 @file{hello.adb}.
1437 The file will be saved in the same directory you specified as the
1438 location of the default project file.
1440 @item @emph{Updating the project file}
1442 You need to add the new source file to the project.
1443 To do this, select
1444 the @code{Project} menu and then @code{Edit project properties}.
1445 Click the @code{Main files} tab on the left, and then the
1446 @code{Add} button.
1447 Choose @file{hello.adb} from the list, and press @code{Open}.
1448 The project settings window will reflect this action.
1449 Click @code{OK}.
1451 @item @emph{Building and running the program}
1453 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1454 and select @file{hello.adb}.
1455 The Messages window will display the resulting invocations of @command{gcc},
1456 @command{gnatbind}, and @command{gnatlink}
1457 (reflecting the default switch settings from the
1458 project file that you created) and then a ``successful compilation/build''
1459 message.
1461 To run the program, choose the @code{Build} menu, then @code{Run}, and
1462 select @command{hello}.
1463 An @emph{Arguments Selection} window will appear.
1464 There are no command line arguments, so just click @code{OK}.
1466 The Messages window will now display the program's output (the string
1467 @code{Hello from GPS}), and at the bottom of the GPS window a status
1468 update is displayed (@code{Run: hello}).
1469 Close the GPS window (or select @code{File}, then @code{Exit}) to
1470 terminate this GPS session.
1471 @end enumerate
1473 @node Simple Debugging with GPS
1474 @subsection Simple Debugging with GPS
1475 @noindent
1476 This section illustrates basic debugging techniques (setting breakpoints,
1477 examining/modifying variables, single stepping).
1479 @enumerate
1480 @item @emph{Opening a project}
1482 Start GPS and select @code{Open existing project}; browse to
1483 specify the project file @file{sample.prj} that you had created in the
1484 earlier example.
1486 @item @emph{Creating a source file}
1488 Select @code{File}, then @code{New}, and type in the following program:
1490 @smallexample @c ada
1491 @group
1492 with Ada.Text_IO; use Ada.Text_IO;
1493 procedure Example is
1494    Line : String (1..80);
1495    N    : Natural;
1496 begin
1497    Put_Line("Type a line of text at each prompt; an empty line to exit");
1498    loop
1499       Put(": ");
1500       Get_Line (Line, N);
1501       Put_Line (Line (1..N) );
1502       exit when N=0;
1503    end loop;
1504 end Example;
1505 @end group
1506 @end smallexample
1508 @noindent
1509 Select @code{File}, then @code{Save as}, and enter the file name
1510 @file{example.adb}.
1512 @item @emph{Updating the project file}
1514 Add @code{Example} as a new main unit for the project:
1515 @enumerate a
1516 @item
1517 Select @code{Project}, then @code{Edit Project Properties}.
1519 @item
1520 Select the @code{Main files} tab, click @code{Add}, then
1521 select the file @file{example.adb} from the list, and
1522 click @code{Open}.
1523 You will see the file name appear in the list of main units
1525 @item
1526 Click @code{OK}
1527 @end enumerate
1529 @item @emph{Building/running the executable}
1531 To build the executable
1532 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1534 Run the program to see its effect (in the Messages area).
1535 Each line that you enter is displayed; an empty line will
1536 cause the loop to exit and the program to terminate.
1538 @item @emph{Debugging the program}
1540 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1541 which are required for debugging, are on by default when you create
1542 a new project.
1543 Thus unless you intentionally remove these settings, you will be able
1544 to debug any program that you develop using GPS.
1546 @enumerate a
1547 @item @emph{Initializing}
1549 Select @code{Debug}, then @code{Initialize}, then @file{example}
1551 @item @emph{Setting a breakpoint}
1553 After performing the initialization step, you will observe a small
1554 icon to the right of each line number.
1555 This serves as a toggle for breakpoints; clicking the icon will
1556 set a breakpoint at the corresponding line (the icon will change to
1557 a red circle with an ``x''), and clicking it again
1558 will remove the breakpoint / reset the icon.
1560 For purposes of this example, set a breakpoint at line 10 (the
1561 statement @code{Put_Line@ (Line@ (1..N));}
1563 @item @emph{Starting program execution}
1565 Select @code{Debug}, then @code{Run}.  When the
1566 @code{Program Arguments} window appears, click @code{OK}.
1567 A console window will appear; enter some line of text,
1568 e.g. @code{abcde}, at the prompt.
1569 The program will pause execution when it gets to the
1570 breakpoint, and the corresponding line is highlighted.
1572 @item @emph{Examining a variable}
1574 Move the mouse over one of the occurrences of the variable @code{N}.
1575 You will see the value (5) displayed, in ``tool tip'' fashion.
1576 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1577 You will see information about @code{N} appear in the @code{Debugger Data}
1578 pane, showing the value as 5.
1580 @item @emph{Assigning a new value to a variable}
1582 Right click on the @code{N} in the @code{Debugger Data} pane, and
1583 select @code{Set value of N}.
1584 When the input window appears, enter the value @code{4} and click
1585 @code{OK}.
1586 This value does not automatically appear in the @code{Debugger Data}
1587 pane; to see it, right click again on the @code{N} in the
1588 @code{Debugger Data} pane and select @code{Update value}.
1589 The new value, 4, will appear in red.
1591 @item @emph{Single stepping}
1593 Select @code{Debug}, then @code{Next}.
1594 This will cause the next statement to be executed, in this case the
1595 call of @code{Put_Line} with the string slice.
1596 Notice in the console window that the displayed string is simply
1597 @code{abcd} and not @code{abcde} which you had entered.
1598 This is because the upper bound of the slice is now 4 rather than 5.
1600 @item @emph{Removing a breakpoint}
1602 Toggle the breakpoint icon at line 10.
1604 @item @emph{Resuming execution from a breakpoint}
1606 Select @code{Debug}, then @code{Continue}.
1607 The program will reach the next iteration of the loop, and
1608 wait for input after displaying the prompt.
1609 This time, just hit the @kbd{Enter} key.
1610 The value of @code{N} will be 0, and the program will terminate.
1611 The console window will disappear.
1612 @end enumerate
1613 @end enumerate
1615 @node Introduction to Glide and GVD
1616 @section Introduction to Glide and GVD
1617 @cindex Glide
1618 @cindex GVD
1619 @noindent
1620 This section describes the main features of Glide,
1621 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1622 the GNU Visual Debugger.
1623 These tools may be present in addition to, or in place of, GPS on some
1624 platforms.
1625 Additional information on Glide and GVD may be found
1626 in the on-line help for these tools.
1628 @menu
1629 * Building a New Program with Glide::
1630 * Simple Debugging with GVD::
1631 * Other Glide Features::
1632 @end menu
1634 @node Building a New Program with Glide
1635 @subsection Building a New Program with Glide
1636 @noindent
1637 The simplest way to invoke Glide is to enter @command{glide}
1638 at the command prompt.  It will generally be useful to issue this
1639 as a background command, thus allowing you to continue using
1640 your command window for other purposes while Glide is running:
1642 @smallexample
1643 $ glide&
1644 @end smallexample
1646 @noindent
1647 Glide will start up with an initial screen displaying the top-level menu items
1648 as well as some other information.  The menu selections are as follows
1649 @itemize @bullet
1650 @item @code{Buffers}
1651 @item @code{Files}
1652 @item @code{Tools}
1653 @item @code{Edit}
1654 @item @code{Search}
1655 @item @code{Mule}
1656 @item @code{Glide}
1657 @item @code{Help}
1658 @end itemize
1660 @noindent
1661 For this introductory example, you will need to create a new Ada source file.
1662 First, select the @code{Files} menu.  This will pop open a menu with around
1663 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1664 Depending on the platform, you may see a pop-up window where you can browse
1665 to an appropriate directory and then enter the file name, or else simply
1666 see a line at the bottom of the Glide window where you can likewise enter
1667 the file name.  Note that in Glide, when you attempt to open a non-existent
1668 file, the effect is to create a file with that name.  For this example enter
1669 @file{hello.adb} as the name of the file.
1671 A new buffer will now appear, occupying the entire Glide window,
1672 with the file name at the top.  The menu selections are slightly different
1673 from the ones you saw on the opening screen; there is an @code{Entities} item,
1674 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1675 the file extension to identify the source language, so @file{adb} indicates
1676 an Ada source file.
1678 You will enter some of the source program lines explicitly,
1679 and use the syntax-oriented template mechanism to enter other lines.
1680 First, type the following text:
1681 @smallexample
1682 with Ada.Text_IO; use Ada.Text_IO;
1683 procedure Hello is
1684 begin
1685 @end smallexample
1687 @noindent
1688 Observe that Glide uses different colors to distinguish reserved words from
1689 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1690 automatically indented in anticipation of declarations.  When you enter
1691 @code{begin}, Glide recognizes that there are no declarations and thus places
1692 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1693 indented, where the statement(s) will be placed.
1695 The main part of the program will be a @code{for} loop.  Instead of entering
1696 the text explicitly, however, use a statement template.  Select the @code{Ada}
1697 item on the top menu bar, move the mouse to the @code{Statements} item,
1698 and you will see a large selection of alternatives.  Choose @code{for loop}.
1699 You will be prompted (at the bottom of the buffer) for a loop name;
1700 simply press the @key{Enter} key since a loop name is not needed.
1701 You should see the beginning of a @code{for} loop appear in the source
1702 program window.  You will now be prompted for the name of the loop variable;
1703 enter a line with the identifier @code{ind} (lower case).  Note that,
1704 by default, Glide capitalizes the name (you can override such behavior
1705 if you wish, although this is outside the scope of this introduction).
1706 Next, Glide prompts you for the loop range; enter a line containing
1707 @code{1..5} and you will see this also appear in the source program,
1708 together with the remaining elements of the @code{for} loop syntax.
1710 Next enter the statement (with an intentional error, a missing semicolon)
1711 that will form the body of the loop:
1712 @smallexample
1713 Put_Line("Hello, World" & Integer'Image(I))
1714 @end smallexample
1716 @noindent
1717 Finally, type @code{end Hello;} as the last line in the program.
1718 Now save the file: choose the @code{File} menu item, and then the
1719 @code{Save buffer} selection.  You will see a message at the bottom
1720 of the buffer confirming that the file has been saved.
1722 You are now ready to attempt to build the program.  Select the @code{Ada}
1723 item from the top menu bar.  Although we could choose simply to compile
1724 the file, we will instead attempt to do a build (which invokes
1725 @command{gnatmake}) since, if the compile is successful, we want to build
1726 an executable.  Thus select @code{Ada build}.  This will fail because of the
1727 compilation error, and you will notice that the Glide window has been split:
1728 the top window contains the source file, and the bottom window contains the
1729 output from the GNAT tools. Glide allows you to navigate from a compilation
1730 error to the source file position corresponding to the error: click the
1731 middle mouse button (or simultaneously press the left and right buttons,
1732 on a two-button mouse) on the diagnostic line in the tool window.  The
1733 focus will shift to the source window, and the cursor will be positioned
1734 on the character at which the error was detected.
1736 Correct the error: type in a semicolon to terminate the statement.
1737 Although you can again save the file explicitly, you can also simply invoke
1738 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1739 This time the build will succeed; the tool output window shows you the
1740 options that are supplied by default.  The GNAT tools' output (e.g.
1741 object and ALI files, executable) will go in the directory from which
1742 Glide was launched.
1744 To execute the program, choose @code{Ada} and then @code{Run}.
1745 You should see the program's output displayed in the bottom window:
1747 @smallexample
1748 Hello, world 1
1749 Hello, world 2
1750 Hello, world 3
1751 Hello, world 4
1752 Hello, world 5
1753 @end smallexample
1755 @node Simple Debugging with GVD
1756 @subsection Simple Debugging with GVD
1758 @noindent
1759 This section describes how to set breakpoints, examine/modify variables,
1760 and step through execution.
1762 In order to enable debugging, you need to pass the @option{-g} switch
1763 to both the compiler and to @command{gnatlink}.  If you are using
1764 the command line, passing @option{-g} to @command{gnatmake} will have
1765 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1766 by issuing the command:
1768 @smallexample
1769 $ gvd hello
1770 @end smallexample
1772 @noindent
1773 If you are using Glide, then @option{-g} is passed to the relevant tools
1774 by default when you do a build.  Start the debugger by selecting the
1775 @code{Ada} menu item, and then @code{Debug}.
1777 GVD comes up in a multi-part window.  One pane shows the names of files
1778 comprising your executable; another pane shows the source code of the current
1779 unit (initially your main subprogram), another pane shows the debugger output
1780 and user interactions, and the fourth pane (the data canvas at the top
1781 of the window) displays data objects that you have selected.
1783 To the left of the source file pane, you will notice green dots adjacent
1784 to some lines.  These are lines for which object code exists and where
1785 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1786 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1787 in a red circle.  Clicking the circle toggles the breakpoint off,
1788 and the red circle is replaced by the green dot.
1790 For this example, set a breakpoint at the statement where @code{Put_Line}
1791 is invoked.
1793 Start program execution by selecting the @code{Run} button on the top menu bar.
1794 (The @code{Start} button will also start your program, but it will
1795 cause program execution to break at the entry to your main subprogram.)
1796 Evidence of reaching the breakpoint will appear: the source file line will be
1797 highlighted, and the debugger interactions pane will display
1798 a relevant message.
1800 You can examine the values of variables in several ways.  Move the mouse
1801 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1802 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1803 and select @code{Display Ind}; a box showing the variable's name and value
1804 will appear in the data canvas.
1806 Although a loop index is a constant with respect to Ada semantics,
1807 you can change its value in the debugger.  Right-click in the box
1808 for @code{Ind}, and select the @code{Set Value of Ind} item.
1809 Enter @code{2} as the new value, and press @command{OK}.
1810 The box for @code{Ind} shows the update.
1812 Press the @code{Step} button on the top menu bar; this will step through
1813 one line of program text (the invocation of @code{Put_Line}), and you can
1814 observe the effect of having modified @code{Ind} since the value displayed
1815 is @code{2}.
1817 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1818 button.  You will see the remaining output lines displayed in the debugger
1819 interaction window, along with a message confirming normal program
1820 termination.
1822 @node Other Glide Features
1823 @subsection Other Glide Features
1825 @noindent
1826 You may have observed that some of the menu selections contain abbreviations;
1827 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1828 These are @emph{shortcut keys} that you can use instead of selecting
1829 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1830 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1831 of selecting @code{Files} and then @code{Open file...}.
1833 To abort a Glide command, type @key{Ctrl-g}.
1835 If you want Glide to start with an existing source file, you can either
1836 launch Glide as above and then open the file via @code{Files} @result{}
1837 @code{Open file...}, or else simply pass the name of the source file
1838 on the command line:
1840 @smallexample
1841 $ glide hello.adb&
1842 @end smallexample
1844 @noindent
1845 While you are using Glide, a number of @emph{buffers} exist.
1846 You create some explicitly; e.g., when you open/create a file.
1847 Others arise as an effect of the commands that you issue; e.g., the buffer
1848 containing the output of the tools invoked during a build.  If a buffer
1849 is hidden, you can bring it into a visible window by first opening
1850 the @code{Buffers} menu and then selecting the desired entry.
1852 If a buffer occupies only part of the Glide screen and you want to expand it
1853 to fill the entire screen, then click in the buffer and then select
1854 @code{Files} @result{} @code{One Window}.
1856 If a window is occupied by one buffer and you want to split the window
1857 to bring up a second buffer, perform the following steps:
1858 @itemize @bullet
1859 @item Select @code{Files} @result{} @code{Split Window};
1860 this will produce two windows each of which holds the original buffer
1861 (these are not copies, but rather different views of the same buffer contents)
1863 @item With the focus in one of the windows,
1864 select the desired buffer from the @code{Buffers} menu
1865 @end itemize
1867 @noindent
1868 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1869 @end ifclear
1871 @node The GNAT Compilation Model
1872 @chapter The GNAT Compilation Model
1873 @cindex GNAT compilation model
1874 @cindex Compilation model
1876 @menu
1877 * Source Representation::
1878 * Foreign Language Representation::
1879 * File Naming Rules::
1880 * Using Other File Names::
1881 * Alternative File Naming Schemes::
1882 * Generating Object Files::
1883 * Source Dependencies::
1884 * The Ada Library Information Files::
1885 * Binding an Ada Program::
1886 * Mixed Language Programming::
1887 * Building Mixed Ada & C++ Programs::
1888 * Comparison between GNAT and C/C++ Compilation Models::
1889 * Comparison between GNAT and Conventional Ada Library Models::
1890 @ifset vms
1891 * Placement of temporary files::
1892 @end ifset
1893 @end menu
1895 @noindent
1896 This chapter describes the compilation model used by GNAT. Although
1897 similar to that used by other languages, such as C and C++, this model
1898 is substantially different from the traditional Ada compilation models,
1899 which are based on a library. The model is initially described without
1900 reference to the library-based model. If you have not previously used an
1901 Ada compiler, you need only read the first part of this chapter. The
1902 last section describes and discusses the differences between the GNAT
1903 model and the traditional Ada compiler models. If you have used other
1904 Ada compilers, this section will help you to understand those
1905 differences, and the advantages of the GNAT model.
1907 @node Source Representation
1908 @section Source Representation
1909 @cindex Latin-1
1911 @noindent
1912 Ada source programs are represented in standard text files, using
1913 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1914 7-bit ASCII set, plus additional characters used for
1915 representing foreign languages (@pxref{Foreign Language Representation}
1916 for support of non-USA character sets). The format effector characters
1917 are represented using their standard ASCII encodings, as follows:
1919 @table @code
1920 @item VT
1921 @findex VT
1922 Vertical tab, @code{16#0B#}
1924 @item HT
1925 @findex HT
1926 Horizontal tab, @code{16#09#}
1928 @item CR
1929 @findex CR
1930 Carriage return, @code{16#0D#}
1932 @item LF
1933 @findex LF
1934 Line feed, @code{16#0A#}
1936 @item FF
1937 @findex FF
1938 Form feed, @code{16#0C#}
1939 @end table
1941 @noindent
1942 Source files are in standard text file format. In addition, GNAT will
1943 recognize a wide variety of stream formats, in which the end of
1944 physical lines is marked by any of the following sequences:
1945 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1946 in accommodating files that are imported from other operating systems.
1948 @cindex End of source file
1949 @cindex Source file, end
1950 @findex SUB
1951 The end of a source file is normally represented by the physical end of
1952 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1953 recognized as signalling the end of the source file. Again, this is
1954 provided for compatibility with other operating systems where this
1955 code is used to represent the end of file.
1957 Each file contains a single Ada compilation unit, including any pragmas
1958 associated with the unit. For example, this means you must place a
1959 package declaration (a package @dfn{spec}) and the corresponding body in
1960 separate files. An Ada @dfn{compilation} (which is a sequence of
1961 compilation units) is represented using a sequence of files. Similarly,
1962 you will place each subunit or child unit in a separate file.
1964 @node Foreign Language Representation
1965 @section Foreign Language Representation
1967 @noindent
1968 GNAT supports the standard character sets defined in Ada 95 as well as
1969 several other non-standard character sets for use in localized versions
1970 of the compiler (@pxref{Character Set Control}).
1971 @menu
1972 * Latin-1::
1973 * Other 8-Bit Codes::
1974 * Wide Character Encodings::
1975 @end menu
1977 @node Latin-1
1978 @subsection Latin-1
1979 @cindex Latin-1
1981 @noindent
1982 The basic character set is Latin-1. This character set is defined by ISO
1983 standard 8859, part 1. The lower half (character codes @code{16#00#}
1984 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1985 is used to represent additional characters. These include extended letters
1986 used by European languages, such as French accents, the vowels with umlauts
1987 used in German, and the extra letter A-ring used in Swedish.
1989 @findex Ada.Characters.Latin_1
1990 For a complete list of Latin-1 codes and their encodings, see the source
1991 file of library unit @code{Ada.Characters.Latin_1} in file
1992 @file{a-chlat1.ads}.
1993 You may use any of these extended characters freely in character or
1994 string literals. In addition, the extended characters that represent
1995 letters can be used in identifiers.
1997 @node Other 8-Bit Codes
1998 @subsection Other 8-Bit Codes
2000 @noindent
2001 GNAT also supports several other 8-bit coding schemes:
2003 @table @asis
2004 @item ISO 8859-2 (Latin-2)
2005 @cindex Latin-2
2006 @cindex ISO 8859-2
2007 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2008 equivalence.
2010 @item ISO 8859-3 (Latin-3)
2011 @cindex Latin-3
2012 @cindex ISO 8859-3
2013 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2014 equivalence.
2016 @item ISO 8859-4 (Latin-4)
2017 @cindex Latin-4
2018 @cindex ISO 8859-4
2019 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2020 equivalence.
2022 @item ISO 8859-5 (Cyrillic)
2023 @cindex ISO 8859-5
2024 @cindex Cyrillic
2025 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2026 lowercase equivalence.
2028 @item ISO 8859-15 (Latin-9)
2029 @cindex ISO 8859-15
2030 @cindex Latin-9
2031 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2032 lowercase equivalence
2034 @item IBM PC (code page 437)
2035 @cindex code page 437
2036 This code page is the normal default for PCs in the U.S. It corresponds
2037 to the original IBM PC character set. This set has some, but not all, of
2038 the extended Latin-1 letters, but these letters do not have the same
2039 encoding as Latin-1. In this mode, these letters are allowed in
2040 identifiers with uppercase and lowercase equivalence.
2042 @item IBM PC (code page 850)
2043 @cindex code page 850
2044 This code page is a modification of 437 extended to include all the
2045 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2046 mode, all these letters are allowed in identifiers with uppercase and
2047 lowercase equivalence.
2049 @item Full Upper 8-bit
2050 Any character in the range 80-FF allowed in identifiers, and all are
2051 considered distinct. In other words, there are no uppercase and lowercase
2052 equivalences in this range. This is useful in conjunction with
2053 certain encoding schemes used for some foreign character sets (e.g.
2054 the typical method of representing Chinese characters on the PC).
2056 @item No Upper-Half
2057 No upper-half characters in the range 80-FF are allowed in identifiers.
2058 This gives Ada 83 compatibility for identifier names.
2059 @end table
2061 @noindent
2062 For precise data on the encodings permitted, and the uppercase and lowercase
2063 equivalences that are recognized, see the file @file{csets.adb} in
2064 the GNAT compiler sources. You will need to obtain a full source release
2065 of GNAT to obtain this file.
2067 @node Wide Character Encodings
2068 @subsection Wide Character Encodings
2070 @noindent
2071 GNAT allows wide character codes to appear in character and string
2072 literals, and also optionally in identifiers, by means of the following
2073 possible encoding schemes:
2075 @table @asis
2077 @item Hex Coding
2078 In this encoding, a wide character is represented by the following five
2079 character sequence:
2081 @smallexample
2082 ESC a b c d
2083 @end smallexample
2085 @noindent
2086 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2087 characters (using uppercase letters) of the wide character code. For
2088 example, ESC A345 is used to represent the wide character with code
2089 @code{16#A345#}.
2090 This scheme is compatible with use of the full Wide_Character set.
2092 @item Upper-Half Coding
2093 @cindex Upper-Half Coding
2094 The wide character with encoding @code{16#abcd#} where the upper bit is on
2095 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2096 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2097 character, but is not required to be in the upper half. This method can
2098 be also used for shift-JIS or EUC, where the internal coding matches the
2099 external coding.
2101 @item Shift JIS Coding
2102 @cindex Shift JIS Coding
2103 A wide character is represented by a two-character sequence,
2104 @code{16#ab#} and
2105 @code{16#cd#}, with the restrictions described for upper-half encoding as
2106 described above. The internal character code is the corresponding JIS
2107 character according to the standard algorithm for Shift-JIS
2108 conversion. Only characters defined in the JIS code set table can be
2109 used with this encoding method.
2111 @item EUC Coding
2112 @cindex EUC Coding
2113 A wide character is represented by a two-character sequence
2114 @code{16#ab#} and
2115 @code{16#cd#}, with both characters being in the upper half. The internal
2116 character code is the corresponding JIS character according to the EUC
2117 encoding algorithm. Only characters defined in the JIS code set table
2118 can be used with this encoding method.
2120 @item UTF-8 Coding
2121 A wide character is represented using
2122 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2123 10646-1/Am.2. Depending on the character value, the representation
2124 is a one, two, or three byte sequence:
2125 @smallexample
2126 @iftex
2127 @leftskip=.7cm
2128 @end iftex
2129 16#0000#-16#007f#: 2#0xxxxxxx#
2130 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2131 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2133 @end smallexample
2135 @noindent
2136 where the xxx bits correspond to the left-padded bits of the
2137 16-bit character value. Note that all lower half ASCII characters
2138 are represented as ASCII bytes and all upper half characters and
2139 other wide characters are represented as sequences of upper-half
2140 (The full UTF-8 scheme allows for encoding 31-bit characters as
2141 6-byte sequences, but in this implementation, all UTF-8 sequences
2142 of four or more bytes length will be treated as illegal).
2143 @item Brackets Coding
2144 In this encoding, a wide character is represented by the following eight
2145 character sequence:
2147 @smallexample
2148 [ " a b c d " ]
2149 @end smallexample
2151 @noindent
2152 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2153 characters (using uppercase letters) of the wide character code. For
2154 example, [``A345''] is used to represent the wide character with code
2155 @code{16#A345#}. It is also possible (though not required) to use the
2156 Brackets coding for upper half characters. For example, the code
2157 @code{16#A3#} can be represented as @code{[``A3'']}.
2159 This scheme is compatible with use of the full Wide_Character set,
2160 and is also the method used for wide character encoding in the standard
2161 ACVC (Ada Compiler Validation Capability) test suite distributions.
2163 @end table
2165 @noindent
2166 Note: Some of these coding schemes do not permit the full use of the
2167 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2168 use of the upper half of the Latin-1 set.
2170 @node File Naming Rules
2171 @section File Naming Rules
2173 @noindent
2174 The default file name is determined by the name of the unit that the
2175 file contains. The name is formed by taking the full expanded name of
2176 the unit and replacing the separating dots with hyphens and using
2177 ^lowercase^uppercase^ for all letters.
2179 An exception arises if the file name generated by the above rules starts
2180 with one of the characters
2181 @ifset vms
2182 A,G,I, or S,
2183 @end ifset
2184 @ifclear vms
2185 a,g,i, or s,
2186 @end ifclear
2187 and the second character is a
2188 minus. In this case, the character ^tilde^dollar sign^ is used in place
2189 of the minus. The reason for this special rule is to avoid clashes with
2190 the standard names for child units of the packages System, Ada,
2191 Interfaces, and GNAT, which use the prefixes
2192 @ifset vms
2193 S- A- I- and G-
2194 @end ifset
2195 @ifclear vms
2196 s- a- i- and g-
2197 @end ifclear
2198 respectively.
2200 The file extension is @file{.ads} for a spec and
2201 @file{.adb} for a body. The following list shows some
2202 examples of these rules.
2204 @table @file
2205 @item main.ads
2206 Main (spec)
2207 @item main.adb
2208 Main (body)
2209 @item arith_functions.ads
2210 Arith_Functions (package spec)
2211 @item arith_functions.adb
2212 Arith_Functions (package body)
2213 @item func-spec.ads
2214 Func.Spec (child package spec)
2215 @item func-spec.adb
2216 Func.Spec (child package body)
2217 @item main-sub.adb
2218 Sub (subunit of Main)
2219 @item ^a~bad.adb^A$BAD.ADB^
2220 A.Bad (child package body)
2221 @end table
2223 @noindent
2224 Following these rules can result in excessively long
2225 file names if corresponding
2226 unit names are long (for example, if child units or subunits are
2227 heavily nested). An option is available to shorten such long file names
2228 (called file name ``krunching''). This may be particularly useful when
2229 programs being developed with GNAT are to be used on operating systems
2230 with limited file name lengths. @xref{Using gnatkr}.
2232 Of course, no file shortening algorithm can guarantee uniqueness over
2233 all possible unit names; if file name krunching is used, it is your
2234 responsibility to ensure no name clashes occur. Alternatively you
2235 can specify the exact file names that you want used, as described
2236 in the next section. Finally, if your Ada programs are migrating from a
2237 compiler with a different naming convention, you can use the gnatchop
2238 utility to produce source files that follow the GNAT naming conventions.
2239 (For details @pxref{Renaming Files Using gnatchop}.)
2241 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2242 systems, case is not significant. So for example on @code{Windows XP}
2243 if the canonical name is @code{main-sub.adb}, you can use the file name
2244 @code{Main-Sub.adb} instead. However, case is significant for other
2245 operating systems, so for example, if you want to use other than
2246 canonically cased file names on a Unix system, you need to follow
2247 the procedures described in the next section.
2249 @node Using Other File Names
2250 @section Using Other File Names
2251 @cindex File names
2253 @noindent
2254 In the previous section, we have described the default rules used by
2255 GNAT to determine the file name in which a given unit resides. It is
2256 often convenient to follow these default rules, and if you follow them,
2257 the compiler knows without being explicitly told where to find all
2258 the files it needs.
2260 However, in some cases, particularly when a program is imported from
2261 another Ada compiler environment, it may be more convenient for the
2262 programmer to specify which file names contain which units. GNAT allows
2263 arbitrary file names to be used by means of the Source_File_Name pragma.
2264 The form of this pragma is as shown in the following examples:
2265 @cindex Source_File_Name pragma
2267 @smallexample @c ada
2268 @cartouche
2269 pragma Source_File_Name (My_Utilities.Stacks,
2270   Spec_File_Name => "myutilst_a.ada");
2271 pragma Source_File_name (My_Utilities.Stacks,
2272   Body_File_Name => "myutilst.ada");
2273 @end cartouche
2274 @end smallexample
2276 @noindent
2277 As shown in this example, the first argument for the pragma is the unit
2278 name (in this example a child unit). The second argument has the form
2279 of a named association. The identifier
2280 indicates whether the file name is for a spec or a body;
2281 the file name itself is given by a string literal.
2283 The source file name pragma is a configuration pragma, which means that
2284 normally it will be placed in the @file{gnat.adc}
2285 file used to hold configuration
2286 pragmas that apply to a complete compilation environment.
2287 For more details on how the @file{gnat.adc} file is created and used
2288 see @ref{Handling of Configuration Pragmas}.
2289 @cindex @file{gnat.adc}
2291 @ifclear vms
2292 GNAT allows completely arbitrary file names to be specified using the
2293 source file name pragma. However, if the file name specified has an
2294 extension other than @file{.ads} or @file{.adb} it is necessary to use
2295 a special syntax when compiling the file. The name in this case must be
2296 preceded by the special sequence @code{-x} followed by a space and the name
2297 of the language, here @code{ada}, as in:
2299 @smallexample
2300 $ gcc -c -x ada peculiar_file_name.sim
2301 @end smallexample
2302 @end ifclear
2304 @noindent
2305 @command{gnatmake} handles non-standard file names in the usual manner (the
2306 non-standard file name for the main program is simply used as the
2307 argument to gnatmake). Note that if the extension is also non-standard,
2308 then it must be included in the gnatmake command, it may not be omitted.
2310 @node Alternative File Naming Schemes
2311 @section Alternative File Naming Schemes
2312 @cindex File naming schemes, alternative
2313 @cindex File names
2315 In the previous section, we described the use of the @code{Source_File_Name}
2316 pragma to allow arbitrary names to be assigned to individual source files.
2317 However, this approach requires one pragma for each file, and especially in
2318 large systems can result in very long @file{gnat.adc} files, and also create
2319 a maintenance problem.
2321 GNAT also provides a facility for specifying systematic file naming schemes
2322 other than the standard default naming scheme previously described. An
2323 alternative scheme for naming is specified by the use of
2324 @code{Source_File_Name} pragmas having the following format:
2325 @cindex Source_File_Name pragma
2327 @smallexample @c ada
2328 pragma Source_File_Name (
2329    Spec_File_Name  => FILE_NAME_PATTERN
2330  [,Casing          => CASING_SPEC]
2331  [,Dot_Replacement => STRING_LITERAL]);
2333 pragma Source_File_Name (
2334    Body_File_Name  => FILE_NAME_PATTERN
2335  [,Casing          => CASING_SPEC]
2336  [,Dot_Replacement => STRING_LITERAL]);
2338 pragma Source_File_Name (
2339    Subunit_File_Name  => FILE_NAME_PATTERN
2340  [,Casing             => CASING_SPEC]
2341  [,Dot_Replacement    => STRING_LITERAL]);
2343 FILE_NAME_PATTERN ::= STRING_LITERAL
2344 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2345 @end smallexample
2347 @noindent
2348 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2349 It contains a single asterisk character, and the unit name is substituted
2350 systematically for this asterisk. The optional parameter
2351 @code{Casing} indicates
2352 whether the unit name is to be all upper-case letters, all lower-case letters,
2353 or mixed-case. If no
2354 @code{Casing} parameter is used, then the default is all
2355 ^lower-case^upper-case^.
2357 The optional @code{Dot_Replacement} string is used to replace any periods
2358 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2359 argument is used then separating dots appear unchanged in the resulting
2360 file name.
2361 Although the above syntax indicates that the
2362 @code{Casing} argument must appear
2363 before the @code{Dot_Replacement} argument, but it
2364 is also permissible to write these arguments in the opposite order.
2366 As indicated, it is possible to specify different naming schemes for
2367 bodies, specs, and subunits. Quite often the rule for subunits is the
2368 same as the rule for bodies, in which case, there is no need to give
2369 a separate @code{Subunit_File_Name} rule, and in this case the
2370 @code{Body_File_name} rule is used for subunits as well.
2372 The separate rule for subunits can also be used to implement the rather
2373 unusual case of a compilation environment (e.g. a single directory) which
2374 contains a subunit and a child unit with the same unit name. Although
2375 both units cannot appear in the same partition, the Ada Reference Manual
2376 allows (but does not require) the possibility of the two units coexisting
2377 in the same environment.
2379 The file name translation works in the following steps:
2381 @itemize @bullet
2383 @item
2384 If there is a specific @code{Source_File_Name} pragma for the given unit,
2385 then this is always used, and any general pattern rules are ignored.
2387 @item
2388 If there is a pattern type @code{Source_File_Name} pragma that applies to
2389 the unit, then the resulting file name will be used if the file exists. If
2390 more than one pattern matches, the latest one will be tried first, and the
2391 first attempt resulting in a reference to a file that exists will be used.
2393 @item
2394 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2395 for which the corresponding file exists, then the standard GNAT default
2396 naming rules are used.
2398 @end itemize
2400 @noindent
2401 As an example of the use of this mechanism, consider a commonly used scheme
2402 in which file names are all lower case, with separating periods copied
2403 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2404 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2405 two pragmas appear:
2407 @smallexample @c ada
2408 pragma Source_File_Name
2409   (Spec_File_Name => "*.1.ada");
2410 pragma Source_File_Name
2411   (Body_File_Name => "*.2.ada");
2412 @end smallexample
2414 @noindent
2415 The default GNAT scheme is actually implemented by providing the following
2416 default pragmas internally:
2418 @smallexample @c ada
2419 pragma Source_File_Name
2420   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2421 pragma Source_File_Name
2422   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2423 @end smallexample
2425 @noindent
2426 Our final example implements a scheme typically used with one of the
2427 Ada 83 compilers, where the separator character for subunits was ``__''
2428 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2429 by adding @file{.ADA}, and subunits by
2430 adding @file{.SEP}. All file names were
2431 upper case. Child units were not present of course since this was an
2432 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2433 the same double underscore separator for child units.
2435 @smallexample @c ada
2436 pragma Source_File_Name
2437   (Spec_File_Name => "*_.ADA",
2438    Dot_Replacement => "__",
2439    Casing = Uppercase);
2440 pragma Source_File_Name
2441   (Body_File_Name => "*.ADA",
2442    Dot_Replacement => "__",
2443    Casing = Uppercase);
2444 pragma Source_File_Name
2445   (Subunit_File_Name => "*.SEP",
2446    Dot_Replacement => "__",
2447    Casing = Uppercase);
2448 @end smallexample
2450 @node Generating Object Files
2451 @section Generating Object Files
2453 @noindent
2454 An Ada program consists of a set of source files, and the first step in
2455 compiling the program is to generate the corresponding object files.
2456 These are generated by compiling a subset of these source files.
2457 The files you need to compile are the following:
2459 @itemize @bullet
2460 @item
2461 If a package spec has no body, compile the package spec to produce the
2462 object file for the package.
2464 @item
2465 If a package has both a spec and a body, compile the body to produce the
2466 object file for the package. The source file for the package spec need
2467 not be compiled in this case because there is only one object file, which
2468 contains the code for both the spec and body of the package.
2470 @item
2471 For a subprogram, compile the subprogram body to produce the object file
2472 for the subprogram. The spec, if one is present, is as usual in a
2473 separate file, and need not be compiled.
2475 @item
2476 @cindex Subunits
2477 In the case of subunits, only compile the parent unit. A single object
2478 file is generated for the entire subunit tree, which includes all the
2479 subunits.
2481 @item
2482 Compile child units independently of their parent units
2483 (though, of course, the spec of all the ancestor unit must be present in order
2484 to compile a child unit).
2486 @item
2487 @cindex Generics
2488 Compile generic units in the same manner as any other units. The object
2489 files in this case are small dummy files that contain at most the
2490 flag used for elaboration checking. This is because GNAT always handles generic
2491 instantiation by means of macro expansion. However, it is still necessary to
2492 compile generic units, for dependency checking and elaboration purposes.
2493 @end itemize
2495 @noindent
2496 The preceding rules describe the set of files that must be compiled to
2497 generate the object files for a program. Each object file has the same
2498 name as the corresponding source file, except that the extension is
2499 @file{.o} as usual.
2501 You may wish to compile other files for the purpose of checking their
2502 syntactic and semantic correctness. For example, in the case where a
2503 package has a separate spec and body, you would not normally compile the
2504 spec. However, it is convenient in practice to compile the spec to make
2505 sure it is error-free before compiling clients of this spec, because such
2506 compilations will fail if there is an error in the spec.
2508 GNAT provides an option for compiling such files purely for the
2509 purposes of checking correctness; such compilations are not required as
2510 part of the process of building a program. To compile a file in this
2511 checking mode, use the @option{-gnatc} switch.
2513 @node Source Dependencies
2514 @section Source Dependencies
2516 @noindent
2517 A given object file clearly depends on the source file which is compiled
2518 to produce it. Here we are using @dfn{depends} in the sense of a typical
2519 @code{make} utility; in other words, an object file depends on a source
2520 file if changes to the source file require the object file to be
2521 recompiled.
2522 In addition to this basic dependency, a given object may depend on
2523 additional source files as follows:
2525 @itemize @bullet
2526 @item
2527 If a file being compiled @code{with}'s a unit @var{X}, the object file
2528 depends on the file containing the spec of unit @var{X}. This includes
2529 files that are @code{with}'ed implicitly either because they are parents
2530 of @code{with}'ed child units or they are run-time units required by the
2531 language constructs used in a particular unit.
2533 @item
2534 If a file being compiled instantiates a library level generic unit, the
2535 object file depends on both the spec and body files for this generic
2536 unit.
2538 @item
2539 If a file being compiled instantiates a generic unit defined within a
2540 package, the object file depends on the body file for the package as
2541 well as the spec file.
2543 @item
2544 @findex Inline
2545 @cindex @option{-gnatn} switch
2546 If a file being compiled contains a call to a subprogram for which
2547 pragma @code{Inline} applies and inlining is activated with the
2548 @option{-gnatn} switch, the object file depends on the file containing the
2549 body of this subprogram as well as on the file containing the spec. Note
2550 that for inlining to actually occur as a result of the use of this switch,
2551 it is necessary to compile in optimizing mode.
2553 @cindex @option{-gnatN} switch
2554 The use of @option{-gnatN} activates a more extensive inlining optimization
2555 that is performed by the front end of the compiler. This inlining does
2556 not require that the code generation be optimized. Like @option{-gnatn},
2557 the use of this switch generates additional dependencies.
2558 Note that
2559 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2560 to specify both options.
2562 @item
2563 If an object file O  depends on the proper body of a subunit through inlining
2564 or instantiation, it depends on the parent unit of the subunit. This means that
2565 any modification of the parent unit or one of its subunits affects the
2566 compilation of O.
2568 @item
2569 The object file for a parent unit depends on all its subunit body files.
2571 @item
2572 The previous two rules meant that for purposes of computing dependencies and
2573 recompilation, a body and all its subunits are treated as an indivisible whole.
2575 @noindent
2576 These rules are applied transitively: if unit @code{A} @code{with}'s
2577 unit @code{B}, whose elaboration calls an inlined procedure in package
2578 @code{C}, the object file for unit @code{A} will depend on the body of
2579 @code{C}, in file @file{c.adb}.
2581 The set of dependent files described by these rules includes all the
2582 files on which the unit is semantically dependent, as described in the
2583 Ada 95 Language Reference Manual. However, it is a superset of what the
2584 ARM describes, because it includes generic, inline, and subunit dependencies.
2586 An object file must be recreated by recompiling the corresponding source
2587 file if any of the source files on which it depends are modified. For
2588 example, if the @code{make} utility is used to control compilation,
2589 the rule for an Ada object file must mention all the source files on
2590 which the object file depends, according to the above definition.
2591 The determination of the necessary
2592 recompilations is done automatically when one uses @command{gnatmake}.
2593 @end itemize
2595 @node The Ada Library Information Files
2596 @section The Ada Library Information Files
2597 @cindex Ada Library Information files
2598 @cindex @file{ALI} files
2600 @noindent
2601 Each compilation actually generates two output files. The first of these
2602 is the normal object file that has a @file{.o} extension. The second is a
2603 text file containing full dependency information. It has the same
2604 name as the source file, but an @file{.ali} extension.
2605 This file is known as the Ada Library Information (@file{ALI}) file.
2606 The following information is contained in the @file{ALI} file.
2608 @itemize @bullet
2609 @item
2610 Version information (indicates which version of GNAT was used to compile
2611 the unit(s) in question)
2613 @item
2614 Main program information (including priority and time slice settings,
2615 as well as the wide character encoding used during compilation).
2617 @item
2618 List of arguments used in the @command{gcc} command for the compilation
2620 @item
2621 Attributes of the unit, including configuration pragmas used, an indication
2622 of whether the compilation was successful, exception model used etc.
2624 @item
2625 A list of relevant restrictions applying to the unit (used for consistency)
2626 checking.
2628 @item
2629 Categorization information (e.g. use of pragma @code{Pure}).
2631 @item
2632 Information on all @code{with}'ed units, including presence of
2633 @code{Elaborate} or @code{Elaborate_All} pragmas.
2635 @item
2636 Information from any @code{Linker_Options} pragmas used in the unit
2638 @item
2639 Information on the use of @code{Body_Version} or @code{Version}
2640 attributes in the unit.
2642 @item
2643 Dependency information. This is a list of files, together with
2644 time stamp and checksum information. These are files on which
2645 the unit depends in the sense that recompilation is required
2646 if any of these units are modified.
2648 @item
2649 Cross-reference data. Contains information on all entities referenced
2650 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2651 provide cross-reference information.
2653 @end itemize
2655 @noindent
2656 For a full detailed description of the format of the @file{ALI} file,
2657 see the source of the body of unit @code{Lib.Writ}, contained in file
2658 @file{lib-writ.adb} in the GNAT compiler sources.
2660 @node Binding an Ada Program
2661 @section Binding an Ada Program
2663 @noindent
2664 When using languages such as C and C++, once the source files have been
2665 compiled the only remaining step in building an executable program
2666 is linking the object modules together. This means that it is possible to
2667 link an inconsistent version of a program, in which two units have
2668 included different versions of the same header.
2670 The rules of Ada do not permit such an inconsistent program to be built.
2671 For example, if two clients have different versions of the same package,
2672 it is illegal to build a program containing these two clients.
2673 These rules are enforced by the GNAT binder, which also determines an
2674 elaboration order consistent with the Ada rules.
2676 The GNAT binder is run after all the object files for a program have
2677 been created. It is given the name of the main program unit, and from
2678 this it determines the set of units required by the program, by reading the
2679 corresponding ALI files. It generates error messages if the program is
2680 inconsistent or if no valid order of elaboration exists.
2682 If no errors are detected, the binder produces a main program, in Ada by
2683 default, that contains calls to the elaboration procedures of those
2684 compilation unit that require them, followed by
2685 a call to the main program. This Ada program is compiled to generate the
2686 object file for the main program. The name of
2687 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2688 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2689 main program unit.
2691 Finally, the linker is used to build the resulting executable program,
2692 using the object from the main program from the bind step as well as the
2693 object files for the Ada units of the program.
2695 @node Mixed Language Programming
2696 @section Mixed Language Programming
2697 @cindex Mixed Language Programming
2699 @noindent
2700 This section describes how to develop a mixed-language program,
2701 specifically one that comprises units in both Ada and C.
2703 @menu
2704 * Interfacing to C::
2705 * Calling Conventions::
2706 @end menu
2708 @node Interfacing to C
2709 @subsection Interfacing to C
2710 @noindent
2711 Interfacing Ada with a foreign language such as C involves using
2712 compiler directives to import and/or export entity definitions in each
2713 language---using @code{extern} statements in C, for instance, and the
2714 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2715 a full treatment of these topics, read Appendix B, section 1 of the Ada
2716 95 Language Reference Manual.
2718 There are two ways to build a program using GNAT that contains some Ada
2719 sources and some foreign language sources, depending on whether or not
2720 the main subprogram is written in Ada.  Here is a source example with
2721 the main subprogram in Ada:
2723 @smallexample
2724 /* file1.c */
2725 #include <stdio.h>
2727 void print_num (int num)
2729   printf ("num is %d.\n", num);
2730   return;
2733 /* file2.c */
2735 /* num_from_Ada is declared in my_main.adb */
2736 extern int num_from_Ada;
2738 int get_num (void)
2740   return num_from_Ada;
2742 @end smallexample
2744 @smallexample @c ada
2745 --  my_main.adb
2746 procedure My_Main is
2748    --  Declare then export an Integer entity called num_from_Ada
2749    My_Num : Integer := 10;
2750    pragma Export (C, My_Num, "num_from_Ada");
2752    --  Declare an Ada function spec for Get_Num, then use
2753    --  C function get_num for the implementation.
2754    function Get_Num return Integer;
2755    pragma Import (C, Get_Num, "get_num");
2757    --  Declare an Ada procedure spec for Print_Num, then use
2758    --  C function print_num for the implementation.
2759    procedure Print_Num (Num : Integer);
2760    pragma Import (C, Print_Num, "print_num");
2762 begin
2763    Print_Num (Get_Num);
2764 end My_Main;
2765 @end smallexample
2767 @enumerate
2768 @item
2769 To build this example, first compile the foreign language files to
2770 generate object files:
2771 @smallexample
2772 gcc -c file1.c
2773 gcc -c file2.c
2774 @end smallexample
2776 @item
2777 Then, compile the Ada units to produce a set of object files and ALI
2778 files:
2779 @smallexample
2780 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2781 @end smallexample
2783 @item
2784 Run the Ada binder on the Ada main program:
2785 @smallexample
2786 gnatbind my_main.ali
2787 @end smallexample
2789 @item
2790 Link the Ada main program, the Ada objects and the other language
2791 objects:
2792 @smallexample
2793 gnatlink my_main.ali file1.o file2.o
2794 @end smallexample
2795 @end enumerate
2797 The last three steps can be grouped in a single command:
2798 @smallexample
2799 gnatmake my_main.adb -largs file1.o file2.o
2800 @end smallexample
2802 @cindex Binder output file
2803 @noindent
2804 If the main program is in a language other than Ada, then you may have
2805 more than one entry point into the Ada subsystem. You must use a special
2806 binder option to generate callable routines that initialize and
2807 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2808 Calls to the initialization and finalization routines must be inserted
2809 in the main program, or some other appropriate point in the code. The
2810 call to initialize the Ada units must occur before the first Ada
2811 subprogram is called, and the call to finalize the Ada units must occur
2812 after the last Ada subprogram returns. The binder will place the
2813 initialization and finalization subprograms into the
2814 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2815 sources.  To illustrate, we have the following example:
2817 @smallexample
2818 /* main.c */
2819 extern void adainit (void);
2820 extern void adafinal (void);
2821 extern int add (int, int);
2822 extern int sub (int, int);
2824 int main (int argc, char *argv[])
2826   int a = 21, b = 7;
2828   adainit();
2830   /* Should print "21 + 7 = 28" */
2831   printf ("%d + %d = %d\n", a, b, add (a, b));
2832   /* Should print "21 - 7 = 14" */
2833   printf ("%d - %d = %d\n", a, b, sub (a, b));
2835   adafinal();
2837 @end smallexample
2839 @smallexample @c ada
2840 --  unit1.ads
2841 package Unit1 is
2842    function Add (A, B : Integer) return Integer;
2843    pragma Export (C, Add, "add");
2844 end Unit1;
2846 --  unit1.adb
2847 package body Unit1 is
2848    function Add (A, B : Integer) return Integer is
2849    begin
2850       return A + B;
2851    end Add;
2852 end Unit1;
2854 --  unit2.ads
2855 package Unit2 is
2856    function Sub (A, B : Integer) return Integer;
2857    pragma Export (C, Sub, "sub");
2858 end Unit2;
2860 --  unit2.adb
2861 package body Unit2 is
2862    function Sub (A, B : Integer) return Integer is
2863    begin
2864       return A - B;
2865    end Sub;
2866 end Unit2;
2867 @end smallexample
2869 @enumerate
2870 @item
2871 The build procedure for this application is similar to the last
2872 example's.  First, compile the foreign language files to generate object
2873 files:
2874 @smallexample
2875 ^gcc -c main.c^gcc -c main.c^
2876 @end smallexample
2878 @item
2879 Next, compile the Ada units to produce a set of object files and ALI
2880 files:
2881 @smallexample
2882 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2883 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2884 @end smallexample
2886 @item
2887 Run the Ada binder on every generated ALI file.  Make sure to use the
2888 @option{-n} option to specify a foreign main program:
2889 @smallexample
2890 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2891 @end smallexample
2893 @item
2894 Link the Ada main program, the Ada objects and the foreign language
2895 objects. You need only list the last ALI file here:
2896 @smallexample
2897 gnatlink unit2.ali main.o -o exec_file
2898 @end smallexample
2900 This procedure yields a binary executable called @file{exec_file}.
2901 @end enumerate
2903 @node Calling Conventions
2904 @subsection Calling Conventions
2905 @cindex Foreign Languages
2906 @cindex Calling Conventions
2907 GNAT follows standard calling sequence conventions and will thus interface
2908 to any other language that also follows these conventions. The following
2909 Convention identifiers are recognized by GNAT:
2911 @table @code
2912 @cindex Interfacing to Ada
2913 @cindex Other Ada compilers
2914 @cindex Convention Ada
2915 @item Ada
2916 This indicates that the standard Ada calling sequence will be
2917 used and all Ada data items may be passed without any limitations in the
2918 case where GNAT is used to generate both the caller and callee. It is also
2919 possible to mix GNAT generated code and code generated by another Ada
2920 compiler. In this case, the data types should be restricted to simple
2921 cases, including primitive types. Whether complex data types can be passed
2922 depends on the situation. Probably it is safe to pass simple arrays, such
2923 as arrays of integers or floats. Records may or may not work, depending
2924 on whether both compilers lay them out identically. Complex structures
2925 involving variant records, access parameters, tasks, or protected types,
2926 are unlikely to be able to be passed.
2928 Note that in the case of GNAT running
2929 on a platform that supports HP Ada 83, a higher degree of compatibility
2930 can be guaranteed, and in particular records are layed out in an identical
2931 manner in the two compilers. Note also that if output from two different
2932 compilers is mixed, the program is responsible for dealing with elaboration
2933 issues. Probably the safest approach is to write the main program in the
2934 version of Ada other than GNAT, so that it takes care of its own elaboration
2935 requirements, and then call the GNAT-generated adainit procedure to ensure
2936 elaboration of the GNAT components. Consult the documentation of the other
2937 Ada compiler for further details on elaboration.
2939 However, it is not possible to mix the tasking run time of GNAT and
2940 HP Ada 83, All the tasking operations must either be entirely within
2941 GNAT compiled sections of the program, or entirely within HP Ada 83
2942 compiled sections of the program.
2944 @cindex Interfacing to Assembly
2945 @cindex Convention Assembler
2946 @item Assembler
2947 Specifies assembler as the convention. In practice this has the
2948 same effect as convention Ada (but is not equivalent in the sense of being
2949 considered the same convention).
2951 @cindex Convention Asm
2952 @findex Asm
2953 @item Asm
2954 Equivalent to Assembler.
2956 @cindex Interfacing to COBOL
2957 @cindex Convention COBOL
2958 @findex COBOL
2959 @item COBOL
2960 Data will be passed according to the conventions described
2961 in section B.4 of the Ada 95 Reference Manual.
2963 @findex C
2964 @cindex Interfacing to C
2965 @cindex Convention C
2966 @item C
2967 Data will be passed according to the conventions described
2968 in section B.3 of the Ada 95 Reference Manual.
2970 @findex C varargs function
2971 @cindex Intefacing to C varargs function
2972 @cindex varargs function interfaces
2973 @item C varargs function
2974 In C, @code{varargs} allows a function to take a variable number of
2975 arguments. There is no direct equivalent in this to Ada. One
2976 approach that can be used is to create a C wrapper for each
2977 different profile and then interface to this C wrapper. For
2978 example, to print an @code{int} value using @code{printf},
2979 create a C function @code{printfi} that takes two arguments, a
2980 pointer to a string and an int, and calls @code{printf}.
2981 Then in the Ada program, use pragma @code{Import} to
2982 interface to printfi.
2984 It may work on some platforms to directly interface to
2985 a @code{varargs} function by providing a specific Ada profile
2986 for a a particular call. However, this does not work on
2987 all platforms, since there is no guarantee that the
2988 calling sequence for a two argument normal C function
2989 is the same as for calling a @code{varargs} C function with
2990 the same two arguments.
2992 @cindex Convention Default
2993 @findex Default
2994 @item Default
2995 Equivalent to C.
2997 @cindex Convention External
2998 @findex External
2999 @item External
3000 Equivalent to C.
3002 @findex C++
3003 @cindex Interfacing to C++
3004 @cindex Convention C++
3005 @item CPP
3006 This stands for C++. For most purposes this is identical to C.
3007 See the separate description of the specialized GNAT pragmas relating to
3008 C++ interfacing for further details.
3010 @findex Fortran
3011 @cindex Interfacing to Fortran
3012 @cindex Convention Fortran
3013 @item Fortran
3014 Data will be passed according to the conventions described
3015 in section B.5 of the Ada 95 Reference Manual.
3017 @item Intrinsic
3018 This applies to an intrinsic operation, as defined in the Ada 95
3019 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3020 this means that the body of the subprogram is provided by the compiler itself,
3021 usually by means of an efficient code sequence, and that the user does not
3022 supply an explicit body for it. In an application program, the pragma can
3023 only be applied to the following two sets of names, which the GNAT compiler
3024 recognizes.
3026 @itemize @bullet
3027 @item
3028 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3029 Arithmetic.  The corresponding subprogram declaration must have
3030 two formal parameters. The
3031 first one must be a signed integer type or a modular type with a binary
3032 modulus, and the second parameter must be of type Natural.
3033 The return type must be the same as the type of the first argument. The size
3034 of this type can only be 8, 16, 32, or 64.
3035 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3036 The corresponding operator declaration must have parameters and result type
3037 that have the same root numeric type (for example, all three are long_float
3038 types). This simplifies the definition of operations that use type checking
3039 to perform dimensional checks:
3041 @smallexample @c ada
3042 type Distance is new Long_Float;
3043 type Time     is new Long_Float;
3044 type Velocity is new Long_Float;
3045 function "/" (D : Distance; T : Time)
3046   return Velocity;
3047 pragma Import (Intrinsic, "/");
3048 @end smallexample
3050 @noindent
3051 This common idiom is often programmed with a generic definition and an
3052 explicit body. The pragma makes it simpler to introduce such declarations.
3053 It incurs no overhead in compilation time or code size, because it is
3054 implemented as a single machine instruction.
3055 @end itemize
3056 @noindent
3058 @ifset unw
3059 @findex Stdcall
3060 @cindex Convention Stdcall
3061 @item Stdcall
3062 This is relevant only to Windows XP/2000/NT/95 implementations of GNAT,
3063 and specifies that the @code{Stdcall} calling sequence will be used,
3064 as defined by the NT API. Nevertheless, to ease building
3065 cross-platform bindings this convention will be handled as a @code{C} calling
3066 convention on non Windows platforms.
3068 @findex DLL
3069 @cindex Convention DLL
3070 @item DLL
3071 This is equivalent to @code{Stdcall}.
3073 @findex Win32
3074 @cindex Convention Win32
3075 @item Win32
3076 This is equivalent to @code{Stdcall}.
3077 @end ifset
3079 @findex Stubbed
3080 @cindex Convention Stubbed
3081 @item Stubbed
3082 This is a special convention that indicates that the compiler
3083 should provide a stub body that raises @code{Program_Error}.
3084 @end table
3086 @noindent
3087 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3088 that can be used to parametrize conventions and allow additional synonyms
3089 to be specified. For example if you have legacy code in which the convention
3090 identifier Fortran77 was used for Fortran, you can use the configuration
3091 pragma:
3093 @smallexample @c ada
3094 pragma Convention_Identifier (Fortran77, Fortran);
3095 @end smallexample
3097 @noindent
3098 And from now on the identifier Fortran77 may be used as a convention
3099 identifier (for example in an @code{Import} pragma) with the same
3100 meaning as Fortran.
3102 @node Building Mixed Ada & C++ Programs
3103 @section Building Mixed Ada & C++ Programs
3105 @noindent
3106 A programmer inexperienced with mixed-language development may find that
3107 building an application containing both Ada and C++ code can be a
3108 challenge. As a matter of fact, interfacing with C++ has not been
3109 standardized in the Ada 95 Reference Manual due to the immaturity of --
3110 and lack of standards for -- C++ at the time. This section gives a few
3111 hints that should make this task easier. The first section addresses
3112 the differences regarding interfacing with C. The second section
3113 looks into the delicate problem of linking the complete application from
3114 its Ada and C++ parts. The last section gives some hints on how the GNAT
3115 run time can be adapted in order to allow inter-language dispatching
3116 with a new C++ compiler.
3118 @menu
3119 * Interfacing to C++::
3120 * Linking a Mixed C++ & Ada Program::
3121 * A Simple Example::
3122 * Adapting the Run Time to a New C++ Compiler::
3123 @end menu
3125 @node Interfacing to C++
3126 @subsection Interfacing to C++
3128 @noindent
3129 GNAT supports interfacing with C++ compilers generating code that is
3130 compatible with the standard Application Binary Interface of the given
3131 platform.
3133 @noindent
3134 Interfacing can be done at 3 levels: simple data, subprograms, and
3135 classes. In the first two cases, GNAT offers a specific @var{Convention
3136 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3137 the names of subprograms, and currently, GNAT does not provide any help
3138 to solve the demangling problem. This problem can be addressed in two
3139 ways:
3140 @itemize @bullet
3141 @item
3142 by modifying the C++ code in order to force a C convention using
3143 the @code{extern "C"} syntax.
3145 @item
3146 by figuring out the mangled name and use it as the Link_Name argument of
3147 the pragma import.
3148 @end itemize
3150 @noindent
3151 Interfacing at the class level can be achieved by using the GNAT specific
3152 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3153 Reference Manual for additional information.
3155 @node Linking a Mixed C++ & Ada Program
3156 @subsection Linking a Mixed C++ & Ada Program
3158 @noindent
3159 Usually the linker of the C++ development system must be used to link
3160 mixed applications because most C++ systems will resolve elaboration
3161 issues (such as calling constructors on global class instances)
3162 transparently during the link phase. GNAT has been adapted to ease the
3163 use of a foreign linker for the last phase. Three cases can be
3164 considered:
3165 @enumerate
3167 @item
3168 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3169 The C++ linker can simply be called by using the C++ specific driver
3170 called @code{c++}. Note that this setup is not very common because it
3171 may involve recompiling the whole GCC tree from sources, which makes it
3172 harder to upgrade the compilation system for one language without
3173 destabilizing the other.
3175 @smallexample
3176 $ c++ -c file1.C
3177 $ c++ -c file2.C
3178 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3179 @end smallexample
3181 @item
3182 Using GNAT and G++ from two different GCC installations: If both
3183 compilers are on the PATH, the previous method may be used. It is
3184 important to note that environment variables such as C_INCLUDE_PATH,
3185 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3186 at the same time and may make one of the two compilers operate
3187 improperly if set during invocation of the wrong compiler.  It is also
3188 very important that the linker uses the proper @file{libgcc.a} GCC
3189 library -- that is, the one from the C++ compiler installation. The
3190 implicit link command as suggested in the gnatmake command from the
3191 former example can be replaced by an explicit link command with the
3192 full-verbosity option in order to verify which library is used:
3193 @smallexample
3194 $ gnatbind ada_unit
3195 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3196 @end smallexample
3197 If there is a problem due to interfering environment variables, it can
3198 be worked around by using an intermediate script. The following example
3199 shows the proper script to use when GNAT has not been installed at its
3200 default location and g++ has been installed at its default location:
3202 @smallexample
3203 $ cat ./my_script
3204 #!/bin/sh
3205 unset BINUTILS_ROOT
3206 unset GCC_ROOT
3207 c++ $*
3208 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3209 @end smallexample
3211 @item
3212 Using a non-GNU C++ compiler: The commands previously described can be
3213 used to insure that the C++ linker is used. Nonetheless, you need to add
3214 a few more parameters to the link command line, depending on the exception
3215 mechanism used.
3217 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3218 to the libgcc libraries are required:
3220 @smallexample
3221 $ cat ./my_script
3222 #!/bin/sh
3223 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3224 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3225 @end smallexample
3227 Where CC is the name of the non-GNU C++ compiler.
3229 If the @code{zero cost} exception mechanism is used, and the platform
3230 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3231 paths to more objects are required:
3233 @smallexample
3234 $ cat ./my_script
3235 #!/bin/sh
3236 CC `gcc -print-file-name=crtbegin.o` $* \
3237 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3238 `gcc -print-file-name=crtend.o`
3239 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3240 @end smallexample
3242 If the @code{zero cost} exception mechanism is used, and the platform
3243 doesn't support automatic registration of exception tables (e.g. HP-UX,
3244 Tru64 or AIX), the simple approach described above will not work and
3245 a pre-linking phase using GNAT will be necessary.
3247 @end enumerate
3249 @node A Simple Example
3250 @subsection  A Simple Example
3251 @noindent
3252 The following example, provided as part of the GNAT examples, shows how
3253 to achieve procedural interfacing between Ada and C++ in both
3254 directions. The C++ class A has two methods. The first method is exported
3255 to Ada by the means of an extern C wrapper function. The second method
3256 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3257 a limited record with a layout comparable to the C++ class. The Ada
3258 subprogram, in turn, calls the C++ method. So, starting from the C++
3259 main program, the process passes back and forth between the two
3260 languages.
3262 @noindent
3263 Here are the compilation commands:
3264 @smallexample
3265 $ gnatmake -c simple_cpp_interface
3266 $ c++ -c cpp_main.C
3267 $ c++ -c ex7.C
3268 $ gnatbind -n simple_cpp_interface
3269 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3270       -lstdc++ ex7.o cpp_main.o
3271 @end smallexample
3273 @noindent
3274 Here are the corresponding sources:
3275 @smallexample
3277 //cpp_main.C
3279 #include "ex7.h"
3281 extern "C" @{
3282   void adainit (void);
3283   void adafinal (void);
3284   void method1 (A *t);
3287 void method1 (A *t)
3289   t->method1 ();
3292 int main ()
3294   A obj;
3295   adainit ();
3296   obj.method2 (3030);
3297   adafinal ();
3300 //ex7.h
3302 class Origin @{
3303  public:
3304   int o_value;
3306 class A : public Origin @{
3307  public:
3308   void method1 (void);
3309   void method2 (int v);
3310   A();
3311   int   a_value;
3314 //ex7.C
3316 #include "ex7.h"
3317 #include <stdio.h>
3319 extern "C" @{ void ada_method2 (A *t, int v);@}
3321 void A::method1 (void)
3323   a_value = 2020;
3324   printf ("in A::method1, a_value = %d \n",a_value);
3328 void A::method2 (int v)
3330    ada_method2 (this, v);
3331    printf ("in A::method2, a_value = %d \n",a_value);
3335 A::A(void)
3337    a_value = 1010;
3338   printf ("in A::A, a_value = %d \n",a_value);
3341 -- Ada sources
3342 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3344    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3345    @b{begin}
3346       Method1 (This);
3347       This.A_Value := V;
3348    @b{end} Ada_Method2;
3350 @b{end} Simple_Cpp_Interface;
3352 @b{package} Simple_Cpp_Interface @b{is}
3353    @b{type} A @b{is} @b{limited}
3354       @b{record}
3355          O_Value : Integer;
3356          A_Value : Integer;
3357       @b{end} @b{record};
3358    @b{pragma} Convention (C, A);
3360    @b{procedure} Method1 (This : @b{in} @b{out} A);
3361    @b{pragma} Import (C, Method1);
3363    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3364    @b{pragma} Export (C, Ada_Method2);
3366 @b{end} Simple_Cpp_Interface;
3367 @end smallexample
3369 @node Adapting the Run Time to a New C++ Compiler
3370 @subsection Adapting the Run Time to a New C++ Compiler
3371 @noindent
3372 GNAT offers the capability to derive Ada 95 tagged types directly from
3373 preexisting C++ classes and . See ``Interfacing with C++'' in the
3374 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3375 such a goal
3376 has been made user configurable through a GNAT library unit
3377 @code{Interfaces.CPP}. The default version of this file is adapted to
3378 the GNU C++ compiler. Internal knowledge of the virtual
3379 table layout used by the new C++ compiler is needed to configure
3380 properly this unit. The Interface of this unit is known by the compiler
3381 and cannot be changed except for the value of the constants defining the
3382 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3383 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3384 of this unit for more details.
3386 @node Comparison between GNAT and C/C++ Compilation Models
3387 @section Comparison between GNAT and C/C++ Compilation Models
3389 @noindent
3390 The GNAT model of compilation is close to the C and C++ models. You can
3391 think of Ada specs as corresponding to header files in C. As in C, you
3392 don't need to compile specs; they are compiled when they are used. The
3393 Ada @code{with} is similar in effect to the @code{#include} of a C
3394 header.
3396 One notable difference is that, in Ada, you may compile specs separately
3397 to check them for semantic and syntactic accuracy. This is not always
3398 possible with C headers because they are fragments of programs that have
3399 less specific syntactic or semantic rules.
3401 The other major difference is the requirement for running the binder,
3402 which performs two important functions. First, it checks for
3403 consistency. In C or C++, the only defense against assembling
3404 inconsistent programs lies outside the compiler, in a makefile, for
3405 example. The binder satisfies the Ada requirement that it be impossible
3406 to construct an inconsistent program when the compiler is used in normal
3407 mode.
3409 @cindex Elaboration order control
3410 The other important function of the binder is to deal with elaboration
3411 issues. There are also elaboration issues in C++ that are handled
3412 automatically. This automatic handling has the advantage of being
3413 simpler to use, but the C++ programmer has no control over elaboration.
3414 Where @code{gnatbind} might complain there was no valid order of
3415 elaboration, a C++ compiler would simply construct a program that
3416 malfunctioned at run time.
3418 @node Comparison between GNAT and Conventional Ada Library Models
3419 @section Comparison between GNAT and Conventional Ada Library Models
3421 @noindent
3422 This section is intended to be useful to Ada programmers who have
3423 previously used an Ada compiler implementing the traditional Ada library
3424 model, as described in the Ada 95 Language Reference Manual. If you
3425 have not used such a system, please go on to the next section.
3427 @cindex GNAT library
3428 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3429 source files themselves acts as the library. Compiling Ada programs does
3430 not generate any centralized information, but rather an object file and
3431 a ALI file, which are of interest only to the binder and linker.
3432 In a traditional system, the compiler reads information not only from
3433 the source file being compiled, but also from the centralized library.
3434 This means that the effect of a compilation depends on what has been
3435 previously compiled. In particular:
3437 @itemize @bullet
3438 @item
3439 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3440 to the version of the unit most recently compiled into the library.
3442 @item
3443 Inlining is effective only if the necessary body has already been
3444 compiled into the library.
3446 @item
3447 Compiling a unit may obsolete other units in the library.
3448 @end itemize
3450 @noindent
3451 In GNAT, compiling one unit never affects the compilation of any other
3452 units because the compiler reads only source files. Only changes to source
3453 files can affect the results of a compilation. In particular:
3455 @itemize @bullet
3456 @item
3457 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3458 to the source version of the unit that is currently accessible to the
3459 compiler.
3461 @item
3462 @cindex Inlining
3463 Inlining requires the appropriate source files for the package or
3464 subprogram bodies to be available to the compiler. Inlining is always
3465 effective, independent of the order in which units are complied.
3467 @item
3468 Compiling a unit never affects any other compilations. The editing of
3469 sources may cause previous compilations to be out of date if they
3470 depended on the source file being modified.
3471 @end itemize
3473 @noindent
3474 The most important result of these differences is that order of compilation
3475 is never significant in GNAT. There is no situation in which one is
3476 required to do one compilation before another. What shows up as order of
3477 compilation requirements in the traditional Ada library becomes, in
3478 GNAT, simple source dependencies; in other words, there is only a set
3479 of rules saying what source files must be present when a file is
3480 compiled.
3482 @ifset vms
3483 @node Placement of temporary files
3484 @section Placement of temporary files
3485 @cindex Temporary files (user control over placement)
3487 @noindent
3488 GNAT creates temporary files in the directory designated by the environment
3489 variable @env{TMPDIR}.
3490 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3491 for detailed information on how environment variables are resolved.
3492 For most users the easiest way to make use of this feature is to simply
3493 define @env{TMPDIR} as a job level logical name).
3494 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3495 for compiler temporary files, then you can include something like the
3496 following command in your @file{LOGIN.COM} file:
3498 @smallexample
3499 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3500 @end smallexample
3502 @noindent
3503 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3504 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3505 designated by @env{TEMP}.
3506 If none of these environment variables are defined then GNAT uses the
3507 directory designated by the logical name @code{SYS$SCRATCH:}
3508 (by default the user's home directory). If all else fails
3509 GNAT uses the current directory for temporary files.
3510 @end ifset
3512 @c *************************
3513 @node Compiling Using gcc
3514 @chapter Compiling Using @command{gcc}
3516 @noindent
3517 This chapter discusses how to compile Ada programs using the @command{gcc}
3518 command. It also describes the set of switches
3519 that can be used to control the behavior of the compiler.
3520 @menu
3521 * Compiling Programs::
3522 * Switches for gcc::
3523 * Search Paths and the Run-Time Library (RTL)::
3524 * Order of Compilation Issues::
3525 * Examples::
3526 @end menu
3528 @node Compiling Programs
3529 @section Compiling Programs
3531 @noindent
3532 The first step in creating an executable program is to compile the units
3533 of the program using the @command{gcc} command. You must compile the
3534 following files:
3536 @itemize @bullet
3537 @item
3538 the body file (@file{.adb}) for a library level subprogram or generic
3539 subprogram
3541 @item
3542 the spec file (@file{.ads}) for a library level package or generic
3543 package that has no body
3545 @item
3546 the body file (@file{.adb}) for a library level package
3547 or generic package that has a body
3549 @end itemize
3551 @noindent
3552 You need @emph{not} compile the following files
3554 @itemize @bullet
3556 @item
3557 the spec of a library unit which has a body
3559 @item
3560 subunits
3561 @end itemize
3563 @noindent
3564 because they are compiled as part of compiling related units. GNAT
3565 package specs
3566 when the corresponding body is compiled, and subunits when the parent is
3567 compiled.
3569 @cindex cannot generate code
3570 If you attempt to compile any of these files, you will get one of the
3571 following error messages (where fff is the name of the file you compiled):
3573 @smallexample
3574 cannot generate code for file @var{fff} (package spec)
3575 to check package spec, use -gnatc
3577 cannot generate code for file @var{fff} (missing subunits)
3578 to check parent unit, use -gnatc
3580 cannot generate code for file @var{fff} (subprogram spec)
3581 to check subprogram spec, use -gnatc
3583 cannot generate code for file @var{fff} (subunit)
3584 to check subunit, use -gnatc
3585 @end smallexample
3587 @noindent
3588 As indicated by the above error messages, if you want to submit
3589 one of these files to the compiler to check for correct semantics
3590 without generating code, then use the @option{-gnatc} switch.
3592 The basic command for compiling a file containing an Ada unit is
3594 @smallexample
3595 $ gcc -c [@var{switches}] @file{file name}
3596 @end smallexample
3598 @noindent
3599 where @var{file name} is the name of the Ada file (usually
3600 having an extension
3601 @file{.ads} for a spec or @file{.adb} for a body).
3602 @ifclear vms
3603 You specify the
3604 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3605 @end ifclear
3606 The result of a successful compilation is an object file, which has the
3607 same name as the source file but an extension of @file{.o} and an Ada
3608 Library Information (ALI) file, which also has the same name as the
3609 source file, but with @file{.ali} as the extension. GNAT creates these
3610 two output files in the current directory, but you may specify a source
3611 file in any directory using an absolute or relative path specification
3612 containing the directory information.
3614 @findex gnat1
3615 @command{gcc} is actually a driver program that looks at the extensions of
3616 the file arguments and loads the appropriate compiler. For example, the
3617 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3618 These programs are in directories known to the driver program (in some
3619 configurations via environment variables you set), but need not be in
3620 your path. The @command{gcc} driver also calls the assembler and any other
3621 utilities needed to complete the generation of the required object
3622 files.
3624 It is possible to supply several file names on the same @command{gcc}
3625 command. This causes @command{gcc} to call the appropriate compiler for
3626 each file. For example, the following command lists three separate
3627 files to be compiled:
3629 @smallexample
3630 $ gcc -c x.adb y.adb z.c
3631 @end smallexample
3633 @noindent
3634 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3635 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3636 The compiler generates three object files @file{x.o}, @file{y.o} and
3637 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3638 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3639 @ifclear vms
3640 except for
3641 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3642 @end ifclear
3644 @node Switches for gcc
3645 @section Switches for @command{gcc}
3647 @noindent
3648 The @command{gcc} command accepts switches that control the
3649 compilation process. These switches are fully described in this section.
3650 First we briefly list all the switches, in alphabetical order, then we
3651 describe the switches in more detail in functionally grouped sections.
3653 More switches exist for GCC than those documented here, especially
3654 for specific targets. However, their use is not recommended as
3655 they may change code generation in ways that are incompatible with
3656 the Ada run-time library, or can cause inconsistencies between
3657 compilation units.
3659 @menu
3660 * Output and Error Message Control::
3661 * Warning Message Control::
3662 * Debugging and Assertion Control::
3663 * Validity Checking::
3664 * Style Checking::
3665 * Run-Time Checks::
3666 * Using gcc for Syntax Checking::
3667 * Using gcc for Semantic Checking::
3668 * Compiling Different Versions of Ada::
3669 * Character Set Control::
3670 * File Naming Control::
3671 * Subprogram Inlining Control::
3672 * Auxiliary Output Control::
3673 * Debugging Control::
3674 * Exception Handling Control::
3675 * Units to Sources Mapping Files::
3676 * Integrated Preprocessing::
3677 * Code Generation Control::
3678 @ifset vms
3679 * Return Codes::
3680 @end ifset
3681 @end menu
3683 @table @option
3684 @c !sort!
3685 @ifclear vms
3686 @cindex @option{-b} (@command{gcc})
3687 @item -b @var{target}
3688 Compile your program to run on @var{target}, which is the name of a
3689 system configuration. You must have a GNAT cross-compiler built if
3690 @var{target} is not the same as your host system.
3692 @item -B@var{dir}
3693 @cindex @option{-B} (@command{gcc})
3694 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3695 from @var{dir} instead of the default location. Only use this switch
3696 when multiple versions of the GNAT compiler are available. See the
3697 @command{gcc} manual page for further details. You would normally use the
3698 @option{-b} or @option{-V} switch instead.
3700 @item -c
3701 @cindex @option{-c} (@command{gcc})
3702 Compile. Always use this switch when compiling Ada programs.
3704 Note: for some other languages when using @command{gcc}, notably in
3705 the case of C and C++, it is possible to use
3706 use @command{gcc} without a @option{-c} switch to
3707 compile and link in one step. In the case of GNAT, you
3708 cannot use this approach, because the binder must be run
3709 and @command{gcc} cannot be used to run the GNAT binder.
3710 @end ifclear
3712 @item -fno-inline
3713 @cindex @option{-fno-inline} (@command{gcc})
3714 Suppresses all back-end inlining, even if other optimization or inlining
3715 switches are set.
3716 This includes suppression of inlining that results
3717 from the use of the pragma @code{Inline_Always}.
3718 See also @option{-gnatn} and @option{-gnatN}.
3720 @item -fno-strict-aliasing
3721 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3722 Causes the compiler to avoid assumptions regarding non-aliasing
3723 of objects of different types. See
3724 @ref{Optimization and Strict Aliasing} for details.
3726 @item -fstack-check
3727 @cindex @option{-fstack-check} (@command{gcc})
3728 Activates stack checking.
3729 See @ref{Stack Overflow Checking} for details of the use of this option.
3731 @item -fstack-usage
3732 @cindex @option{-fstack-usage} (@command{gcc})
3733 Makes the compiler output stack usage information for the program, on a
3734 per-function basis.  The description of the format is to be found in
3735 the GCC documentation.
3737 @item -fcallgraph-info
3738 @cindex @option{-fcallgraph-info} (@command{gcc})
3739 Makes the compiler output callgraph information for the program, on a
3740 per-file basis.  The information is generated in the VCG format.  It can
3741 be decorated with additional, per-node information if other debugging
3742 options are enabled (only works with -fstack-usage as of this writing).
3744 @item ^-g^/DEBUG^
3745 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3746 Generate debugging information. This information is stored in the object
3747 file and copied from there to the final executable file by the linker,
3748 where it can be read by the debugger. You must use the
3749 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3751 @item -gnat83
3752 @cindex @option{-gnat83} (@command{gcc})
3753 Enforce Ada 83 restrictions.
3755 @item -gnat95
3756 @cindex @option{-gnat95} (@command{gcc})
3757 Enforce Ada 95 restrictions.
3759 @item -gnat05
3760 @cindex @option{-gnat05} (@command{gcc})
3761 Allow full Ada 2005 features.
3763 @item -gnata
3764 @cindex @option{-gnata} (@command{gcc})
3765 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3766 activated. Note that these pragmas can also be controlled using the
3767 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3769 @item -gnatA
3770 @cindex @option{-gnatA} (@command{gcc})
3771 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3772 it will be ignored.
3774 @item -gnatb
3775 @cindex @option{-gnatb} (@command{gcc})
3776 Generate brief messages to @file{stderr} even if verbose mode set.
3778 @item -gnatc
3779 @cindex @option{-gnatc} (@command{gcc})
3780 Check syntax and semantics only (no code generation attempted).
3782 @item -gnatd
3783 @cindex @option{-gnatd} (@command{gcc})
3784 Specify debug options for the compiler. The string of characters after
3785 the @option{-gnatd} specify the specific debug options. The possible
3786 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3787 compiler source file @file{debug.adb} for details of the implemented
3788 debug options. Certain debug options are relevant to applications
3789 programmers, and these are documented at appropriate points in this
3790 users guide.
3792 @item -gnatD
3793 @cindex @option{-gnatD} (@command{gcc})
3794 Create expanded source files for source level debugging. This switch
3795 also suppress generation of cross-reference information
3796 (see @option{-gnatx}).
3798 @item -gnatec=@var{path}
3799 @cindex @option{-gnatec} (@command{gcc})
3800 Specify a configuration pragma file
3801 @ifclear vms
3802 (the equal sign is optional)
3803 @end ifclear
3804 (@pxref{The Configuration Pragmas Files}).
3806 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3807 @cindex @option{-gnateD} (@command{gcc})
3808 Defines a symbol, associated with value, for preprocessing.
3809 (@pxref{Integrated Preprocessing}).
3811 @item -gnatef
3812 @cindex @option{-gnatef} (@command{gcc})
3813 Display full source path name in brief error messages.
3815 @item -gnatem=@var{path}
3816 @cindex @option{-gnatem} (@command{gcc})
3817 Specify a mapping file
3818 @ifclear vms
3819 (the equal sign is optional)
3820 @end ifclear
3821 (@pxref{Units to Sources Mapping Files}).
3823 @item -gnatep=@var{file}
3824 @cindex @option{-gnatep} (@command{gcc})
3825 Specify a preprocessing data file
3826 @ifclear vms
3827 (the equal sign is optional)
3828 @end ifclear
3829 (@pxref{Integrated Preprocessing}).
3831 @item -gnatE
3832 @cindex @option{-gnatE} (@command{gcc})
3833 Full dynamic elaboration checks.
3835 @item -gnatf
3836 @cindex @option{-gnatf} (@command{gcc})
3837 Full errors. Multiple errors per line, all undefined references, do not
3838 attempt to suppress cascaded errors.
3840 @item -gnatF
3841 @cindex @option{-gnatF} (@command{gcc})
3842 Externals names are folded to all uppercase.
3844 @item -gnatg
3845 @cindex @option{-gnatg} (@command{gcc})
3846 Internal GNAT implementation mode. This should not be used for
3847 applications programs, it is intended only for use by the compiler
3848 and its run-time library. For documentation, see the GNAT sources.
3849 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3850 are generated on unreferenced entities, and all warnings are treated
3851 as errors.
3853 @item -gnatG
3854 @cindex @option{-gnatG} (@command{gcc})
3855 List generated expanded code in source form.
3857 @item ^-gnath^/HELP^
3858 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3859 Output usage information. The output is written to @file{stdout}.
3861 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3862 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3863 Identifier character set
3864 @ifclear vms
3865 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3866 @end ifclear
3867 @ifset vms
3868 For details of the possible selections for @var{c},
3869 see @ref{Character Set Control}.
3870 @end ifset
3872 @item -gnatk=@var{n}
3873 @cindex @option{-gnatk} (@command{gcc})
3874 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3876 @item -gnatl
3877 @cindex @option{-gnatl} (@command{gcc})
3878 Output full source listing with embedded error messages.
3880 @item -gnatm=@var{n}
3881 @cindex @option{-gnatm} (@command{gcc})
3882 Limit number of detected error or warning messages to @var{n}
3883 where @var{n} is in the range 1..999_999. The default setting if
3884 no switch is given is 9999. Compilation is terminated if this
3885 limit is exceeded. The equal sign here is optional.
3887 @item -gnatn
3888 @cindex @option{-gnatn} (@command{gcc})
3889 Activate inlining for subprograms for which
3890 pragma @code{inline} is specified. This inlining is performed
3891 by the GCC back-end.
3893 @item -gnatN
3894 @cindex @option{-gnatN} (@command{gcc})
3895 Activate front end inlining for subprograms for which
3896 pragma @code{Inline} is specified. This inlining is performed
3897 by the front end and will be visible in the
3898 @option{-gnatG} output.
3899 In some cases, this has proved more effective than the back end
3900 inlining resulting from the use of
3901 @option{-gnatn}.
3902 Note that
3903 @option{-gnatN} automatically implies
3904 @option{-gnatn} so it is not necessary
3905 to specify both options. There are a few cases that the back-end inlining
3906 catches that cannot be dealt with in the front-end.
3908 @item -gnato
3909 @cindex @option{-gnato} (@command{gcc})
3910 Enable numeric overflow checking (which is not normally enabled by
3911 default). Not that division by zero is a separate check that is not
3912 controlled by this switch (division by zero checking is on by default).
3914 @item -gnatp
3915 @cindex @option{-gnatp} (@command{gcc})
3916 Suppress all checks.
3918 @item -gnatP
3919 @cindex @option{-gnatP} (@command{gcc})
3920 Enable polling. This is required on some systems (notably Windows NT) to
3921 obtain asynchronous abort and asynchronous transfer of control capability.
3922 See the description of pragma Polling in the GNAT Reference Manual for
3923 full details.
3925 @item -gnatq
3926 @cindex @option{-gnatq} (@command{gcc})
3927 Don't quit; try semantics, even if parse errors.
3929 @item -gnatQ
3930 @cindex @option{-gnatQ} (@command{gcc})
3931 Don't quit; generate @file{ALI} and tree files even if illegalities.
3933 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3934 @cindex @option{-gnatR} (@command{gcc})
3935 Output representation information for declared types and objects.
3937 @item -gnats
3938 @cindex @option{-gnats} (@command{gcc})
3939 Syntax check only.
3941 @item -gnatS
3942 @cindex @option{-gnatS} (@command{gcc})
3943 Print package Standard.
3945 @item -gnatt
3946 @cindex @option{-gnatt} (@command{gcc})
3947 Generate tree output file.
3949 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3950 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3951 All compiler tables start at @var{nnn} times usual starting size.
3953 @item -gnatu
3954 @cindex @option{-gnatu} (@command{gcc})
3955 List units for this compilation.
3957 @item -gnatU
3958 @cindex @option{-gnatU} (@command{gcc})
3959 Tag all error messages with the unique string ``error:''
3961 @item -gnatv
3962 @cindex @option{-gnatv} (@command{gcc})
3963 Verbose mode. Full error output with source lines to @file{stdout}.
3965 @item -gnatV
3966 @cindex @option{-gnatV} (@command{gcc})
3967 Control level of validity checking. See separate section describing
3968 this feature.
3970 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3971 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
3972 Warning mode where
3973 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3974 the exact warnings that
3975 are enabled or disabled (@pxref{Warning Message Control}).
3977 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3978 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
3979 Wide character encoding method
3980 @ifclear vms
3981 (@var{e}=n/h/u/s/e/8).
3982 @end ifclear
3983 @ifset vms
3984 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3985 @end ifset
3987 @item -gnatx
3988 @cindex @option{-gnatx} (@command{gcc})
3989 Suppress generation of cross-reference information.
3991 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3992 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
3993 Enable built-in style checks (@pxref{Style Checking}).
3995 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3996 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
3997 Distribution stub generation and compilation
3998 @ifclear vms
3999 (@var{m}=r/c for receiver/caller stubs).
4000 @end ifclear
4001 @ifset vms
4002 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4003 to be generated and compiled).
4004 @end ifset
4006 @item ^-I^/SEARCH=^@var{dir}
4007 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4008 @cindex RTL
4009 Direct GNAT to search the @var{dir} directory for source files needed by
4010 the current compilation
4011 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4013 @item ^-I-^/NOCURRENT_DIRECTORY^
4014 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4015 @cindex RTL
4016 Except for the source file named in the command line, do not look for source
4017 files in the directory containing the source file named in the command line
4018 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4020 @ifclear vms
4021 @item -mbig-switch
4022 @cindex @option{-mbig-switch} (@command{gcc})
4023 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4024 This standard gcc switch causes the compiler to use larger offsets in its
4025 jump table representation for @code{case} statements.
4026 This may result in less efficient code, but is sometimes necessary
4027 (for example on HP-UX targets)
4028 @cindex HP-UX and @option{-mbig-switch} option
4029 in order to compile large and/or nested @code{case} statements.
4031 @item -o @var{file}
4032 @cindex @option{-o} (@command{gcc})
4033 This switch is used in @command{gcc} to redirect the generated object file
4034 and its associated ALI file. Beware of this switch with GNAT, because it may
4035 cause the object file and ALI file to have different names which in turn
4036 may confuse the binder and the linker.
4037 @end ifclear
4039 @item -nostdinc
4040 @cindex @option{-nostdinc} (@command{gcc})
4041 Inhibit the search of the default location for the GNAT Run Time
4042 Library (RTL) source files.
4044 @item -nostdlib
4045 @cindex @option{-nostdlib} (@command{gcc})
4046 Inhibit the search of the default location for the GNAT Run Time
4047 Library (RTL) ALI files.
4049 @ifclear vms
4050 @item -O[@var{n}]
4051 @cindex @option{-O} (@command{gcc})
4052 @var{n} controls the optimization level.
4054 @table @asis
4055 @item n = 0
4056 No optimization, the default setting if no @option{-O} appears
4058 @item n = 1
4059 Normal optimization, the default if you specify @option{-O} without
4060 an operand. A good compromise between code quality and compilation
4061 time.
4063 @item n = 2
4064 Extensive optimization, may improve execution time, possibly at the cost of
4065 substantially increased compilation time.
4067 @end table
4068 @end ifclear
4070 @ifset vms
4071 @item  /NOOPTIMIZE
4072 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4073 Equivalent to @option{/OPTIMIZE=NONE}.
4074 This is the default behavior in the absence of an @option{/OPTMIZE}
4075 qualifier.
4077 @item /OPTIMIZE[=(keyword[,...])]
4078 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4079 Selects the level of optimization for your program. The supported
4080 keywords are as follows:
4081 @table @code
4082 @item   ALL
4083 Perform most optimizations, including those that
4084 are expensive.
4085 This is the default if the @option{/OPTMIZE} qualifier is supplied
4086 without keyword options.
4088 @item   NONE
4089 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4091 @item SOME
4092 Perform some optimizations, but omit ones that are costly.
4094 @item   DEVELOPMENT
4095 Same as @code{SOME}.
4097 @item   UNROLL_LOOPS
4098 Try to unroll loops. This keyword may be specified together with
4099 any keyword above other than @code{NONE}. Loop unrolling
4100 usually, but not always, improves the performance of programs.
4101 @end table
4102 @end ifset
4104 @ifclear vms
4105 @item -pass-exit-codes
4106 @cindex @option{-pass-exit-codes} (@command{gcc})
4107 Catch exit codes from the compiler and use the most meaningful as
4108 exit status.
4109 @end ifclear
4111 @item --RTS=@var{rts-path}
4112 @cindex @option{--RTS} (@command{gcc})
4113 Specifies the default location of the runtime library. Same meaning as the
4114 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4116 @item ^-S^/ASM^
4117 @cindex @option{^-S^/ASM^} (@command{gcc})
4118 ^Used in place of @option{-c} to^Used to^
4119 cause the assembler source file to be
4120 generated, using @file{^.s^.S^} as the extension,
4121 instead of the object file.
4122 This may be useful if you need to examine the generated assembly code.
4124 @item ^-fverbose-asm^/VERBOSE_ASM^
4125 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4126 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4127 to cause the generated assembly code file to be annotated with variable
4128 names, making it significantly easier to follow.
4130 @item ^-v^/VERBOSE^
4131 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4132 Show commands generated by the @command{gcc} driver. Normally used only for
4133 debugging purposes or if you need to be sure what version of the
4134 compiler you are executing.
4136 @ifclear vms
4137 @item -V @var{ver}
4138 @cindex @option{-V} (@command{gcc})
4139 Execute @var{ver} version of the compiler. This is the @command{gcc}
4140 version, not the GNAT version.
4141 @end ifclear
4143 @item ^-w^NO_BACK_END_WARNINGS^
4144 @cindex @option{-w} (@command{gcc})
4145 Turn off warnings generated by the back end of the compiler. Use of
4146 this switch also causes the default for front end warnings to be set
4147 to suppress (as though @option{-gnatws} had appeared at the start of
4148 the options.
4150 @end table
4152 @ifclear vms
4153 You may combine a sequence of GNAT switches into a single switch. For
4154 example, the combined switch
4156 @cindex Combining GNAT switches
4157 @smallexample
4158 -gnatofi3
4159 @end smallexample
4161 @noindent
4162 is equivalent to specifying the following sequence of switches:
4164 @smallexample
4165 -gnato -gnatf -gnati3
4166 @end smallexample
4167 @end ifclear
4169 @c NEED TO CHECK THIS FOR VMS
4171 @noindent
4172 The following restrictions apply to the combination of switches
4173 in this manner:
4175 @itemize @bullet
4176 @item
4177 The switch @option{-gnatc} if combined with other switches must come
4178 first in the string.
4180 @item
4181 The switch @option{-gnats} if combined with other switches must come
4182 first in the string.
4184 @item
4185 The switches
4186 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4187 may not be combined with any other switches.
4189 @ifclear vms
4190 @item
4191 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4192 switch), then all further characters in the switch are interpreted
4193 as style modifiers (see description of @option{-gnaty}).
4195 @item
4196 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4197 switch), then all further characters in the switch are interpreted
4198 as debug flags (see description of @option{-gnatd}).
4200 @item
4201 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4202 switch), then all further characters in the switch are interpreted
4203 as warning mode modifiers (see description of @option{-gnatw}).
4205 @item
4206 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4207 switch), then all further characters in the switch are interpreted
4208 as validity checking options (see description of @option{-gnatV}).
4209 @end ifclear
4210 @end itemize
4212 @node Output and Error Message Control
4213 @subsection Output and Error Message Control
4214 @findex stderr
4216 @noindent
4217 The standard default format for error messages is called ``brief format''.
4218 Brief format messages are written to @file{stderr} (the standard error
4219 file) and have the following form:
4221 @smallexample
4222 e.adb:3:04: Incorrect spelling of keyword "function"
4223 e.adb:4:20: ";" should be "is"
4224 @end smallexample
4226 @noindent
4227 The first integer after the file name is the line number in the file,
4228 and the second integer is the column number within the line.
4229 @code{glide} can parse the error messages
4230 and point to the referenced character.
4231 The following switches provide control over the error message
4232 format:
4234 @table @option
4235 @c !sort!
4236 @item -gnatv
4237 @cindex @option{-gnatv} (@command{gcc})
4238 @findex stdout
4239 @ifclear vms
4240 The v stands for verbose.
4241 @end ifclear
4242 The effect of this setting is to write long-format error
4243 messages to @file{stdout} (the standard output file.
4244 The same program compiled with the
4245 @option{-gnatv} switch would generate:
4247 @smallexample
4248 @cartouche
4249 3. funcion X (Q : Integer)
4250    |
4251 >>> Incorrect spelling of keyword "function"
4252 4. return Integer;
4253                  |
4254 >>> ";" should be "is"
4255 @end cartouche
4256 @end smallexample
4258 @noindent
4259 The vertical bar indicates the location of the error, and the @samp{>>>}
4260 prefix can be used to search for error messages. When this switch is
4261 used the only source lines output are those with errors.
4263 @item -gnatl
4264 @cindex @option{-gnatl} (@command{gcc})
4265 @ifclear vms
4266 The @code{l} stands for list.
4267 @end ifclear
4268 This switch causes a full listing of
4269 the file to be generated. The output might look as follows:
4271 @smallexample
4272 @cartouche
4273  1. procedure E is
4274  2.    V : Integer;
4275  3.    funcion X (Q : Integer)
4276        |
4277     >>> Incorrect spelling of keyword "function"
4278  4.     return Integer;
4279                       |
4280     >>> ";" should be "is"
4281  5.    begin
4282  6.       return Q + Q;
4283  7.    end;
4284  8. begin
4285  9.    V := X + X;
4286 10.end E;
4287 @end cartouche
4288 @end smallexample
4290 @noindent
4291 @findex stderr
4292 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4293 standard output is redirected, a brief summary is written to
4294 @file{stderr} (standard error) giving the number of error messages and
4295 warning messages generated.
4297 @item -gnatU
4298 @cindex @option{-gnatU} (@command{gcc})
4299 This switch forces all error messages to be preceded by the unique
4300 string ``error:''. This means that error messages take a few more
4301 characters in space, but allows easy searching for and identification
4302 of error messages.
4304 @item -gnatb
4305 @cindex @option{-gnatb} (@command{gcc})
4306 @ifclear vms
4307 The @code{b} stands for brief.
4308 @end ifclear
4309 This switch causes GNAT to generate the
4310 brief format error messages to @file{stderr} (the standard error
4311 file) as well as the verbose
4312 format message or full listing (which as usual is written to
4313 @file{stdout} (the standard output file).
4315 @item -gnatm=@var{n}
4316 @cindex @option{-gnatm} (@command{gcc})
4317 @ifclear vms
4318 The @code{m} stands for maximum.
4319 @end ifclear
4320 @var{n} is a decimal integer in the
4321 range of 1 to 999 and limits the number of error messages to be
4322 generated. For example, using @option{-gnatm2} might yield
4324 @smallexample
4325 e.adb:3:04: Incorrect spelling of keyword "function"
4326 e.adb:5:35: missing ".."
4327 fatal error: maximum errors reached
4328 compilation abandoned
4329 @end smallexample
4331 @noindent
4332 Note that the equal sign is optional, so the switches
4333 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4335 @item -gnatf
4336 @cindex @option{-gnatf} (@command{gcc})
4337 @cindex Error messages, suppressing
4338 @ifclear vms
4339 The @code{f} stands for full.
4340 @end ifclear
4341 Normally, the compiler suppresses error messages that are likely to be
4342 redundant. This switch causes all error
4343 messages to be generated. In particular, in the case of
4344 references to undefined variables. If a given variable is referenced
4345 several times, the normal format of messages is
4346 @smallexample
4347 e.adb:7:07: "V" is undefined (more references follow)
4348 @end smallexample
4350 @noindent
4351 where the parenthetical comment warns that there are additional
4352 references to the variable @code{V}. Compiling the same program with the
4353 @option{-gnatf} switch yields
4355 @smallexample
4356 e.adb:7:07: "V" is undefined
4357 e.adb:8:07: "V" is undefined
4358 e.adb:8:12: "V" is undefined
4359 e.adb:8:16: "V" is undefined
4360 e.adb:9:07: "V" is undefined
4361 e.adb:9:12: "V" is undefined
4362 @end smallexample
4364 @noindent
4365 The @option{-gnatf} switch also generates additional information for
4366 some error messages.  Some examples are:
4368 @itemize @bullet
4369 @item
4370 Full details on entities not available in high integrity mode
4371 @item
4372 Details on possibly non-portable unchecked conversion
4373 @item
4374 List possible interpretations for ambiguous calls
4375 @item
4376 Additional details on incorrect parameters
4377 @end itemize
4379 @item -gnatq
4380 @cindex @option{-gnatq} (@command{gcc})
4381 @ifclear vms
4382 The @code{q} stands for quit (really ``don't quit'').
4383 @end ifclear
4384 In normal operation mode, the compiler first parses the program and
4385 determines if there are any syntax errors. If there are, appropriate
4386 error messages are generated and compilation is immediately terminated.
4387 This switch tells
4388 GNAT to continue with semantic analysis even if syntax errors have been
4389 found. This may enable the detection of more errors in a single run. On
4390 the other hand, the semantic analyzer is more likely to encounter some
4391 internal fatal error when given a syntactically invalid tree.
4393 @item -gnatQ
4394 @cindex @option{-gnatQ} (@command{gcc})
4395 In normal operation mode, the @file{ALI} file is not generated if any
4396 illegalities are detected in the program. The use of @option{-gnatQ} forces
4397 generation of the @file{ALI} file. This file is marked as being in
4398 error, so it cannot be used for binding purposes, but it does contain
4399 reasonably complete cross-reference information, and thus may be useful
4400 for use by tools (e.g. semantic browsing tools or integrated development
4401 environments) that are driven from the @file{ALI} file. This switch
4402 implies @option{-gnatq}, since the semantic phase must be run to get a
4403 meaningful ALI file.
4405 In addition, if @option{-gnatt} is also specified, then the tree file is
4406 generated even if there are illegalities. It may be useful in this case
4407 to also specify @option{-gnatq} to ensure that full semantic processing
4408 occurs. The resulting tree file can be processed by ASIS, for the purpose
4409 of providing partial information about illegal units, but if the error
4410 causes the tree to be badly malformed, then ASIS may crash during the
4411 analysis.
4413 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4414 being in error, @command{gnatmake} will attempt to recompile the source when it
4415 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4417 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4418 since ALI files are never generated if @option{-gnats} is set.
4420 @end table
4422 @node Warning Message Control
4423 @subsection Warning Message Control
4424 @cindex Warning messages
4425 @noindent
4426 In addition to error messages, which correspond to illegalities as defined
4427 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4428 situations.
4430 First, the compiler considers some constructs suspicious and generates a
4431 warning message to alert you to a possible error. Second, if the
4432 compiler detects a situation that is sure to raise an exception at
4433 run time, it generates a warning message. The following shows an example
4434 of warning messages:
4435 @smallexample
4436 e.adb:4:24: warning: creation of object may raise Storage_Error
4437 e.adb:10:17: warning: static value out of range
4438 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4439 @end smallexample
4441 @noindent
4442 GNAT considers a large number of situations as appropriate
4443 for the generation of warning messages. As always, warnings are not
4444 definite indications of errors. For example, if you do an out-of-range
4445 assignment with the deliberate intention of raising a
4446 @code{Constraint_Error} exception, then the warning that may be
4447 issued does not indicate an error. Some of the situations for which GNAT
4448 issues warnings (at least some of the time) are given in the following
4449 list. This list is not complete, and new warnings are often added to
4450 subsequent versions of GNAT. The list is intended to give a general idea
4451 of the kinds of warnings that are generated.
4453 @itemize @bullet
4454 @item
4455 Possible infinitely recursive calls
4457 @item
4458 Out-of-range values being assigned
4460 @item
4461 Possible order of elaboration problems
4463 @item
4464 Unreachable code
4466 @item
4467 Fixed-point type declarations with a null range
4469 @item
4470 Direct_IO or Sequential_IO instantiated with a type that has access values
4472 @item
4473 Variables that are never assigned a value
4475 @item
4476 Variables that are referenced before being initialized
4478 @item
4479 Task entries with no corresponding @code{accept} statement
4481 @item
4482 Duplicate accepts for the same task entry in a @code{select}
4484 @item
4485 Objects that take too much storage
4487 @item
4488 Unchecked conversion between types of differing sizes
4490 @item
4491 Missing @code{return} statement along some execution path in a function
4493 @item
4494 Incorrect (unrecognized) pragmas
4496 @item
4497 Incorrect external names
4499 @item
4500 Allocation from empty storage pool
4502 @item
4503 Potentially blocking operation in protected type
4505 @item
4506 Suspicious parenthesization of expressions
4508 @item
4509 Mismatching bounds in an aggregate
4511 @item
4512 Attempt to return local value by reference
4514 @item
4515 Premature instantiation of a generic body
4517 @item
4518 Attempt to pack aliased components
4520 @item
4521 Out of bounds array subscripts
4523 @item
4524 Wrong length on string assignment
4526 @item
4527 Violations of style rules if style checking is enabled
4529 @item
4530 Unused @code{with} clauses
4532 @item
4533 @code{Bit_Order} usage that does not have any effect
4535 @item
4536 @code{Standard.Duration} used to resolve universal fixed expression
4538 @item
4539 Dereference of possibly null value
4541 @item
4542 Declaration that is likely to cause storage error
4544 @item
4545 Internal GNAT unit @code{with}'ed by application unit
4547 @item
4548 Values known to be out of range at compile time
4550 @item
4551 Unreferenced labels and variables
4553 @item
4554 Address overlays that could clobber memory
4556 @item
4557 Unexpected initialization when address clause present
4559 @item
4560 Bad alignment for address clause
4562 @item
4563 Useless type conversions
4565 @item
4566 Redundant assignment statements and other redundant constructs
4568 @item
4569 Useless exception handlers
4571 @item
4572 Accidental hiding of name by child unit
4574 @item
4575 Access before elaboration detected at compile time
4577 @item
4578 A range in a @code{for} loop that is known to be null or might be null
4580 @end itemize
4582 @noindent
4583 The following switches are available to control the handling of
4584 warning messages:
4586 @table @option
4587 @c !sort!
4588 @item -gnatwa
4589 @emph{Activate all optional errors.}
4590 @cindex @option{-gnatwa} (@command{gcc})
4591 This switch activates most optional warning messages, see remaining list
4592 in this section for details on optional warning messages that can be
4593 individually controlled.  The warnings that are not turned on by this
4594 switch are
4595 @option{-gnatwd} (implicit dereferencing),
4596 @option{-gnatwh} (hiding),
4597 and @option{-gnatwl} (elaboration warnings).
4598 All other optional warnings are turned on.
4600 @item -gnatwA
4601 @emph{Suppress all optional errors.}
4602 @cindex @option{-gnatwA} (@command{gcc})
4603 This switch suppresses all optional warning messages, see remaining list
4604 in this section for details on optional warning messages that can be
4605 individually controlled.
4607 @item -gnatwb
4608 @emph{Activate warnings on bad fixed values.}
4609 @cindex @option{-gnatwb} (@command{gcc})
4610 @cindex Bad fixed values
4611 @cindex Fixed-point Small value
4612 @cindex Small value
4613 This switch activates warnings for static fixed-point expressions whose
4614 value is not an exact multiple of Small. Such values are implementation
4615 dependent, since an implementation is free to choose either of the multiples
4616 that surround the value. GNAT always chooses the closer one, but this is not
4617 required behavior, and it is better to specify a value that is an exact
4618 multiple, ensuring predictable execution. The default is that such warnings
4619 are not generated.
4621 @item -gnatwB
4622 @emph{Suppress warnings on bad fixed values.}
4623 @cindex @option{-gnatwB} (@command{gcc})
4624 This switch suppresses warnings for static fixed-point expressions whose
4625 value is not an exact multiple of Small.
4627 @item -gnatwc
4628 @emph{Activate warnings on conditionals.}
4629 @cindex @option{-gnatwc} (@command{gcc})
4630 @cindex Conditionals, constant
4631 This switch activates warnings for conditional expressions used in
4632 tests that are known to be True or False at compile time. The default
4633 is that such warnings are not generated.
4634 Note that this warning does
4635 not get issued for the use of boolean variables or constants whose
4636 values are known at compile time, since this is a standard technique
4637 for conditional compilation in Ada, and this would generate too many
4638 ``false positive'' warnings.
4640 This warning option also activates a special test for comparisons using
4641 the operators >= and <=. If the compiler can tell that only the equality
4642 condition is posible, then it will warn that the > or < part of the test
4643 is useless and that the operator could be replaced by =. An example would
4644 be comparing a Natural variable <= 0.
4646 This warning can also be turned on using @option{-gnatwa}.
4648 @item -gnatwC
4649 @emph{Suppress warnings on conditionals.}
4650 @cindex @option{-gnatwC} (@command{gcc})
4651 This switch suppresses warnings for conditional expressions used in
4652 tests that are known to be True or False at compile time.
4654 @item -gnatwd
4655 @emph{Activate warnings on implicit dereferencing.}
4656 @cindex @option{-gnatwd} (@command{gcc})
4657 If this switch is set, then the use of a prefix of an access type
4658 in an indexed component, slice, or selected component without an
4659 explicit @code{.all} will generate a warning. With this warning
4660 enabled, access checks occur only at points where an explicit
4661 @code{.all} appears in the source code (assuming no warnings are
4662 generated as a result of this switch). The default is that such
4663 warnings are not generated.
4664 Note that @option{-gnatwa} does not affect the setting of
4665 this warning option.
4667 @item -gnatwD
4668 @emph{Suppress warnings on implicit dereferencing.}
4669 @cindex @option{-gnatwD} (@command{gcc})
4670 @cindex Implicit dereferencing
4671 @cindex Dereferencing, implicit
4672 This switch suppresses warnings for implicit dereferences in
4673 indexed components, slices, and selected components.
4675 @item -gnatwe
4676 @emph{Treat warnings as errors.}
4677 @cindex @option{-gnatwe} (@command{gcc})
4678 @cindex Warnings, treat as error
4679 This switch causes warning messages to be treated as errors.
4680 The warning string still appears, but the warning messages are counted
4681 as errors, and prevent the generation of an object file.
4683 @item -gnatwf
4684 @emph{Activate warnings on unreferenced formals.}
4685 @cindex @option{-gnatwf} (@command{gcc})
4686 @cindex Formals, unreferenced
4687 This switch causes a warning to be generated if a formal parameter
4688 is not referenced in the body of the subprogram. This warning can
4689 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4691 @item -gnatwF
4692 @emph{Suppress warnings on unreferenced formals.}
4693 @cindex @option{-gnatwF} (@command{gcc})
4694 This switch suppresses warnings for unreferenced formal
4695 parameters. Note that the
4696 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4697 effect of warning on unreferenced entities other than subprogram
4698 formals.
4700 @item -gnatwg
4701 @emph{Activate warnings on unrecognized pragmas.}
4702 @cindex @option{-gnatwg} (@command{gcc})
4703 @cindex Pragmas, unrecognized
4704 This switch causes a warning to be generated if an unrecognized
4705 pragma is encountered. Apart from issuing this warning, the
4706 pragma is ignored and has no effect. This warning can
4707 also be turned on using @option{-gnatwa}. The default
4708 is that such warnings are issued (satisfying the Ada Reference
4709 Manual requirement that such warnings appear).
4711 @item -gnatwG
4712 @emph{Suppress warnings on unrecognized pragmas.}
4713 @cindex @option{-gnatwG} (@command{gcc})
4714 This switch suppresses warnings for unrecognized pragmas.
4716 @item -gnatwh
4717 @emph{Activate warnings on hiding.}
4718 @cindex @option{-gnatwh} (@command{gcc})
4719 @cindex Hiding of Declarations
4720 This switch activates warnings on hiding declarations.
4721 A declaration is considered hiding
4722 if it is for a non-overloadable entity, and it declares an entity with the
4723 same name as some other entity that is directly or use-visible. The default
4724 is that such warnings are not generated.
4725 Note that @option{-gnatwa} does not affect the setting of this warning option.
4727 @item -gnatwH
4728 @emph{Suppress warnings on hiding.}
4729 @cindex @option{-gnatwH} (@command{gcc})
4730 This switch suppresses warnings on hiding declarations.
4732 @item -gnatwi
4733 @emph{Activate warnings on implementation units.}
4734 @cindex @option{-gnatwi} (@command{gcc})
4735 This switch activates warnings for a @code{with} of an internal GNAT
4736 implementation unit, defined as any unit from the @code{Ada},
4737 @code{Interfaces}, @code{GNAT},
4738 ^^@code{DEC},^ or @code{System}
4739 hierarchies that is not
4740 documented in either the Ada Reference Manual or the GNAT
4741 Programmer's Reference Manual. Such units are intended only
4742 for internal implementation purposes and should not be @code{with}'ed
4743 by user programs. The default is that such warnings are generated
4744 This warning can also be turned on using @option{-gnatwa}.
4746 @item -gnatwI
4747 @emph{Disable warnings on implementation units.}
4748 @cindex @option{-gnatwI} (@command{gcc})
4749 This switch disables warnings for a @code{with} of an internal GNAT
4750 implementation unit.
4752 @item -gnatwj
4753 @emph{Activate warnings on obsolescent features (Annex J).}
4754 @cindex @option{-gnatwj} (@command{gcc})
4755 @cindex Features, obsolescent
4756 @cindex Obsolescent features
4757 If this warning option is activated, then warnings are generated for
4758 calls to subprograms marked with @code{pragma Obsolescent} and
4759 for use of features in Annex J of the Ada Reference Manual. In the
4760 case of Annex J, not all features are flagged. In particular use
4761 of the renamed packages (like @code{Text_IO}) and use of package
4762 @code{ASCII} are not flagged, since these are very common and
4763 would generate many annoying positive warnings. The default is that
4764 such warnings are not generated.
4766 In addition to the above cases, warnings are also generated for
4767 GNAT features that have been provided in past versions but which
4768 have been superseded (typically by features in the new Ada standard).
4769 For example, @code{pragma Ravenscar} will be flagged since its
4770 function is replaced by @code{pragma Profile(Ravenscar)}.
4772 Note that this warning option functions differently from the
4773 restriction @code{No_Obsolescent_Features} in two respects.
4774 First, the restriction applies only to annex J features.
4775 Second, the restriction does flag uses of package @code{ASCII}.
4777 @item -gnatwJ
4778 @emph{Suppress warnings on obsolescent features (Annex J).}
4779 @cindex @option{-gnatwJ} (@command{gcc})
4780 This switch disables warnings on use of obsolescent features.
4782 @item -gnatwk
4783 @emph{Activate warnings on variables that could be constants.}
4784 @cindex @option{-gnatwk} (@command{gcc})
4785 This switch activates warnings for variables that are initialized but
4786 never modified, and then could be declared constants.
4788 @item -gnatwK
4789 @emph{Suppress warnings on variables that could be constants.}
4790 @cindex @option{-gnatwK} (@command{gcc})
4791 This switch disables warnings on variables that could be declared constants.
4793 @item -gnatwl
4794 @emph{Activate warnings for missing elaboration pragmas.}
4795 @cindex @option{-gnatwl} (@command{gcc})
4796 @cindex Elaboration, warnings
4797 This switch activates warnings on missing
4798 @code{Elaborate_All} and @code{Elaborate} pragmas.
4799 See the section in this guide on elaboration checking for details on
4800 when such pragmas should be used. Warnings are also generated if you
4801 are using the static mode of elaboration, and a @code{pragma Elaborate}
4802 is encountered. The default is that such warnings
4803 are not generated.
4804 This warning is not automatically turned on by the use of @option{-gnatwa}.
4806 @item -gnatwL
4807 @emph{Suppress warnings for missing elaboration pragmas.}
4808 @cindex @option{-gnatwL} (@command{gcc})
4809 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4810 See the section in this guide on elaboration checking for details on
4811 when such pragmas should be used.
4813 @item -gnatwm
4814 @emph{Activate warnings on modified but unreferenced variables.}
4815 @cindex @option{-gnatwm} (@command{gcc})
4816 This switch activates warnings for variables that are assigned (using
4817 an initialization value or with one or more assignment statements) but
4818 whose value is never read. The warning is suppressed for volatile
4819 variables and also for variables that are renamings of other variables
4820 or for which an address clause is given.
4821 This warning can also be turned on using @option{-gnatwa}.
4823 @item -gnatwM
4824 @emph{Disable warnings on modified but unreferenced variables.}
4825 @cindex @option{-gnatwM} (@command{gcc})
4826 This switch disables warnings for variables that are assigned or
4827 initialized, but never read.
4829 @item -gnatwn
4830 @emph{Set normal warnings mode.}
4831 @cindex @option{-gnatwn} (@command{gcc})
4832 This switch sets normal warning mode, in which enabled warnings are
4833 issued and treated as warnings rather than errors. This is the default
4834 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4835 an explicit @option{-gnatws} or
4836 @option{-gnatwe}. It also cancels the effect of the
4837 implicit @option{-gnatwe} that is activated by the
4838 use of @option{-gnatg}.
4840 @item -gnatwo
4841 @emph{Activate warnings on address clause overlays.}
4842 @cindex @option{-gnatwo} (@command{gcc})
4843 @cindex Address Clauses, warnings
4844 This switch activates warnings for possibly unintended initialization
4845 effects of defining address clauses that cause one variable to overlap
4846 another. The default is that such warnings are generated.
4847 This warning can also be turned on using @option{-gnatwa}.
4849 @item -gnatwO
4850 @emph{Suppress warnings on address clause overlays.}
4851 @cindex @option{-gnatwO} (@command{gcc})
4852 This switch suppresses warnings on possibly unintended initialization
4853 effects of defining address clauses that cause one variable to overlap
4854 another.
4856 @item -gnatwp
4857 @emph{Activate warnings on ineffective pragma Inlines.}
4858 @cindex @option{-gnatwp} (@command{gcc})
4859 @cindex Inlining, warnings
4860 This switch activates warnings for failure of front end inlining
4861 (activated by @option{-gnatN}) to inline a particular call. There are
4862 many reasons for not being able to inline a call, including most
4863 commonly that the call is too complex to inline.
4864 This warning can also be turned on using @option{-gnatwa}.
4866 @item -gnatwP
4867 @emph{Suppress warnings on ineffective pragma Inlines.}
4868 @cindex @option{-gnatwP} (@command{gcc})
4869 This switch suppresses warnings on ineffective pragma Inlines. If the
4870 inlining mechanism cannot inline a call, it will simply ignore the
4871 request silently.
4873 @item -gnatwr
4874 @emph{Activate warnings on redundant constructs.}
4875 @cindex @option{-gnatwr} (@command{gcc})
4876 This switch activates warnings for redundant constructs. The following
4877 is the current list of constructs regarded as redundant:
4878 This warning can also be turned on using @option{-gnatwa}.
4880 @itemize @bullet
4881 @item
4882 Assignment of an item to itself.
4883 @item
4884 Type conversion that converts an expression to its own type.
4885 @item
4886 Use of the attribute @code{Base} where @code{typ'Base} is the same
4887 as @code{typ}.
4888 @item
4889 Use of pragma @code{Pack} when all components are placed by a record
4890 representation clause.
4891 @item
4892 Exception handler containing only a reraise statement (raise with no
4893 operand) which has no effect.
4894 @item
4895 Use of the operator abs on an operand that is known at compile time
4896 to be non-negative
4897 @item
4898 Comparison of boolean expressions to an explicit True value.
4899 @end itemize
4901 @item -gnatwR
4902 @emph{Suppress warnings on redundant constructs.}
4903 @cindex @option{-gnatwR} (@command{gcc})
4904 This switch suppresses warnings for redundant constructs.
4906 @item -gnatws
4907 @emph{Suppress all warnings.}
4908 @cindex @option{-gnatws} (@command{gcc})
4909 This switch completely suppresses the
4910 output of all warning messages from the GNAT front end.
4911 Note that it does not suppress warnings from the @command{gcc} back end.
4912 To suppress these back end warnings as well, use the switch @option{-w}
4913 in addition to @option{-gnatws}.
4915 @item -gnatwu
4916 @emph{Activate warnings on unused entities.}
4917 @cindex @option{-gnatwu} (@command{gcc})
4918 This switch activates warnings to be generated for entities that
4919 are declared but not referenced, and for units that are @code{with}'ed
4920 and not
4921 referenced. In the case of packages, a warning is also generated if
4922 no entities in the package are referenced. This means that if the package
4923 is referenced but the only references are in @code{use}
4924 clauses or @code{renames}
4925 declarations, a warning is still generated. A warning is also generated
4926 for a generic package that is @code{with}'ed but never instantiated.
4927 In the case where a package or subprogram body is compiled, and there
4928 is a @code{with} on the corresponding spec
4929 that is only referenced in the body,
4930 a warning is also generated, noting that the
4931 @code{with} can be moved to the body. The default is that
4932 such warnings are not generated.
4933 This switch also activates warnings on unreferenced formals
4934 (it includes the effect of @option{-gnatwf}).
4935 This warning can also be turned on using @option{-gnatwa}.
4937 @item -gnatwU
4938 @emph{Suppress warnings on unused entities.}
4939 @cindex @option{-gnatwU} (@command{gcc})
4940 This switch suppresses warnings for unused entities and packages.
4941 It also turns off warnings on unreferenced formals (and thus includes
4942 the effect of @option{-gnatwF}).
4944 @item -gnatwv
4945 @emph{Activate warnings on unassigned variables.}
4946 @cindex @option{-gnatwv} (@command{gcc})
4947 @cindex Unassigned variable warnings
4948 This switch activates warnings for access to variables which
4949 may not be properly initialized. The default is that
4950 such warnings are generated.
4952 @item -gnatwV
4953 @emph{Suppress warnings on unassigned variables.}
4954 @cindex @option{-gnatwV} (@command{gcc})
4955 This switch suppresses warnings for access to variables which
4956 may not be properly initialized.
4958 @item -gnatwy
4959 @emph{Activate warnings for Ada 2005 compatibility issues.}
4960 @cindex @option{-gnatwy} (@command{gcc})
4961 @cindex Ada 2005 compatibility issues warnings
4962 For the most part Ada 2005 is upwards compatible with Ada 95,
4963 but there are some exceptions (for example the fact that
4964 @code{interface} is now a reserved word in Ada 2005). This
4965 switch activates several warnings to help in identifying
4966 and correcting such incompatibilities. The default is that
4967 these warnings are generated. Note that at one point Ada 2005
4968 was called Ada 0Y, hence the choice of character.
4970 @item -gnatwY
4971 @emph{Disable warnings for Ada 2005 compatibility issues.}
4972 @cindex @option{-gnatwY} (@command{gcc})
4973 @cindex Ada 2005 compatibility issues warnings
4974 This switch suppresses several warnings intended to help in identifying
4975 incompatibilities between Ada 95 and Ada 2005.
4977 @item -gnatwx
4978 @emph{Activate warnings on Export/Import pragmas.}
4979 @cindex @option{-gnatwx} (@command{gcc})
4980 @cindex Export/Import pragma warnings
4981 This switch activates warnings on Export/Import pragmas when
4982 the compiler detects a possible conflict between the Ada and
4983 foreign language calling sequences. For example, the use of
4984 default parameters in a convention C procedure is dubious
4985 because the C compiler cannot supply the proper default, so
4986 a warning is issued. The default is that such warnings are
4987 generated.
4989 @item -gnatwX
4990 @emph{Suppress warnings on Export/Import pragmas.}
4991 @cindex @option{-gnatwX} (@command{gcc})
4992 This switch suppresses warnings on Export/Import pragmas.
4993 The sense of this is that you are telling the compiler that
4994 you know what you are doing in writing the pragma, and it
4995 should not complain at you.
4997 @item -gnatwz
4998 @emph{Activate warnings on unchecked conversions.}
4999 @cindex @option{-gnatwz} (@command{gcc})
5000 @cindex Unchecked_Conversion warnings
5001 This switch activates warnings for unchecked conversions
5002 where the types are known at compile time to have different
5003 sizes. The default
5004 is that such warnings are generated.
5006 @item -gnatwZ
5007 @emph{Suppress warnings on unchecked conversions.}
5008 @cindex @option{-gnatwZ} (@command{gcc})
5009 This switch suppresses warnings for unchecked conversions
5010 where the types are known at compile time to have different
5011 sizes.
5013 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5014 @cindex @option{-Wuninitialized}
5015 The warnings controlled by the @option{-gnatw} switch are generated by the
5016 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5017 can provide additional warnings. One such useful warning is provided by
5018 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5019 conjunction with tunrning on optimization mode. This causes the flow
5020 analysis circuits of the back end optimizer to output additional
5021 warnings about uninitialized variables.
5023 @item ^-w^/NO_BACK_END_WARNINGS^
5024 @cindex @option{-w}
5025 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5026 code generator detects a number of warning situations that are missed
5027 by the @option{GNAT} front end, and this switch can be used to suppress them.
5028 The use of this switch also sets the default front end warning mode to
5029 @option{-gnatws}, that is, front end warnings suppressed as well.
5031 @end table
5033 @noindent
5034 @ifclear vms
5035 A string of warning parameters can be used in the same parameter. For example:
5037 @smallexample
5038 -gnatwaLe
5039 @end smallexample
5041 @noindent
5042 will turn on all optional warnings except for elaboration pragma warnings,
5043 and also specify that warnings should be treated as errors.
5044 @end ifclear
5045 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5047 @table @option
5048 @c !sort!
5049 @item -gnatwC
5050 @item -gnatwD
5051 @item -gnatwF
5052 @item -gnatwg
5053 @item -gnatwH
5054 @item -gnatwi
5055 @item -gnatwJ
5056 @item -gnatwK
5057 @item -gnatwL
5058 @item -gnatwM
5059 @item -gnatwn
5060 @item -gnatwo
5061 @item -gnatwP
5062 @item -gnatwR
5063 @item -gnatwU
5064 @item -gnatwv
5065 @item -gnatwz
5066 @item -gnatwx
5068 @end table
5070 @node Debugging and Assertion Control
5071 @subsection Debugging and Assertion Control
5073 @table @option
5074 @item -gnata
5075 @cindex @option{-gnata} (@command{gcc})
5076 @findex Assert
5077 @findex Debug
5078 @cindex Assertions
5080 @noindent
5081 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5082 are ignored. This switch, where @samp{a} stands for assert, causes
5083 @code{Assert} and @code{Debug} pragmas to be activated.
5085 The pragmas have the form:
5087 @smallexample
5088 @cartouche
5089    @b{pragma} Assert (@var{Boolean-expression} [,
5090                       @var{static-string-expression}])
5091    @b{pragma} Debug (@var{procedure call})
5092 @end cartouche
5093 @end smallexample
5095 @noindent
5096 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5097 If the result is @code{True}, the pragma has no effect (other than
5098 possible side effects from evaluating the expression). If the result is
5099 @code{False}, the exception @code{Assert_Failure} declared in the package
5100 @code{System.Assertions} is
5101 raised (passing @var{static-string-expression}, if present, as the
5102 message associated with the exception). If no string expression is
5103 given the default is a string giving the file name and line number
5104 of the pragma.
5106 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5107 @code{pragma Debug} may appear within a declaration sequence, allowing
5108 debugging procedures to be called between declarations.
5110 @ifset vms
5111 @item /DEBUG[=debug-level]
5112 @itemx  /NODEBUG
5113 Specifies how much debugging information is to be included in
5114 the resulting object file where 'debug-level' is one of the following:
5115 @table @code
5116 @item   TRACEBACK
5117 Include both debugger symbol records and traceback
5118 the object file.
5119 This is the default setting.
5120 @item   ALL
5121 Include both debugger symbol records and traceback in
5122 object file.
5123 @item   NONE
5124 Excludes both debugger symbol records and traceback
5125 the object file. Same as /NODEBUG.
5126 @item   SYMBOLS
5127 Includes only debugger symbol records in the object
5128 file. Note that this doesn't include traceback information.
5129 @end table
5130 @end ifset
5131 @end table
5133 @node Validity Checking
5134 @subsection Validity Checking
5135 @findex Validity Checking
5137 @noindent
5138 The Ada 95 Reference Manual has specific requirements for checking
5139 for invalid values. In particular, RM 13.9.1 requires that the
5140 evaluation of invalid values (for example from unchecked conversions),
5141 not result in erroneous execution. In GNAT, the result of such an
5142 evaluation in normal default mode is to either use the value
5143 unmodified, or to raise Constraint_Error in those cases where use
5144 of the unmodified value would cause erroneous execution. The cases
5145 where unmodified values might lead to erroneous execution are case
5146 statements (where a wild jump might result from an invalid value),
5147 and subscripts on the left hand side (where memory corruption could
5148 occur as a result of an invalid value).
5150 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5151 checking mode.
5152 @ifclear vms
5153 The @code{x} argument is a string of letters that
5154 indicate validity checks that are performed or not performed in addition
5155 to the default checks described above.
5156 @end ifclear
5157 @ifset vms
5158 The options allowed for this qualifier
5159 indicate validity checks that are performed or not performed in addition
5160 to the default checks described above.
5161 @end ifset
5163 @table @option
5164 @c !sort!
5165 @item -gnatVa
5166 @emph{All validity checks.}
5167 @cindex @option{-gnatVa} (@command{gcc})
5168 All validity checks are turned on.
5169 @ifclear vms
5170 That is, @option{-gnatVa} is
5171 equivalent to @option{gnatVcdfimorst}.
5172 @end ifclear
5174 @item -gnatVc
5175 @emph{Validity checks for copies.}
5176 @cindex @option{-gnatVc} (@command{gcc})
5177 The right hand side of assignments, and the initializing values of
5178 object declarations are validity checked.
5180 @item -gnatVd
5181 @emph{Default (RM) validity checks.}
5182 @cindex @option{-gnatVd} (@command{gcc})
5183 Some validity checks are done by default following normal Ada semantics
5184 (RM 13.9.1 (9-11)).
5185 A check is done in case statements that the expression is within the range
5186 of the subtype. If it is not, Constraint_Error is raised.
5187 For assignments to array components, a check is done that the expression used
5188 as index is within the range. If it is not, Constraint_Error is raised.
5189 Both these validity checks may be turned off using switch @option{-gnatVD}.
5190 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5191 switch @option{-gnatVd} will leave the checks turned on.
5192 Switch @option{-gnatVD} should be used only if you are sure that all such
5193 expressions have valid values. If you use this switch and invalid values
5194 are present, then the program is erroneous, and wild jumps or memory
5195 overwriting may occur.
5197 @item -gnatVf
5198 @emph{Validity checks for floating-point values.}
5199 @cindex @option{-gnatVf} (@command{gcc})
5200 In the absence of this switch, validity checking occurs only for discrete
5201 values. If @option{-gnatVf} is specified, then validity checking also applies
5202 for floating-point values, and NaN's and infinities are considered invalid,
5203 as well as out of range values for constrained types. Note that this means
5204 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5205 in which floating-point values are checked depends on the setting of other
5206 options. For example,
5207 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5208 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5209 (the order does not matter) specifies that floating-point parameters of mode
5210 @code{in} should be validity checked.
5212 @item -gnatVi
5213 @emph{Validity checks for @code{in} mode parameters}
5214 @cindex @option{-gnatVi} (@command{gcc})
5215 Arguments for parameters of mode @code{in} are validity checked in function
5216 and procedure calls at the point of call.
5218 @item -gnatVm
5219 @emph{Validity checks for @code{in out} mode parameters.}
5220 @cindex @option{-gnatVm} (@command{gcc})
5221 Arguments for parameters of mode @code{in out} are validity checked in
5222 procedure calls at the point of call. The @code{'m'} here stands for
5223 modify, since this concerns parameters that can be modified by the call.
5224 Note that there is no specific option to test @code{out} parameters,
5225 but any reference within the subprogram will be tested in the usual
5226 manner, and if an invalid value is copied back, any reference to it
5227 will be subject to validity checking.
5229 @item -gnatVn
5230 @emph{No validity checks.}
5231 @cindex @option{-gnatVn} (@command{gcc})
5232 This switch turns off all validity checking, including the default checking
5233 for case statements and left hand side subscripts. Note that the use of
5234 the switch @option{-gnatp} suppresses all run-time checks, including
5235 validity checks, and thus implies @option{-gnatVn}. When this switch
5236 is used, it cancels any other @option{-gnatV} previously issued.
5238 @item -gnatVo
5239 @emph{Validity checks for operator and attribute operands.}
5240 @cindex @option{-gnatVo} (@command{gcc})
5241 Arguments for predefined operators and attributes are validity checked.
5242 This includes all operators in package @code{Standard},
5243 the shift operators defined as intrinsic in package @code{Interfaces}
5244 and operands for attributes such as @code{Pos}. Checks are also made
5245 on individual component values for composite comparisons.
5247 @item -gnatVp
5248 @emph{Validity checks for parameters.}
5249 @cindex @option{-gnatVp} (@command{gcc})
5250 This controls the treatment of parameters within a subprogram (as opposed
5251 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5252 of parameters on a call. If either of these call options is used, then
5253 normally an assumption is made within a subprogram that the input arguments
5254 have been validity checking at the point of call, and do not need checking
5255 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5256 is not made, and parameters are not assumed to be valid, so their validity
5257 will be checked (or rechecked) within the subprogram.
5259 @item -gnatVr
5260 @emph{Validity checks for function returns.}
5261 @cindex @option{-gnatVr} (@command{gcc})
5262 The expression in @code{return} statements in functions is validity
5263 checked.
5265 @item -gnatVs
5266 @emph{Validity checks for subscripts.}
5267 @cindex @option{-gnatVs} (@command{gcc})
5268 All subscripts expressions are checked for validity, whether they appear
5269 on the right side or left side (in default mode only left side subscripts
5270 are validity checked).
5272 @item -gnatVt
5273 @emph{Validity checks for tests.}
5274 @cindex @option{-gnatVt} (@command{gcc})
5275 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5276 statements are checked, as well as guard expressions in entry calls.
5278 @end table
5280 @noindent
5281 The @option{-gnatV} switch may be followed by
5282 ^a string of letters^a list of options^
5283 to turn on a series of validity checking options.
5284 For example,
5285 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5286 specifies that in addition to the default validity checking, copies and
5287 function return expressions are to be validity checked.
5288 In order to make it easier
5289 to specify the desired combination of effects,
5290 @ifclear vms
5291 the upper case letters @code{CDFIMORST} may
5292 be used to turn off the corresponding lower case option.
5293 @end ifclear
5294 @ifset vms
5295 the prefix @code{NO} on an option turns off the corresponding validity
5296 checking:
5297 @itemize @bullet
5298 @item @code{NOCOPIES}
5299 @item @code{NODEFAULT}
5300 @item @code{NOFLOATS}
5301 @item @code{NOIN_PARAMS}
5302 @item @code{NOMOD_PARAMS}
5303 @item @code{NOOPERANDS}
5304 @item @code{NORETURNS}
5305 @item @code{NOSUBSCRIPTS}
5306 @item @code{NOTESTS}
5307 @end itemize
5308 @end ifset
5309 Thus
5310 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5311 turns on all validity checking options except for
5312 checking of @code{@b{in out}} procedure arguments.
5314 The specification of additional validity checking generates extra code (and
5315 in the case of @option{-gnatVa} the code expansion can be substantial.
5316 However, these additional checks can be very useful in detecting
5317 uninitialized variables, incorrect use of unchecked conversion, and other
5318 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5319 is useful in conjunction with the extra validity checking, since this
5320 ensures that wherever possible uninitialized variables have invalid values.
5322 See also the pragma @code{Validity_Checks} which allows modification of
5323 the validity checking mode at the program source level, and also allows for
5324 temporary disabling of validity checks.
5326 @node Style Checking
5327 @subsection Style Checking
5328 @findex Style checking
5330 @noindent
5331 The @option{-gnaty^x^(option,option,...)^} switch
5332 @cindex @option{-gnaty} (@command{gcc})
5333 causes the compiler to
5334 enforce specified style rules. A limited set of style rules has been used
5335 in writing the GNAT sources themselves. This switch allows user programs
5336 to activate all or some of these checks. If the source program fails a
5337 specified style check, an appropriate warning message is given, preceded by
5338 the character sequence ``(style)''.
5339 @ifset vms
5340 @code{(option,option,...)} is a sequence of keywords
5341 @end ifset
5342 @ifclear vms
5343 The string @var{x} is a sequence of letters or digits
5344 @end ifclear
5345 indicating the particular style
5346 checks to be performed. The following checks are defined:
5348 @table @option
5349 @c !sort!
5350 @item 1-9
5351 @emph{Specify indentation level.}
5352 If a digit from 1-9 appears
5353 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5354 then proper indentation is checked, with the digit indicating the
5355 indentation level required.
5356 The general style of required indentation is as specified by
5357 the examples in the Ada Reference Manual. Full line comments must be
5358 aligned with the @code{--} starting on a column that is a multiple of
5359 the alignment level.
5361 @item ^a^ATTRIBUTE^
5362 @emph{Check attribute casing.}
5363 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5364 then attribute names, including the case of keywords such as @code{digits}
5365 used as attributes names, must be written in mixed case, that is, the
5366 initial letter and any letter following an underscore must be uppercase.
5367 All other letters must be lowercase.
5369 @item ^b^BLANKS^
5370 @emph{Blanks not allowed at statement end.}
5371 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5372 trailing blanks are not allowed at the end of statements. The purpose of this
5373 rule, together with h (no horizontal tabs), is to enforce a canonical format
5374 for the use of blanks to separate source tokens.
5376 @item ^c^COMMENTS^
5377 @emph{Check comments.}
5378 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5379 then comments must meet the following set of rules:
5381 @itemize @bullet
5383 @item
5384 The ``@code{--}'' that starts the column must either start in column one,
5385 or else at least one blank must precede this sequence.
5387 @item
5388 Comments that follow other tokens on a line must have at least one blank
5389 following the ``@code{--}'' at the start of the comment.
5391 @item
5392 Full line comments must have two blanks following the ``@code{--}'' that
5393 starts the comment, with the following exceptions.
5395 @item
5396 A line consisting only of the ``@code{--}'' characters, possibly preceded
5397 by blanks is permitted.
5399 @item
5400 A comment starting with ``@code{--x}'' where @code{x} is a special character
5401 is permitted.
5402 This allows proper processing of the output generated by specialized tools
5403 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5404 annotation
5405 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5406 special character is defined as being in one of the ASCII ranges
5407 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5408 Note that this usage is not permitted
5409 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5411 @item
5412 A line consisting entirely of minus signs, possibly preceded by blanks, is
5413 permitted. This allows the construction of box comments where lines of minus
5414 signs are used to form the top and bottom of the box.
5416 @item
5417 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5418 least one blank follows the initial ``@code{--}''. Together with the preceding
5419 rule, this allows the construction of box comments, as shown in the following
5420 example:
5421 @smallexample
5422 ---------------------------
5423 -- This is a box comment --
5424 -- with two text lines.  --
5425 ---------------------------
5426 @end smallexample
5427 @end itemize
5429 @item ^d^DOS_LINE_ENDINGS^
5430 @emph{Check no DOS line terminators present.}
5431 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5432 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5433 character (in particular the DOS line terminator sequence CR/LF is not
5434 allowed).
5436 @item ^e^END^
5437 @emph{Check end/exit labels.}
5438 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5439 optional labels on @code{end} statements ending subprograms and on
5440 @code{exit} statements exiting named loops, are required to be present.
5442 @item ^f^VTABS^
5443 @emph{No form feeds or vertical tabs.}
5444 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5445 neither form feeds nor vertical tab characters are permitted
5446 in the source text.
5448 @item ^h^HTABS^
5449 @emph{No horizontal tabs.}
5450 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5451 horizontal tab characters are not permitted in the source text.
5452 Together with the b (no blanks at end of line) check, this
5453 enforces a canonical form for the use of blanks to separate
5454 source tokens.
5456 @item ^i^IF_THEN^
5457 @emph{Check if-then layout.}
5458 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5459 then the keyword @code{then} must appear either on the same
5460 line as corresponding @code{if}, or on a line on its own, lined
5461 up under the @code{if} with at least one non-blank line in between
5462 containing all or part of the condition to be tested.
5464 @item ^k^KEYWORD^
5465 @emph{Check keyword casing.}
5466 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5467 all keywords must be in lower case (with the exception of keywords
5468 such as @code{digits} used as attribute names to which this check
5469 does not apply).
5471 @item ^l^LAYOUT^
5472 @emph{Check layout.}
5473 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5474 layout of statement and declaration constructs must follow the
5475 recommendations in the Ada Reference Manual, as indicated by the
5476 form of the syntax rules. For example an @code{else} keyword must
5477 be lined up with the corresponding @code{if} keyword.
5479 There are two respects in which the style rule enforced by this check
5480 option are more liberal than those in the Ada Reference Manual. First
5481 in the case of record declarations, it is permissible to put the
5482 @code{record} keyword on the same line as the @code{type} keyword, and
5483 then the @code{end} in @code{end record} must line up under @code{type}.
5484 For example, either of the following two layouts is acceptable:
5486 @smallexample @c ada
5487 @cartouche
5488 type q is record
5489    a : integer;
5490    b : integer;
5491 end record;
5493 type q is
5494    record
5495       a : integer;
5496       b : integer;
5497    end record;
5498 @end cartouche
5499 @end smallexample
5501 @noindent
5502 Second, in the case of a block statement, a permitted alternative
5503 is to put the block label on the same line as the @code{declare} or
5504 @code{begin} keyword, and then line the @code{end} keyword up under
5505 the block label. For example both the following are permitted:
5507 @smallexample @c ada
5508 @cartouche
5509 Block : declare
5510    A : Integer := 3;
5511 begin
5512    Proc (A, A);
5513 end Block;
5515 Block :
5516    declare
5517       A : Integer := 3;
5518    begin
5519       Proc (A, A);
5520    end Block;
5521 @end cartouche
5522 @end smallexample
5524 @noindent
5525 The same alternative format is allowed for loops. For example, both of
5526 the following are permitted:
5528 @smallexample @c ada
5529 @cartouche
5530 Clear : while J < 10 loop
5531    A (J) := 0;
5532 end loop Clear;
5534 Clear :
5535    while J < 10 loop
5536       A (J) := 0;
5537    end loop Clear;
5538 @end cartouche
5539 @end smallexample
5541 @item ^Lnnn^MAX_NESTING=nnn^
5542 @emph{Set maximum nesting level}
5543 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5544 the range 0-999, appears in the string after @option{-gnaty} then the
5545 maximum level of nesting of constructs (including subprograms, loops,
5546 blocks, packages, and conditionals) may not exceed the given value. A
5547 value of zero disconnects this style check.
5549 @item ^m^LINE_LENGTH^
5550 @emph{Check maximum line length.}
5551 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5552 then the length of source lines must not exceed 79 characters, including
5553 any trailing blanks. The value of 79 allows convenient display on an
5554 80 character wide device or window, allowing for possible special
5555 treatment of 80 character lines. Note that this count is of
5556 characters in the source text. This means that a tab character counts
5557 as one character in this count but a wide character sequence counts as
5558 a single character (however many bytes are needed in the encoding).
5560 @item ^Mnnn^MAX_LENGTH=nnn^
5561 @emph{Set maximum line length.}
5562 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5563 the string after @option{-gnaty} then the length of lines must not exceed the
5564 given value. The maximum value that can be specified is 32767.
5566 @item ^n^STANDARD_CASING^
5567 @emph{Check casing of entities in Standard.}
5568 If the ^letter n^word STANDARD_CASING^ appears in the string
5569 after @option{-gnaty} then any identifier from Standard must be cased
5570 to match the presentation in the Ada Reference Manual (for example,
5571 @code{Integer} and @code{ASCII.NUL}).
5573 @item ^o^ORDERED_SUBPROGRAMS^
5574 @emph{Check order of subprogram bodies.}
5575 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5576 after @option{-gnaty} then all subprogram bodies in a given scope
5577 (e.g. a package body) must be in alphabetical order. The ordering
5578 rule uses normal Ada rules for comparing strings, ignoring casing
5579 of letters, except that if there is a trailing numeric suffix, then
5580 the value of this suffix is used in the ordering (e.g. Junk2 comes
5581 before Junk10).
5583 @item ^p^PRAGMA^
5584 @emph{Check pragma casing.}
5585 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5586 pragma names must be written in mixed case, that is, the
5587 initial letter and any letter following an underscore must be uppercase.
5588 All other letters must be lowercase.
5590 @item ^r^REFERENCES^
5591 @emph{Check references.}
5592 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5593 then all identifier references must be cased in the same way as the
5594 corresponding declaration. No specific casing style is imposed on
5595 identifiers. The only requirement is for consistency of references
5596 with declarations.
5598 @item ^s^SPECS^
5599 @emph{Check separate specs.}
5600 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5601 separate declarations (``specs'') are required for subprograms (a
5602 body is not allowed to serve as its own declaration). The only
5603 exception is that parameterless library level procedures are
5604 not required to have a separate declaration. This exception covers
5605 the most frequent form of main program procedures.
5607 @item ^t^TOKEN^
5608 @emph{Check token spacing.}
5609 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5610 the following token spacing rules are enforced:
5612 @itemize @bullet
5614 @item
5615 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5617 @item
5618 The token @code{=>} must be surrounded by spaces.
5620 @item
5621 The token @code{<>} must be preceded by a space or a left parenthesis.
5623 @item
5624 Binary operators other than @code{**} must be surrounded by spaces.
5625 There is no restriction on the layout of the @code{**} binary operator.
5627 @item
5628 Colon must be surrounded by spaces.
5630 @item
5631 Colon-equal (assignment, initialization) must be surrounded by spaces.
5633 @item
5634 Comma must be the first non-blank character on the line, or be
5635 immediately preceded by a non-blank character, and must be followed
5636 by a space.
5638 @item
5639 If the token preceding a left parenthesis ends with a letter or digit, then
5640 a space must separate the two tokens.
5642 @item
5643 A right parenthesis must either be the first non-blank character on
5644 a line, or it must be preceded by a non-blank character.
5646 @item
5647 A semicolon must not be preceded by a space, and must not be followed by
5648 a non-blank character.
5650 @item
5651 A unary plus or minus may not be followed by a space.
5653 @item
5654 A vertical bar must be surrounded by spaces.
5655 @end itemize
5657 @item ^u^UNNECESSARY_BLANK_LINES^
5658 @emph{Check unnecessary blank lines.}
5659 Check for unnecessary blank lines. A blank line is considered
5660 unnecessary if it appears at the end of the file, or if more than
5661 one blank line occurs in sequence.
5663 @item ^x^XTRA_PARENS^
5664 @emph{Check extra parentheses.}
5665 Check for the use of an unnecessary extra level of parentheses (C-style)
5666 around conditions in @code{if} statements, @code{while} statements and
5667 @code{exit} statements.
5669 @end table
5671 @noindent
5672 In the above rules, appearing in column one is always permitted, that is,
5673 counts as meeting either a requirement for a required preceding space,
5674 or as meeting a requirement for no preceding space.
5676 Appearing at the end of a line is also always permitted, that is, counts
5677 as meeting either a requirement for a following space, or as meeting
5678 a requirement for no following space.
5680 @noindent
5681 If any of these style rules is violated, a message is generated giving
5682 details on the violation. The initial characters of such messages are
5683 always ``@code{(style)}''. Note that these messages are treated as warning
5684 messages, so they normally do not prevent the generation of an object
5685 file. The @option{-gnatwe} switch can be used to treat warning messages,
5686 including style messages, as fatal errors.
5688 The switch
5689 @ifclear vms
5690 @option{-gnaty} on its own (that is not
5691 followed by any letters or digits),
5692 is equivalent to @code{gnaty3abcefhiklmnprst}, that is all checking
5693 options enabled with the exception of @option{-gnatyo},
5694 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
5695 @end ifclear
5696 @ifset vms
5697 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5698 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
5699 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
5700 @end ifset
5701 an indentation level of 3 is set. This is similar to the standard
5702 checking option that is used for the GNAT sources.
5704 The switch
5705 @ifclear vms
5706 @option{-gnatyN}
5707 @end ifclear
5708 @ifset vms
5709 /STYLE_CHECKS=NONE
5710 @end ifset
5711 clears any previously set style checks.
5713 @node Run-Time Checks
5714 @subsection Run-Time Checks
5715 @cindex Division by zero
5716 @cindex Access before elaboration
5717 @cindex Checks, division by zero
5718 @cindex Checks, access before elaboration
5719 @cindex Checks, stack overflow checking
5721 @noindent
5722 If you compile with the default options, GNAT will insert many run-time
5723 checks into the compiled code, including code that performs range
5724 checking against constraints, but not arithmetic overflow checking for
5725 integer operations (including division by zero), checks for access
5726 before elaboration on subprogram calls, or stack overflow checking. All
5727 other run-time checks, as required by the Ada 95 Reference Manual, are
5728 generated by default. The following @command{gcc} switches refine this
5729 default behavior:
5731 @table @option
5732 @c !sort!
5733 @item -gnatp
5734 @cindex @option{-gnatp} (@command{gcc})
5735 @cindex Suppressing checks
5736 @cindex Checks, suppressing
5737 @findex Suppress
5738 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5739 had been present in the source. Validity checks are also suppressed (in
5740 other words @option{-gnatp} also implies @option{-gnatVn}.
5741 Use this switch to improve the performance
5742 of the code at the expense of safety in the presence of invalid data or
5743 program bugs.
5745 @item -gnato
5746 @cindex @option{-gnato} (@command{gcc})
5747 @cindex Overflow checks
5748 @cindex Check, overflow
5749 Enables overflow checking for integer operations.
5750 This causes GNAT to generate slower and larger executable
5751 programs by adding code to check for overflow (resulting in raising
5752 @code{Constraint_Error} as required by standard Ada
5753 semantics). These overflow checks correspond to situations in which
5754 the true value of the result of an operation may be outside the base
5755 range of the result type. The following example shows the distinction:
5757 @smallexample @c ada
5758 X1 : Integer := Integer'Last;
5759 X2 : Integer range 1 .. 5 := 5;
5760 X3 : Integer := Integer'Last;
5761 X4 : Integer range 1 .. 5 := 5;
5762 F  : Float := 2.0E+20;
5764 X1 := X1 + 1;
5765 X2 := X2 + 1;
5766 X3 := Integer (F);
5767 X4 := Integer (F);
5768 @end smallexample
5770 @noindent
5771 Here the first addition results in a value that is outside the base range
5772 of Integer, and hence requires an overflow check for detection of the
5773 constraint error. Thus the first assignment to @code{X1} raises a
5774 @code{Constraint_Error} exception only if @option{-gnato} is set.
5776 The second increment operation results in a violation
5777 of the explicit range constraint, and such range checks are always
5778 performed (unless specifically suppressed with a pragma @code{suppress}
5779 or the use of @option{-gnatp}).
5781 The two conversions of @code{F} both result in values that are outside
5782 the base range of type @code{Integer} and thus will raise
5783 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5784 The fact that the result of the second conversion is assigned to
5785 variable @code{X4} with a restricted range is irrelevant, since the problem
5786 is in the conversion, not the assignment.
5788 Basically the rule is that in the default mode (@option{-gnato} not
5789 used), the generated code assures that all integer variables stay
5790 within their declared ranges, or within the base range if there is
5791 no declared range. This prevents any serious problems like indexes
5792 out of range for array operations.
5794 What is not checked in default mode is an overflow that results in
5795 an in-range, but incorrect value. In the above example, the assignments
5796 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5797 range of the target variable, but the result is wrong in the sense that
5798 it is too large to be represented correctly. Typically the assignment
5799 to @code{X1} will result in wrap around to the largest negative number.
5800 The conversions of @code{F} will result in some @code{Integer} value
5801 and if that integer value is out of the @code{X4} range then the
5802 subsequent assignment would generate an exception.
5804 @findex Machine_Overflows
5805 Note that the @option{-gnato} switch does not affect the code generated
5806 for any floating-point operations; it applies only to integer
5807 semantics).
5808 For floating-point, GNAT has the @code{Machine_Overflows}
5809 attribute set to @code{False} and the normal mode of operation is to
5810 generate IEEE NaN and infinite values on overflow or invalid operations
5811 (such as dividing 0.0 by 0.0).
5813 The reason that we distinguish overflow checking from other kinds of
5814 range constraint checking is that a failure of an overflow check can
5815 generate an incorrect value, but cannot cause erroneous behavior. This
5816 is unlike the situation with a constraint check on an array subscript,
5817 where failure to perform the check can result in random memory description,
5818 or the range check on a case statement, where failure to perform the check
5819 can cause a wild jump.
5821 Note again that @option{-gnato} is off by default, so overflow checking is
5822 not performed in default mode. This means that out of the box, with the
5823 default settings, GNAT does not do all the checks expected from the
5824 language description in the Ada Reference Manual. If you want all constraint
5825 checks to be performed, as described in this Manual, then you must
5826 explicitly use the -gnato switch either on the @command{gnatmake} or
5827 @command{gcc} command.
5829 @item -gnatE
5830 @cindex @option{-gnatE} (@command{gcc})
5831 @cindex Elaboration checks
5832 @cindex Check, elaboration
5833 Enables dynamic checks for access-before-elaboration
5834 on subprogram calls and generic instantiations.
5835 For full details of the effect and use of this switch,
5836 @xref{Compiling Using gcc}.
5838 @item -fstack-check
5839 @cindex @option{-fstack-check} (@command{gcc})
5840 @cindex Stack Overflow Checking
5841 @cindex Checks, stack overflow checking
5842 Activates stack overflow checking. For full details of the effect and use of
5843 this switch see @ref{Stack Overflow Checking}.
5844 @end table
5846 @findex Unsuppress
5847 @noindent
5848 The setting of these switches only controls the default setting of the
5849 checks. You may modify them using either @code{Suppress} (to remove
5850 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5851 the program source.
5853 @node Using gcc for Syntax Checking
5854 @subsection Using @command{gcc} for Syntax Checking
5855 @table @option
5856 @item -gnats
5857 @cindex @option{-gnats} (@command{gcc})
5858 @ifclear vms
5860 @noindent
5861 The @code{s} stands for ``syntax''.
5862 @end ifclear
5864 Run GNAT in syntax checking only mode. For
5865 example, the command
5867 @smallexample
5868 $ gcc -c -gnats x.adb
5869 @end smallexample
5871 @noindent
5872 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5873 series of files in a single command
5874 @ifclear vms
5875 , and can use wild cards to specify such a group of files.
5876 Note that you must specify the @option{-c} (compile
5877 only) flag in addition to the @option{-gnats} flag.
5878 @end ifclear
5880 You may use other switches in conjunction with @option{-gnats}. In
5881 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5882 format of any generated error messages.
5884 When the source file is empty or contains only empty lines and/or comments,
5885 the output is a warning:
5887 @smallexample
5888 $ gcc -c -gnats -x ada toto.txt
5889 toto.txt:1:01: warning: empty file, contains no compilation units
5891 @end smallexample
5893 Otherwise, the output is simply the error messages, if any. No object file or
5894 ALI file is generated by a syntax-only compilation. Also, no units other
5895 than the one specified are accessed. For example, if a unit @code{X}
5896 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5897 check only mode does not access the source file containing unit
5898 @code{Y}.
5900 @cindex Multiple units, syntax checking
5901 Normally, GNAT allows only a single unit in a source file. However, this
5902 restriction does not apply in syntax-check-only mode, and it is possible
5903 to check a file containing multiple compilation units concatenated
5904 together. This is primarily used by the @code{gnatchop} utility
5905 (@pxref{Renaming Files Using gnatchop}).
5906 @end table
5908 @node Using gcc for Semantic Checking
5909 @subsection Using @command{gcc} for Semantic Checking
5910 @table @option
5911 @item -gnatc
5912 @cindex @option{-gnatc} (@command{gcc})
5914 @ifclear vms
5915 @noindent
5916 The @code{c} stands for ``check''.
5917 @end ifclear
5918 Causes the compiler to operate in semantic check mode,
5919 with full checking for all illegalities specified in the
5920 Ada 95 Reference Manual, but without generation of any object code
5921 (no object file is generated).
5923 Because dependent files must be accessed, you must follow the GNAT
5924 semantic restrictions on file structuring to operate in this mode:
5926 @itemize @bullet
5927 @item
5928 The needed source files must be accessible
5929 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5931 @item
5932 Each file must contain only one compilation unit.
5934 @item
5935 The file name and unit name must match (@pxref{File Naming Rules}).
5936 @end itemize
5938 The output consists of error messages as appropriate. No object file is
5939 generated. An @file{ALI} file is generated for use in the context of
5940 cross-reference tools, but this file is marked as not being suitable
5941 for binding (since no object file is generated).
5942 The checking corresponds exactly to the notion of
5943 legality in the Ada 95 Reference Manual.
5945 Any unit can be compiled in semantics-checking-only mode, including
5946 units that would not normally be compiled (subunits,
5947 and specifications where a separate body is present).
5948 @end table
5950 @node Compiling Different Versions of Ada
5951 @subsection Compiling Different Versions of Ada
5952 @table @option
5953 @cindex Compatibility with Ada 83
5954 @cindex Ada 83 mode
5955 @cindex Ada 95 mode
5956 @cindex Ada 2005 mode
5958 GNAT is primarily an Ada 95 compiler, but the switches described in
5959 this section allow operation in Ada 83 compatibility mode, and also
5960 allow the use of a preliminary implementation of many of the expected
5961 new features in Ada 2005, the forthcoming new version of the standard.
5963 @item -gnat83 (Ada 83 Compatibility Mode)
5964 @cindex @option{-gnat83} (@command{gcc})
5965 @cindex ACVC, Ada 83 tests
5967 @noindent
5968 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5969 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5970 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5971 where this can be done easily.
5972 It is not possible to guarantee this switch does a perfect
5973 job; for example, some subtle tests, such as are
5974 found in earlier ACVC tests (and that have been removed from the ACATS suite
5975 for Ada 95), might not compile correctly.
5976 Nevertheless, this switch may be useful in some circumstances, for example
5977 where, due to contractual reasons, legacy code needs to be maintained
5978 using only Ada 83 features.
5980 With few exceptions (most notably the need to use @code{<>} on
5981 @cindex Generic formal parameters
5982 unconstrained generic formal parameters, the use of the new Ada 95
5983 reserved words, and the use of packages
5984 with optional bodies), it is not necessary to use the
5985 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5986 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5987 means that a correct Ada 83 program is usually also a correct Ada 95
5988 program.
5989 For further information, please refer to @ref{Compatibility and Porting Guide}.
5991 @item -gnat95 (Ada 95 mode)
5992 @cindex @option{-gnat95} (@command{gcc})
5994 @noindent
5995 GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro
5996 compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards
5997 compatible with Ada 83, that legacy Ada 83 programs may be compiled using
5998 this default Ada95 mode without problems (see section above describing the
5999 use of @option{-gnat83} to run in Ada 83 mode).
6001 In Ada 95 mode, the use of Ada 2005 features will in general cause error
6002 messages or warnings. Some specialized releases of GNAT (notably the GAP
6003 academic version) operate in Ada 2005 mode by default (see section below
6004 describing the use of @option{-gnat05} to run in Ada 2005 mode). For such
6005 versions the @option{-gnat95} switch may be used to enforce Ada 95 mode.
6006 This option also can be used to cancel the effect of a previous
6007 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6010 @item -gnat05 (Ada 2005 mode)
6011 @cindex @option{-gnat05} (@command{gcc})
6013 @noindent
6014 Although GNAT is primarily an Ada 95 compiler, it can be set to operate
6015 in Ada 2005 mode using this option. Although the new standard has not
6016 yet been issued (as of early 2005), many features have been discussed and
6017 approved in ``Ada Issues'' (AI's). For the text of these AI's, see
6018 @url{www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}. Included with GNAT
6019 releases is a file @file{features-ada0y} that describes the current set
6020 of implemented Ada 2005 features.
6022 If these features are used in Ada 95 mode (which is the normal default),
6023 then error messages or warnings may be
6024 generated, reflecting the fact that these new features are otherwise
6025 unauthorized extensions to Ada 95. The use of the @option{-gnat05}
6026 switch (or an equivalent pragma) causes these messages to be suppressed.
6028 Note that some specialized releases of GNAT (notably the GAP academic
6029 version) have Ada 2005 mode on by default, and in such environments,
6030 the Ada 2005 features can be used freely without the use of switches.
6032 @end table
6034 @node Character Set Control
6035 @subsection Character Set Control
6036 @table @option
6037 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6038 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6040 @noindent
6041 Normally GNAT recognizes the Latin-1 character set in source program
6042 identifiers, as described in the Ada 95 Reference Manual.
6043 This switch causes
6044 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6045 single character ^^or word^ indicating the character set, as follows:
6047 @table @code
6048 @item 1
6049 ISO 8859-1 (Latin-1) identifiers
6051 @item 2
6052 ISO 8859-2 (Latin-2) letters allowed in identifiers
6054 @item 3
6055 ISO 8859-3 (Latin-3) letters allowed in identifiers
6057 @item 4
6058 ISO 8859-4 (Latin-4) letters allowed in identifiers
6060 @item 5
6061 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6063 @item 9
6064 ISO 8859-15 (Latin-9) letters allowed in identifiers
6066 @item ^p^PC^
6067 IBM PC letters (code page 437) allowed in identifiers
6069 @item ^8^PC850^
6070 IBM PC letters (code page 850) allowed in identifiers
6072 @item ^f^FULL_UPPER^
6073 Full upper-half codes allowed in identifiers
6075 @item ^n^NO_UPPER^
6076 No upper-half codes allowed in identifiers
6078 @item ^w^WIDE^
6079 Wide-character codes (that is, codes greater than 255)
6080 allowed in identifiers
6081 @end table
6083 @xref{Foreign Language Representation}, for full details on the
6084 implementation of these character sets.
6086 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6087 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6088 Specify the method of encoding for wide characters.
6089 @var{e} is one of the following:
6091 @table @code
6093 @item ^h^HEX^
6094 Hex encoding (brackets coding also recognized)
6096 @item ^u^UPPER^
6097 Upper half encoding (brackets encoding also recognized)
6099 @item ^s^SHIFT_JIS^
6100 Shift/JIS encoding (brackets encoding also recognized)
6102 @item ^e^EUC^
6103 EUC encoding (brackets encoding also recognized)
6105 @item ^8^UTF8^
6106 UTF-8 encoding (brackets encoding also recognized)
6108 @item ^b^BRACKETS^
6109 Brackets encoding only (default value)
6110 @end table
6111 For full details on the these encoding
6112 methods see @ref{Wide Character Encodings}.
6113 Note that brackets coding is always accepted, even if one of the other
6114 options is specified, so for example @option{-gnatW8} specifies that both
6115 brackets and @code{UTF-8} encodings will be recognized. The units that are
6116 with'ed directly or indirectly will be scanned using the specified
6117 representation scheme, and so if one of the non-brackets scheme is
6118 used, it must be used consistently throughout the program. However,
6119 since brackets encoding is always recognized, it may be conveniently
6120 used in standard libraries, allowing these libraries to be used with
6121 any of the available coding schemes.
6122 scheme. If no @option{-gnatW?} parameter is present, then the default
6123 representation is Brackets encoding only.
6125 Note that the wide character representation that is specified (explicitly
6126 or by default) for the main program also acts as the default encoding used
6127 for Wide_Text_IO files if not specifically overridden by a WCEM form
6128 parameter.
6130 @end table
6131 @node File Naming Control
6132 @subsection File Naming Control
6134 @table @option
6135 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6136 @cindex @option{-gnatk} (@command{gcc})
6137 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6138 1-999, indicates the maximum allowable length of a file name (not
6139 including the @file{.ads} or @file{.adb} extension). The default is not
6140 to enable file name krunching.
6142 For the source file naming rules, @xref{File Naming Rules}.
6143 @end table
6145 @node Subprogram Inlining Control
6146 @subsection Subprogram Inlining Control
6148 @table @option
6149 @c !sort!
6150 @item -gnatn
6151 @cindex @option{-gnatn} (@command{gcc})
6152 @ifclear vms
6153 The @code{n} here is intended to suggest the first syllable of the
6154 word ``inline''.
6155 @end ifclear
6156 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6157 inlining to actually occur, optimization must be enabled. To enable
6158 inlining of subprograms specified by pragma @code{Inline},
6159 you must also specify this switch.
6160 In the absence of this switch, GNAT does not attempt
6161 inlining and does not need to access the bodies of
6162 subprograms for which @code{pragma Inline} is specified if they are not
6163 in the current unit.
6165 If you specify this switch the compiler will access these bodies,
6166 creating an extra source dependency for the resulting object file, and
6167 where possible, the call will be inlined.
6168 For further details on when inlining is possible
6169 see @ref{Inlining of Subprograms}.
6171 @item -gnatN
6172 @cindex @option{-gnatN} (@command{gcc})
6173 The front end inlining activated by this switch is generally more extensive,
6174 and quite often more effective than the standard @option{-gnatn} inlining mode.
6175 It will also generate additional dependencies.
6176 Note that
6177 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6178 to specify both options.
6179 @end table
6181 @node Auxiliary Output Control
6182 @subsection Auxiliary Output Control
6184 @table @option
6185 @item -gnatt
6186 @cindex @option{-gnatt} (@command{gcc})
6187 @cindex Writing internal trees
6188 @cindex Internal trees, writing to file
6189 Causes GNAT to write the internal tree for a unit to a file (with the
6190 extension @file{.adt}.
6191 This not normally required, but is used by separate analysis tools.
6192 Typically
6193 these tools do the necessary compilations automatically, so you should
6194 not have to specify this switch in normal operation.
6196 @item -gnatu
6197 @cindex @option{-gnatu} (@command{gcc})
6198 Print a list of units required by this compilation on @file{stdout}.
6199 The listing includes all units on which the unit being compiled depends
6200 either directly or indirectly.
6202 @ifclear vms
6203 @item -pass-exit-codes
6204 @cindex @option{-pass-exit-codes} (@command{gcc})
6205 If this switch is not used, the exit code returned by @command{gcc} when
6206 compiling multiple files indicates whether all source files have
6207 been successfully used to generate object files or not.
6209 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6210 exit status and allows an integrated development environment to better
6211 react to a compilation failure. Those exit status are:
6213 @table @asis
6214 @item 5
6215 There was an error in at least one source file.
6216 @item 3
6217 At least one source file did not generate an object file.
6218 @item 2
6219 The compiler died unexpectedly (internal error for example).
6220 @item 0
6221 An object file has been generated for every source file.
6222 @end table
6223 @end ifclear
6224 @end table
6226 @node Debugging Control
6227 @subsection Debugging Control
6229 @table @option
6230 @c !sort!
6231 @cindex Debugging options
6232 @ifclear vms
6233 @item -gnatd@var{x}
6234 @cindex @option{-gnatd} (@command{gcc})
6235 Activate internal debugging switches. @var{x} is a letter or digit, or
6236 string of letters or digits, which specifies the type of debugging
6237 outputs desired. Normally these are used only for internal development
6238 or system debugging purposes. You can find full documentation for these
6239 switches in the body of the @code{Debug} unit in the compiler source
6240 file @file{debug.adb}.
6241 @end ifclear
6243 @item -gnatG
6244 @cindex @option{-gnatG} (@command{gcc})
6245 This switch causes the compiler to generate auxiliary output containing
6246 a pseudo-source listing of the generated expanded code. Like most Ada
6247 compilers, GNAT works by first transforming the high level Ada code into
6248 lower level constructs. For example, tasking operations are transformed
6249 into calls to the tasking run-time routines. A unique capability of GNAT
6250 is to list this expanded code in a form very close to normal Ada source.
6251 This is very useful in understanding the implications of various Ada
6252 usage on the efficiency of the generated code. There are many cases in
6253 Ada (e.g. the use of controlled types), where simple Ada statements can
6254 generate a lot of run-time code. By using @option{-gnatG} you can identify
6255 these cases, and consider whether it may be desirable to modify the coding
6256 approach to improve efficiency.
6258 The format of the output is very similar to standard Ada source, and is
6259 easily understood by an Ada programmer. The following special syntactic
6260 additions correspond to low level features used in the generated code that
6261 do not have any exact analogies in pure Ada source form. The following
6262 is a partial list of these special constructions. See the specification
6263 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6265 @table @code
6266 @item new @var{xxx} [storage_pool = @var{yyy}]
6267 Shows the storage pool being used for an allocator.
6269 @item at end @var{procedure-name};
6270 Shows the finalization (cleanup) procedure for a scope.
6272 @item (if @var{expr} then @var{expr} else @var{expr})
6273 Conditional expression equivalent to the @code{x?y:z} construction in C.
6275 @item @var{target}^^^(@var{source})
6276 A conversion with floating-point truncation instead of rounding.
6278 @item @var{target}?(@var{source})
6279 A conversion that bypasses normal Ada semantic checking. In particular
6280 enumeration types and fixed-point types are treated simply as integers.
6282 @item @var{target}?^^^(@var{source})
6283 Combines the above two cases.
6285 @item @var{x} #/ @var{y}
6286 @itemx @var{x} #mod @var{y}
6287 @itemx @var{x} #* @var{y}
6288 @itemx @var{x} #rem @var{y}
6289 A division or multiplication of fixed-point values which are treated as
6290 integers without any kind of scaling.
6292 @item free @var{expr} [storage_pool = @var{xxx}]
6293 Shows the storage pool associated with a @code{free} statement.
6295 @item [subtype or type declaration]
6296 Used to list an equivalent declaration for an internally generated
6297 type that is referenced elsewhere in the listing.
6299 @item freeze @var{typename} [@var{actions}]
6300 Shows the point at which @var{typename} is frozen, with possible
6301 associated actions to be performed at the freeze point.
6303 @item reference @var{itype}
6304 Reference (and hence definition) to internal type @var{itype}.
6306 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6307 Intrinsic function call.
6309 @item @var{labelname} : label
6310 Declaration of label @var{labelname}.
6312 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6313 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6314 @var{expr}, but handled more efficiently).
6316 @item [constraint_error]
6317 Raise the @code{Constraint_Error} exception.
6319 @item @var{expression}'reference
6320 A pointer to the result of evaluating @var{expression}.
6322 @item @var{target-type}!(@var{source-expression})
6323 An unchecked conversion of @var{source-expression} to @var{target-type}.
6325 @item [@var{numerator}/@var{denominator}]
6326 Used to represent internal real literals (that) have no exact
6327 representation in base 2-16 (for example, the result of compile time
6328 evaluation of the expression 1.0/27.0).
6329 @end table
6331 @item -gnatD
6332 @cindex @option{-gnatD} (@command{gcc})
6333 When used in conjunction with @option{-gnatG}, this switch causes
6334 the expanded source, as described above for
6335 @option{-gnatG} to be written to files with names
6336 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6337 instead of to the standard ooutput file. For
6338 example, if the source file name is @file{hello.adb}, then a file
6339 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6340 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6341 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6342 you to do source level debugging using the generated code which is
6343 sometimes useful for complex code, for example to find out exactly
6344 which part of a complex construction raised an exception. This switch
6345 also suppress generation of cross-reference information (see
6346 @option{-gnatx}) since otherwise the cross-reference information
6347 would refer to the @file{^.dg^.DG^} file, which would cause
6348 confusion since this is not the original source file.
6350 Note that @option{-gnatD} actually implies @option{-gnatG}
6351 automatically, so it is not necessary to give both options.
6352 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6354 @ifclear vms
6355 @item -gnatR[0|1|2|3[s]]
6356 @cindex @option{-gnatR} (@command{gcc})
6357 This switch controls output from the compiler of a listing showing
6358 representation information for declared types and objects. For
6359 @option{-gnatR0}, no information is output (equivalent to omitting
6360 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6361 so @option{-gnatR} with no parameter has the same effect), size and alignment
6362 information is listed for declared array and record types. For
6363 @option{-gnatR2}, size and alignment information is listed for all
6364 expression information for values that are computed at run time for
6365 variant records. These symbolic expressions have a mostly obvious
6366 format with #n being used to represent the value of the n'th
6367 discriminant. See source files @file{repinfo.ads/adb} in the
6368 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6369 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6370 the output is to a file with the name @file{^file.rep^file_REP^} where
6371 file is the name of the corresponding source file.
6372 @end ifclear
6373 @ifset vms
6374 @item /REPRESENTATION_INFO
6375 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6376 This qualifier controls output from the compiler of a listing showing
6377 representation information for declared types and objects. For
6378 @option{/REPRESENTATION_INFO=NONE}, no information is output
6379 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6380 @option{/REPRESENTATION_INFO} without option is equivalent to
6381 @option{/REPRESENTATION_INFO=ARRAYS}.
6382 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6383 information is listed for declared array and record types. For
6384 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6385 is listed for all expression information for values that are computed
6386 at run time for variant records. These symbolic expressions have a mostly
6387 obvious format with #n being used to represent the value of the n'th
6388 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6389 @code{GNAT} sources for full details on the format of
6390 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6391 If _FILE is added at the end of an option
6392 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6393 then the output is to a file with the name @file{file_REP} where
6394 file is the name of the corresponding source file.
6395 @end ifset
6396 Note that it is possible for record components to have zero size. In
6397 this case, the component clause uses an obvious extension of permitted
6398 Ada syntax, for example @code{at 0 range 0 .. -1}.
6400 @item -gnatS
6401 @cindex @option{-gnatS} (@command{gcc})
6402 The use of the switch @option{-gnatS} for an
6403 Ada compilation will cause the compiler to output a
6404 representation of package Standard in a form very
6405 close to standard Ada. It is not quite possible to
6406 do this entirely in standard Ada (since new
6407 numeric base types cannot be created in standard
6408 Ada), but the output is easily
6409 readable to any Ada programmer, and is useful to
6410 determine the characteristics of target dependent
6411 types in package Standard.
6413 @item -gnatx
6414 @cindex @option{-gnatx} (@command{gcc})
6415 Normally the compiler generates full cross-referencing information in
6416 the @file{ALI} file. This information is used by a number of tools,
6417 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6418 suppresses this information. This saves some space and may slightly
6419 speed up compilation, but means that these tools cannot be used.
6420 @end table
6422 @node Exception Handling Control
6423 @subsection Exception Handling Control
6425 @noindent
6426 GNAT uses two methods for handling exceptions at run-time. The
6427 @code{setjmp/longjmp} method saves the context when entering
6428 a frame with an exception handler. Then when an exception is
6429 raised, the context can be restored immediately, without the
6430 need for tracing stack frames. This method provides very fast
6431 exception propagation, but introduces significant overhead for
6432 the use of exception handlers, even if no exception is raised.
6434 The other approach is called ``zero cost'' exception handling.
6435 With this method, the compiler builds static tables to describe
6436 the exception ranges. No dynamic code is required when entering
6437 a frame containing an exception handler. When an exception is
6438 raised, the tables are used to control a back trace of the
6439 subprogram invocation stack to locate the required exception
6440 handler. This method has considerably poorer performance for
6441 the propagation of exceptions, but there is no overhead for
6442 exception handlers if no exception is raised. Note that in this
6443 mode and in the context of mixed Ada and C/C++ programming,
6444 to propagate an exception through a C/C++ code, the C/C++ code
6445 must be compiled with the @option{-funwind-tables} GCC's
6446 option.
6448 The following switches can be used to control which of the
6449 two exception handling methods is used.
6451 @table @option
6452 @c !sort!
6454 @item --RTS=sjlj
6455 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6456 This switch causes the setjmp/longjmp run-time to be used
6457 for exception handling. If this is the default mechanism for the
6458 target (see below), then this has no effect. If the default
6459 mechanism for the target is zero cost exceptions, then
6460 this switch can be used to modify this default, and must be
6461 used for all units in the partition.
6462 This option is rarely used. One case in which it may be
6463 advantageous is if you have an application where exception
6464 raising is common and the overall performance of the
6465 application is improved by favoring exception propagation.
6467 @item --RTS=zcx
6468 @cindex @option{--RTS=zcx} (@command{gnatmake})
6469 @cindex Zero Cost Exceptions
6470 This switch causes the zero cost approach to be used
6471 for exception handling. If this is the default mechanism for the
6472 target (see below), then this has no effect. If the default
6473 mechanism for the target is setjmp/longjmp exceptions, then
6474 this switch can be used to modify this default, and must be
6475 used for all units in the partition.
6476 This option can only be used if the zero cost approach
6477 is available for the target in use (see below).
6478 @end table
6480 @noindent
6481 The @code{setjmp/longjmp} approach is available on all targets, while
6482 the @code{zero cost} approach is available on selected targets.
6483 To determine whether zero cost exceptions can be used for a
6484 particular target, look at the private part of the file system.ads.
6485 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6486 be True to use the zero cost approach. If both of these switches
6487 are set to False, this means that zero cost exception handling
6488 is not yet available for that target. The switch
6489 @code{ZCX_By_Default} indicates the default approach. If this
6490 switch is set to True, then the @code{zero cost} approach is
6491 used by default.
6493 @node Units to Sources Mapping Files
6494 @subsection Units to Sources Mapping Files
6496 @table @option
6498 @item -gnatem^^=^@var{path}
6499 @cindex @option{-gnatem} (@command{gcc})
6500 A mapping file is a way to communicate to the compiler two mappings:
6501 from unit names to file names (without any directory information) and from
6502 file names to path names (with full directory information). These mappings
6503 are used by the compiler to short-circuit the path search.
6505 The use of mapping files is not required for correct operation of the
6506 compiler, but mapping files can improve efficiency, particularly when
6507 sources are read over a slow network connection. In normal operation,
6508 you need not be concerned with the format or use of mapping files,
6509 and the @option{-gnatem} switch is not a switch that you would use
6510 explicitly. it is intended only for use by automatic tools such as
6511 @command{gnatmake} running under the project file facility. The
6512 description here of the format of mapping files is provided
6513 for completeness and for possible use by other tools.
6515 A mapping file is a sequence of sets of three lines. In each set,
6516 the first line is the unit name, in lower case, with ``@code{%s}''
6517 appended for
6518 specifications and ``@code{%b}'' appended for bodies; the second line is the
6519 file name; and the third line is the path name.
6521 Example:
6522 @smallexample
6523    main%b
6524    main.2.ada
6525    /gnat/project1/sources/main.2.ada
6526 @end smallexample
6528 When the switch @option{-gnatem} is specified, the compiler will create
6529 in memory the two mappings from the specified file. If there is any problem
6530 (non existent file, truncated file or duplicate entries), no mapping
6531 will be created.
6533 Several @option{-gnatem} switches may be specified; however, only the last
6534 one on the command line will be taken into account.
6536 When using a project file, @command{gnatmake} create a temporary mapping file
6537 and communicates it to the compiler using this switch.
6539 @end table
6541 @node Integrated Preprocessing
6542 @subsection Integrated Preprocessing
6544 @noindent
6545 GNAT sources may be preprocessed immediately before compilation; the actual
6546 text of the source is not the text of the source file, but is derived from it
6547 through a process called preprocessing. Integrated preprocessing is specified
6548 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6549 indicates, through a text file, the preprocessing data to be used.
6550 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6552 @noindent
6553 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6554 used when Integrated Preprocessing is used. The reason is that preprocessing
6555 with another Preprocessing Data file without changing the sources will
6556 not trigger recompilation without this switch.
6558 @noindent
6559 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6560 always trigger recompilation for sources that are preprocessed,
6561 because @command{gnatmake} cannot compute the checksum of the source after
6562 preprocessing.
6564 @noindent
6565 The actual preprocessing function is described in details in section
6566 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6567 preprocessing is triggered and parameterized.
6569 @table @code
6571 @item -gnatep=@var{file}
6572 @cindex @option{-gnatep} (@command{gcc})
6573 This switch indicates to the compiler the file name (without directory
6574 information) of the preprocessor data file to use. The preprocessor data file
6575 should be found in the source directories.
6577 @noindent
6578 A preprocessing data file is a text file with significant lines indicating
6579 how should be preprocessed either a specific source or all sources not
6580 mentioned in other lines. A significant line is a non empty, non comment line.
6581 Comments are similar to Ada comments.
6583 @noindent
6584 Each significant line starts with either a literal string or the character '*'.
6585 A literal string is the file name (without directory information) of the source
6586 to preprocess. A character '*' indicates the preprocessing for all the sources
6587 that are not specified explicitly on other lines (order of the lines is not
6588 significant). It is an error to have two lines with the same file name or two
6589 lines starting with the character '*'.
6591 @noindent
6592 After the file name or the character '*', another optional literal string
6593 indicating the file name of the definition file to be used for preprocessing
6594 (@pxref{Form of Definitions File}). The definition files are found by the
6595 compiler in one of the source directories. In some cases, when compiling
6596 a source in a directory other than the current directory, if the definition
6597 file is in the current directory, it may be necessary to add the current
6598 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6599 the compiler would not find the definition file.
6601 @noindent
6602 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6603 be found. Those ^switches^switches^ are:
6605 @table @code
6607 @item -b
6608 Causes both preprocessor lines and the lines deleted by
6609 preprocessing to be replaced by blank lines, preserving the line number.
6610 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6611 it cancels the effect of @option{-c}.
6613 @item -c
6614 Causes both preprocessor lines and the lines deleted
6615 by preprocessing to be retained as comments marked
6616 with the special string ``@code{--! }''.
6618 @item -Dsymbol=value
6619 Define or redefine a symbol, associated with value. A symbol is an Ada
6620 identifier, or an Ada reserved word, with the exception of @code{if},
6621 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6622 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6623 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6624 same name defined in a definition file.
6626 @item -s
6627 Causes a sorted list of symbol names and values to be
6628 listed on the standard output file.
6630 @item -u
6631 Causes undefined symbols to be treated as having the value @code{FALSE}
6632 in the context
6633 of a preprocessor test. In the absence of this option, an undefined symbol in
6634 a @code{#if} or @code{#elsif} test will be treated as an error.
6636 @end table
6638 @noindent
6639 Examples of valid lines in a preprocessor data file:
6641 @smallexample
6642   "toto.adb"  "prep.def" -u
6643   --  preprocess "toto.adb", using definition file "prep.def",
6644   --  undefined symbol are False.
6646   * -c -DVERSION=V101
6647   --  preprocess all other sources without a definition file;
6648   --  suppressed lined are commented; symbol VERSION has the value V101.
6650   "titi.adb" "prep2.def" -s
6651   --  preprocess "titi.adb", using definition file "prep2.def";
6652   --  list all symbols with their values.
6653 @end smallexample
6655 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6656 @cindex @option{-gnateD} (@command{gcc})
6657 Define or redefine a preprocessing symbol, associated with value. If no value
6658 is given on the command line, then the value of the symbol is @code{True}.
6659 A symbol is an identifier, following normal Ada (case-insensitive)
6660 rules for its syntax, and value is any sequence (including an empty sequence)
6661 of characters from the set (letters, digits, period, underline).
6662 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6663 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6665 @noindent
6666 A symbol declared with this ^switch^switch^ on the command line replaces a
6667 symbol with the same name either in a definition file or specified with a
6668 ^switch^switch^ -D in the preprocessor data file.
6670 @noindent
6671 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6673 @end table
6675 @node Code Generation Control
6676 @subsection Code Generation Control
6678 @noindent
6680 The GCC technology provides a wide range of target dependent
6681 @option{-m} switches for controlling
6682 details of code generation with respect to different versions of
6683 architectures. This includes variations in instruction sets (e.g.
6684 different members of the power pc family), and different requirements
6685 for optimal arrangement of instructions (e.g. different members of
6686 the x86 family). The list of available @option{-m} switches may be
6687 found in the GCC documentation.
6689 Use of the these @option{-m} switches may in some cases result in improved
6690 code performance.
6692 The GNAT Pro technology is tested and qualified without any
6693 @option{-m} switches,
6694 so generally the most reliable approach is to avoid the use of these
6695 switches. However, we generally expect most of these switches to work
6696 successfully with GNAT Pro, and many customers have reported successful
6697 use of these options.
6699 Our general advice is to avoid the use of @option{-m} switches unless
6700 special needs lead to requirements in this area. In particular,
6701 there is no point in using @option{-m} switches to improve performance
6702 unless you actually see a performance improvement.
6704 @ifset vms
6705 @node Return Codes
6706 @subsection Return Codes
6707 @cindex Return Codes
6708 @cindex @option{/RETURN_CODES=VMS}
6710 @noindent
6711 On VMS, GNAT compiled programs return POSIX-style codes by default,
6712 e.g. @option{/RETURN_CODES=POSIX}.
6714 To enable VMS style return codes, use GNAT BIND and LINK with the option
6715 @option{/RETURN_CODES=VMS}. For example:
6717 @smallexample
6718 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6719 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6720 @end smallexample
6722 @noindent
6723 Programs built with /RETURN_CODES=VMS are suitable to be called in
6724 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6725 are suitable for spawning with appropriate GNAT RTL routines.
6727 @end ifset
6729 @node Search Paths and the Run-Time Library (RTL)
6730 @section Search Paths and the Run-Time Library (RTL)
6732 @noindent
6733 With the GNAT source-based library system, the compiler must be able to
6734 find source files for units that are needed by the unit being compiled.
6735 Search paths are used to guide this process.
6737 The compiler compiles one source file whose name must be given
6738 explicitly on the command line. In other words, no searching is done
6739 for this file. To find all other source files that are needed (the most
6740 common being the specs of units), the compiler examines the following
6741 directories, in the following order:
6743 @enumerate
6744 @item
6745 The directory containing the source file of the main unit being compiled
6746 (the file name on the command line).
6748 @item
6749 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6750 @command{gcc} command line, in the order given.
6752 @item
6753 @findex ADA_PRJ_INCLUDE_FILE
6754 Each of the directories listed in the text file whose name is given
6755 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6757 @noindent
6758 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6759 driver when project files are used. It should not normally be set
6760 by other means.
6762 @item
6763 @findex ADA_INCLUDE_PATH
6764 Each of the directories listed in the value of the
6765 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6766 @ifclear vms
6767 Construct this value
6768 exactly as the @code{PATH} environment variable: a list of directory
6769 names separated by colons (semicolons when working with the NT version).
6770 @end ifclear
6771 @ifset vms
6772 Normally, define this value as a logical name containing a comma separated
6773 list of directory names.
6775 This variable can also be defined by means of an environment string
6776 (an argument to the HP C exec* set of functions).
6778 Logical Name:
6779 @smallexample
6780 DEFINE ANOTHER_PATH FOO:[BAG]
6781 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6782 @end smallexample
6784 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6785 first, followed by the standard Ada 95
6786 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6787 If this is not redefined, the user will obtain the HP Ada 83 IO packages
6788 (Text_IO, Sequential_IO, etc)
6789 instead of the Ada95 packages. Thus, in order to get the Ada 95
6790 packages by default, ADA_INCLUDE_PATH must be redefined.
6791 @end ifset
6793 @item
6794 The content of the @file{ada_source_path} file which is part of the GNAT
6795 installation tree and is used to store standard libraries such as the
6796 GNAT Run Time Library (RTL) source files.
6797 @ifclear vms
6798 @ref{Installing a library}
6799 @end ifclear
6800 @end enumerate
6802 @noindent
6803 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6804 inhibits the use of the directory
6805 containing the source file named in the command line. You can still
6806 have this directory on your search path, but in this case it must be
6807 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6809 Specifying the switch @option{-nostdinc}
6810 inhibits the search of the default location for the GNAT Run Time
6811 Library (RTL) source files.
6813 The compiler outputs its object files and ALI files in the current
6814 working directory.
6815 @ifclear vms
6816 Caution: The object file can be redirected with the @option{-o} switch;
6817 however, @command{gcc} and @code{gnat1} have not been coordinated on this
6818 so the @file{ALI} file will not go to the right place. Therefore, you should
6819 avoid using the @option{-o} switch.
6820 @end ifclear
6822 @findex System.IO
6823 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6824 children make up the GNAT RTL, together with the simple @code{System.IO}
6825 package used in the @code{"Hello World"} example. The sources for these units
6826 are needed by the compiler and are kept together in one directory. Not
6827 all of the bodies are needed, but all of the sources are kept together
6828 anyway. In a normal installation, you need not specify these directory
6829 names when compiling or binding. Either the environment variables or
6830 the built-in defaults cause these files to be found.
6832 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6833 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6834 consisting of child units of @code{GNAT}. This is a collection of generally
6835 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6836 further details.
6838 Besides simplifying access to the RTL, a major use of search paths is
6839 in compiling sources from multiple directories. This can make
6840 development environments much more flexible.
6842 @node Order of Compilation Issues
6843 @section Order of Compilation Issues
6845 @noindent
6846 If, in our earlier example, there was a spec for the @code{hello}
6847 procedure, it would be contained in the file @file{hello.ads}; yet this
6848 file would not have to be explicitly compiled. This is the result of the
6849 model we chose to implement library management. Some of the consequences
6850 of this model are as follows:
6852 @itemize @bullet
6853 @item
6854 There is no point in compiling specs (except for package
6855 specs with no bodies) because these are compiled as needed by clients. If
6856 you attempt a useless compilation, you will receive an error message.
6857 It is also useless to compile subunits because they are compiled as needed
6858 by the parent.
6860 @item
6861 There are no order of compilation requirements: performing a
6862 compilation never obsoletes anything. The only way you can obsolete
6863 something and require recompilations is to modify one of the
6864 source files on which it depends.
6866 @item
6867 There is no library as such, apart from the ALI files
6868 (@pxref{The Ada Library Information Files}, for information on the format
6869 of these files). For now we find it convenient to create separate ALI files,
6870 but eventually the information therein may be incorporated into the object
6871 file directly.
6873 @item
6874 When you compile a unit, the source files for the specs of all units
6875 that it @code{with}'s, all its subunits, and the bodies of any generics it
6876 instantiates must be available (reachable by the search-paths mechanism
6877 described above), or you will receive a fatal error message.
6878 @end itemize
6880 @node Examples
6881 @section Examples
6883 @noindent
6884 The following are some typical Ada compilation command line examples:
6886 @table @code
6887 @item $ gcc -c xyz.adb
6888 Compile body in file @file{xyz.adb} with all default options.
6890 @ifclear vms
6891 @item $ gcc -c -O2 -gnata xyz-def.adb
6892 @end ifclear
6893 @ifset vms
6894 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6895 @end ifset
6897 Compile the child unit package in file @file{xyz-def.adb} with extensive
6898 optimizations, and pragma @code{Assert}/@code{Debug} statements
6899 enabled.
6901 @item $ gcc -c -gnatc abc-def.adb
6902 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6903 mode.
6904 @end table
6906 @node Binding Using gnatbind
6907 @chapter Binding Using @code{gnatbind}
6908 @findex gnatbind
6910 @menu
6911 * Running gnatbind::
6912 * Switches for gnatbind::
6913 * Command-Line Access::
6914 * Search Paths for gnatbind::
6915 * Examples of gnatbind Usage::
6916 @end menu
6918 @noindent
6919 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6920 to bind compiled GNAT objects. The @code{gnatbind} program performs
6921 four separate functions:
6923 @enumerate
6924 @item
6925 Checks that a program is consistent, in accordance with the rules in
6926 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6927 messages are generated if a program uses inconsistent versions of a
6928 given unit.
6930 @item
6931 Checks that an acceptable order of elaboration exists for the program
6932 and issues an error message if it cannot find an order of elaboration
6933 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6935 @item
6936 Generates a main program incorporating the given elaboration order.
6937 This program is a small Ada package (body and spec) that
6938 must be subsequently compiled
6939 using the GNAT compiler. The necessary compilation step is usually
6940 performed automatically by @command{gnatlink}. The two most important
6941 functions of this program
6942 are to call the elaboration routines of units in an appropriate order
6943 and to call the main program.
6945 @item
6946 Determines the set of object files required by the given main program.
6947 This information is output in the forms of comments in the generated program,
6948 to be read by the @command{gnatlink} utility used to link the Ada application.
6949 @end enumerate
6951 @node Running gnatbind
6952 @section Running @code{gnatbind}
6954 @noindent
6955 The form of the @code{gnatbind} command is
6957 @smallexample
6958 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6959 @end smallexample
6961 @noindent
6962 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6963 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6964 package in two files whose names are
6965 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6966 For example, if given the
6967 parameter @file{hello.ali}, for a main program contained in file
6968 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6969 and @file{b~hello.adb}.
6971 When doing consistency checking, the binder takes into consideration
6972 any source files it can locate. For example, if the binder determines
6973 that the given main program requires the package @code{Pack}, whose
6974 @file{.ALI}
6975 file is @file{pack.ali} and whose corresponding source spec file is
6976 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6977 (using the same search path conventions as previously described for the
6978 @command{gcc} command). If it can locate this source file, it checks that
6979 the time stamps
6980 or source checksums of the source and its references to in @file{ALI} files
6981 match. In other words, any @file{ALI} files that mentions this spec must have
6982 resulted from compiling this version of the source file (or in the case
6983 where the source checksums match, a version close enough that the
6984 difference does not matter).
6986 @cindex Source files, use by binder
6987 The effect of this consistency checking, which includes source files, is
6988 that the binder ensures that the program is consistent with the latest
6989 version of the source files that can be located at bind time. Editing a
6990 source file without compiling files that depend on the source file cause
6991 error messages to be generated by the binder.
6993 For example, suppose you have a main program @file{hello.adb} and a
6994 package @code{P}, from file @file{p.ads} and you perform the following
6995 steps:
6997 @enumerate
6998 @item
6999 Enter @code{gcc -c hello.adb} to compile the main program.
7001 @item
7002 Enter @code{gcc -c p.ads} to compile package @code{P}.
7004 @item
7005 Edit file @file{p.ads}.
7007 @item
7008 Enter @code{gnatbind hello}.
7009 @end enumerate
7011 @noindent
7012 At this point, the file @file{p.ali} contains an out-of-date time stamp
7013 because the file @file{p.ads} has been edited. The attempt at binding
7014 fails, and the binder generates the following error messages:
7016 @smallexample
7017 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7018 error: "p.ads" has been modified and must be recompiled
7019 @end smallexample
7021 @noindent
7022 Now both files must be recompiled as indicated, and then the bind can
7023 succeed, generating a main program. You need not normally be concerned
7024 with the contents of this file, but for reference purposes a sample
7025 binder output file is given in @ref{Example of Binder Output File}.
7027 In most normal usage, the default mode of @command{gnatbind} which is to
7028 generate the main package in Ada, as described in the previous section.
7029 In particular, this means that any Ada programmer can read and understand
7030 the generated main program. It can also be debugged just like any other
7031 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7032 @command{gnatbind} and @command{gnatlink}.
7034 However for some purposes it may be convenient to generate the main
7035 program in C rather than Ada. This may for example be helpful when you
7036 are generating a mixed language program with the main program in C. The
7037 GNAT compiler itself is an example.
7038 The use of the @option{^-C^/BIND_FILE=C^} switch
7039 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7040 be generated in C (and compiled using the gnu C compiler).
7042 @node Switches for gnatbind
7043 @section Switches for @command{gnatbind}
7045 @noindent
7046 The following switches are available with @code{gnatbind}; details will
7047 be presented in subsequent sections.
7049 @menu
7050 * Consistency-Checking Modes::
7051 * Binder Error Message Control::
7052 * Elaboration Control::
7053 * Output Control::
7054 * Binding with Non-Ada Main Programs::
7055 * Binding Programs with No Main Subprogram::
7056 @end menu
7058 @table @option
7059 @c !sort!
7060 @item ^-aO^/OBJECT_SEARCH^
7061 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7062 Specify directory to be searched for ALI files.
7064 @item ^-aI^/SOURCE_SEARCH^
7065 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7066 Specify directory to be searched for source file.
7068 @item ^-A^/BIND_FILE=ADA^
7069 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7070 Generate binder program in Ada (default)
7072 @item ^-b^/REPORT_ERRORS=BRIEF^
7073 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7074 Generate brief messages to @file{stderr} even if verbose mode set.
7076 @item ^-c^/NOOUTPUT^
7077 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7078 Check only, no generation of binder output file.
7080 @item ^-C^/BIND_FILE=C^
7081 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7082 Generate binder program in C
7084 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^
7085 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7086 This switch can be used to change the default secondary stack size value
7087 to a specified size, where nnnnn is the size in bytes.
7089 The secondary stack is used to deal with functions that return a variable
7090 sized result, for example a function returning an unconstrained
7091 String. There are two ways in which this secondary stack is allocated.
7093 For most targets, the secondary stack is allocated as a chain of blocks
7094 in the heap, and in this case the size of the chunk allocated is the minimum
7095 of the default secondary stack size value,
7096 and the actual size needed for the current allocation request.
7098 For certain targets, notably bare board targets and the VxWorks 653 target,
7099 the secondary stack is allocated by carving off a fixed ratio chunk of the
7100 primary task stack. For such targets, the environment task is special, and
7101 in this case the default value is used to carve out a section of the
7102 environment task stack.
7105 @item ^-e^/ELABORATION_DEPENDENCIES^
7106 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7107 Output complete list of elaboration-order dependencies.
7109 @item ^-E^/STORE_TRACEBACKS^
7110 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7111 Store tracebacks in exception occurrences when the target supports it.
7112 This is the default with the zero cost exception mechanism.
7113 @ignore
7114 @c The following may get moved to an appendix
7115 This option is currently supported on the following targets:
7116 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7117 @end ignore
7118 See also the packages @code{GNAT.Traceback} and
7119 @code{GNAT.Traceback.Symbolic} for more information.
7120 @ifclear vms
7121 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7122 @command{gcc} option.
7123 @end ifclear
7125 @item ^-F^/FORCE_ELABS_FLAGS^
7126 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7127 Force the checks of elaboration flags. @command{gnatbind} does not normally
7128 generate checks of elaboration flags for the main executable, except when
7129 a Stand-Alone Library is used. However, there are cases when this cannot be
7130 detected by gnatbind. An example is importing an interface of a Stand-Alone
7131 Library through a pragma Import and only specifying through a linker switch
7132 this Stand-Alone Library. This switch is used to guarantee that elaboration
7133 flag checks are generated.
7135 @item ^-h^/HELP^
7136 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7137 Output usage (help) information
7139 @item ^-I^/SEARCH^
7140 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7141 Specify directory to be searched for source and ALI files.
7143 @item ^-I-^/NOCURRENT_DIRECTORY^
7144 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7145 Do not look for sources in the current directory where @code{gnatbind} was
7146 invoked, and do not look for ALI files in the directory containing the
7147 ALI file named in the @code{gnatbind} command line.
7149 @item ^-l^/ORDER_OF_ELABORATION^
7150 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7151 Output chosen elaboration order.
7153 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7154 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7155 Bind the units for library building. In this case the adainit and
7156 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7157 are renamed to ^xxxinit^XXXINIT^ and
7158 ^xxxfinal^XXXFINAL^.
7159 Implies ^-n^/NOCOMPILE^.
7160 @ifclear vms
7161 (@xref{GNAT and Libraries}, for more details.)
7162 @end ifclear
7163 @ifset vms
7164 On OpenVMS, these init and final procedures are exported in uppercase
7165 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7166 the init procedure will be "TOTOINIT" and the exported name of the final
7167 procedure will be "TOTOFINAL".
7168 @end ifset
7170 @item ^-Mxyz^/RENAME_MAIN=xyz^
7171 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7172 Rename generated main program from main to xyz
7174 @item ^-m^/ERROR_LIMIT=^@var{n}
7175 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7176 Limit number of detected errors to @var{n}, where @var{n} is
7177 in the range 1..999_999. The default value if no switch is
7178 given is 9999. Binding is terminated if the limit is exceeded.
7179 @ifset unw
7180 Furthermore, under Windows, the sources pointed to by the libraries path
7181 set in the registry are not searched for.
7182 @end ifset
7184 @item ^-n^/NOMAIN^
7185 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7186 No main program.
7188 @item -nostdinc
7189 @cindex @option{-nostdinc} (@command{gnatbind})
7190 Do not look for sources in the system default directory.
7192 @item -nostdlib
7193 @cindex @option{-nostdlib} (@command{gnatbind})
7194 Do not look for library files in the system default directory.
7196 @item --RTS=@var{rts-path}
7197 @cindex @option{--RTS} (@code{gnatbind})
7198 Specifies the default location of the runtime library. Same meaning as the
7199 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7201 @item ^-o ^/OUTPUT=^@var{file}
7202 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7203 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7204 Note that if this option is used, then linking must be done manually,
7205 gnatlink cannot be used.
7207 @item ^-O^/OBJECT_LIST^
7208 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7209 Output object list.
7211 @item ^-p^/PESSIMISTIC_ELABORATION^
7212 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7213 Pessimistic (worst-case) elaboration order
7215 @item ^-s^/READ_SOURCES=ALL^
7216 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7217 Require all source files to be present.
7219 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7220 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7221 Specifies the value to be used when detecting uninitialized scalar
7222 objects with pragma Initialize_Scalars.
7223 The @var{xxx} ^string specified with the switch^option^ may be either
7224 @itemize @bullet
7225 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7226 @item ``@option{^lo^LOW^}'' for the lowest possible value
7227 @item ``@option{^hi^HIGH^}'' for the highest possible value
7228 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7229 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7230 @end itemize
7232 In addition, you can specify @option{-Sev} to indicate that the value is
7233 to be set at run time. In this case, the program will look for an environment
7234 @cindex GNAT_INIT_SCALARS
7235 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7236 of @option{in/lo/hi/xx} with the same meanings as above.
7237 If no environment variable is found, or if it does not have a valid value,
7238 then the default is @option{in} (invalid values).
7240 @ifclear vms
7241 @item -static
7242 @cindex @option{-static} (@code{gnatbind})
7243 Link against a static GNAT run time.
7245 @item -shared
7246 @cindex @option{-shared} (@code{gnatbind})
7247 Link against a shared GNAT run time when available.
7248 @end ifclear
7250 @item ^-t^/NOTIME_STAMP_CHECK^
7251 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7252 Tolerate time stamp and other consistency errors
7254 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7255 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7256 Set the time slice value to @var{n} milliseconds. If the system supports
7257 the specification of a specific time slice value, then the indicated value
7258 is used. If the system does not support specific time slice values, but
7259 does support some general notion of round-robin scheduling, then any
7260 non-zero value will activate round-robin scheduling.
7262 A value of zero is treated specially. It turns off time
7263 slicing, and in addition, indicates to the tasking run time that the
7264 semantics should match as closely as possible the Annex D
7265 requirements of the Ada RM, and in particular sets the default
7266 scheduling policy to @code{FIFO_Within_Priorities}.
7268 @item ^-v^/REPORT_ERRORS=VERBOSE^
7269 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7270 Verbose mode. Write error messages, header, summary output to
7271 @file{stdout}.
7273 @ifclear vms
7274 @item -w@var{x}
7275 @cindex @option{-w} (@code{gnatbind})
7276 Warning mode (@var{x}=s/e for suppress/treat as error)
7277 @end ifclear
7279 @ifset vms
7280 @item /WARNINGS=NORMAL
7281 @cindex @option{/WARNINGS} (@code{gnatbind})
7282 Normal warnings mode. Warnings are issued but ignored
7284 @item /WARNINGS=SUPPRESS
7285 @cindex @option{/WARNINGS} (@code{gnatbind})
7286 All warning messages are suppressed
7288 @item /WARNINGS=ERROR
7289 @cindex @option{/WARNINGS} (@code{gnatbind})
7290 Warning messages are treated as fatal errors
7291 @end ifset
7293 @item ^-x^/READ_SOURCES=NONE^
7294 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7295 Exclude source files (check object consistency only).
7297 @ifset vms
7298 @item /READ_SOURCES=AVAILABLE
7299 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7300 Default mode, in which sources are checked for consistency only if
7301 they are available.
7302 @end ifset
7304 @item ^-z^/ZERO_MAIN^
7305 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7306 No main subprogram.
7307 @end table
7309 @ifclear vms
7310 @noindent
7311 You may obtain this listing of switches by running @code{gnatbind} with
7312 no arguments.
7313 @end ifclear
7315 @node Consistency-Checking Modes
7316 @subsection Consistency-Checking Modes
7318 @noindent
7319 As described earlier, by default @code{gnatbind} checks
7320 that object files are consistent with one another and are consistent
7321 with any source files it can locate. The following switches control binder
7322 access to sources.
7324 @table @option
7325 @c !sort!
7326 @item ^-s^/READ_SOURCES=ALL^
7327 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7328 Require source files to be present. In this mode, the binder must be
7329 able to locate all source files that are referenced, in order to check
7330 their consistency. In normal mode, if a source file cannot be located it
7331 is simply ignored. If you specify this switch, a missing source
7332 file is an error.
7334 @item ^-x^/READ_SOURCES=NONE^
7335 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7336 Exclude source files. In this mode, the binder only checks that ALI
7337 files are consistent with one another. Source files are not accessed.
7338 The binder runs faster in this mode, and there is still a guarantee that
7339 the resulting program is self-consistent.
7340 If a source file has been edited since it was last compiled, and you
7341 specify this switch, the binder will not detect that the object
7342 file is out of date with respect to the source file. Note that this is the
7343 mode that is automatically used by @command{gnatmake} because in this
7344 case the checking against sources has already been performed by
7345 @command{gnatmake} in the course of compilation (i.e. before binding).
7347 @ifset vms
7348 @item /READ_SOURCES=AVAILABLE
7349 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7350 This is the default mode in which source files are checked if they are
7351 available, and ignored if they are not available.
7352 @end ifset
7353 @end table
7355 @node Binder Error Message Control
7356 @subsection Binder Error Message Control
7358 @noindent
7359 The following switches provide control over the generation of error
7360 messages from the binder:
7362 @table @option
7363 @c !sort!
7364 @item ^-v^/REPORT_ERRORS=VERBOSE^
7365 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7366 Verbose mode. In the normal mode, brief error messages are generated to
7367 @file{stderr}. If this switch is present, a header is written
7368 to @file{stdout} and any error messages are directed to @file{stdout}.
7369 All that is written to @file{stderr} is a brief summary message.
7371 @item ^-b^/REPORT_ERRORS=BRIEF^
7372 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7373 Generate brief error messages to @file{stderr} even if verbose mode is
7374 specified. This is relevant only when used with the
7375 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7377 @ifclear vms
7378 @item -m@var{n}
7379 @cindex @option{-m} (@code{gnatbind})
7380 Limits the number of error messages to @var{n}, a decimal integer in the
7381 range 1-999. The binder terminates immediately if this limit is reached.
7383 @item -M@var{xxx}
7384 @cindex @option{-M} (@code{gnatbind})
7385 Renames the generated main program from @code{main} to @code{xxx}.
7386 This is useful in the case of some cross-building environments, where
7387 the actual main program is separate from the one generated
7388 by @code{gnatbind}.
7389 @end ifclear
7391 @item ^-ws^/WARNINGS=SUPPRESS^
7392 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7393 @cindex Warnings
7394 Suppress all warning messages.
7396 @item ^-we^/WARNINGS=ERROR^
7397 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7398 Treat any warning messages as fatal errors.
7400 @ifset vms
7401 @item /WARNINGS=NORMAL
7402 Standard mode with warnings generated, but warnings do not get treated
7403 as errors.
7404 @end ifset
7406 @item ^-t^/NOTIME_STAMP_CHECK^
7407 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7408 @cindex Time stamp checks, in binder
7409 @cindex Binder consistency checks
7410 @cindex Consistency checks, in binder
7411 The binder performs a number of consistency checks including:
7413 @itemize @bullet
7414 @item
7415 Check that time stamps of a given source unit are consistent
7416 @item
7417 Check that checksums of a given source unit are consistent
7418 @item
7419 Check that consistent versions of @code{GNAT} were used for compilation
7420 @item
7421 Check consistency of configuration pragmas as required
7422 @end itemize
7424 @noindent
7425 Normally failure of such checks, in accordance with the consistency
7426 requirements of the Ada Reference Manual, causes error messages to be
7427 generated which abort the binder and prevent the output of a binder
7428 file and subsequent link to obtain an executable.
7430 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7431 into warnings, so that
7432 binding and linking can continue to completion even in the presence of such
7433 errors. The result may be a failed link (due to missing symbols), or a
7434 non-functional executable which has undefined semantics.
7435 @emph{This means that
7436 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7437 with extreme care.}
7438 @end table
7440 @node Elaboration Control
7441 @subsection Elaboration Control
7443 @noindent
7444 The following switches provide additional control over the elaboration
7445 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7447 @table @option
7448 @item ^-p^/PESSIMISTIC_ELABORATION^
7449 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7450 Normally the binder attempts to choose an elaboration order that is
7451 likely to minimize the likelihood of an elaboration order error resulting
7452 in raising a @code{Program_Error} exception. This switch reverses the
7453 action of the binder, and requests that it deliberately choose an order
7454 that is likely to maximize the likelihood of an elaboration error.
7455 This is useful in ensuring portability and avoiding dependence on
7456 accidental fortuitous elaboration ordering.
7458 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7459 switch if dynamic
7460 elaboration checking is used (@option{-gnatE} switch used for compilation).
7461 This is because in the default static elaboration mode, all necessary
7462 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7463 These implicit pragmas are still respected by the binder in
7464 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7465 safe elaboration order is assured.
7466 @end table
7468 @node Output Control
7469 @subsection Output Control
7471 @noindent
7472 The following switches allow additional control over the output
7473 generated by the binder.
7475 @table @option
7476 @c !sort!
7478 @item ^-A^/BIND_FILE=ADA^
7479 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7480 Generate binder program in Ada (default). The binder program is named
7481 @file{b~@var{mainprog}.adb} by default. This can be changed with
7482 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7484 @item ^-c^/NOOUTPUT^
7485 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7486 Check only. Do not generate the binder output file. In this mode the
7487 binder performs all error checks but does not generate an output file.
7489 @item ^-C^/BIND_FILE=C^
7490 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7491 Generate binder program in C. The binder program is named
7492 @file{b_@var{mainprog}.c}.
7493 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7494 option.
7496 @item ^-e^/ELABORATION_DEPENDENCIES^
7497 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7498 Output complete list of elaboration-order dependencies, showing the
7499 reason for each dependency. This output can be rather extensive but may
7500 be useful in diagnosing problems with elaboration order. The output is
7501 written to @file{stdout}.
7503 @item ^-h^/HELP^
7504 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7505 Output usage information. The output is written to @file{stdout}.
7507 @item ^-K^/LINKER_OPTION_LIST^
7508 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7509 Output linker options to @file{stdout}. Includes library search paths,
7510 contents of pragmas Ident and Linker_Options, and libraries added
7511 by @code{gnatbind}.
7513 @item ^-l^/ORDER_OF_ELABORATION^
7514 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7515 Output chosen elaboration order. The output is written to @file{stdout}.
7517 @item ^-O^/OBJECT_LIST^
7518 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7519 Output full names of all the object files that must be linked to provide
7520 the Ada component of the program. The output is written to @file{stdout}.
7521 This list includes the files explicitly supplied and referenced by the user
7522 as well as implicitly referenced run-time unit files. The latter are
7523 omitted if the corresponding units reside in shared libraries. The
7524 directory names for the run-time units depend on the system configuration.
7526 @item ^-o ^/OUTPUT=^@var{file}
7527 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7528 Set name of output file to @var{file} instead of the normal
7529 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7530 binder generated body filename. In C mode you would normally give
7531 @var{file} an extension of @file{.c} because it will be a C source program.
7532 Note that if this option is used, then linking must be done manually.
7533 It is not possible to use gnatlink in this case, since it cannot locate
7534 the binder file.
7536 @item ^-r^/RESTRICTION_LIST^
7537 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7538 Generate list of @code{pragma Restrictions} that could be applied to
7539 the current unit. This is useful for code audit purposes, and also may
7540 be used to improve code generation in some cases.
7542 @end table
7544 @node Binding with Non-Ada Main Programs
7545 @subsection Binding with Non-Ada Main Programs
7547 @noindent
7548 In our description so far we have assumed that the main
7549 program is in Ada, and that the task of the binder is to generate a
7550 corresponding function @code{main} that invokes this Ada main
7551 program. GNAT also supports the building of executable programs where
7552 the main program is not in Ada, but some of the called routines are
7553 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7554 The following switch is used in this situation:
7556 @table @option
7557 @item ^-n^/NOMAIN^
7558 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7559 No main program. The main program is not in Ada.
7560 @end table
7562 @noindent
7563 In this case, most of the functions of the binder are still required,
7564 but instead of generating a main program, the binder generates a file
7565 containing the following callable routines:
7567 @table @code
7568 @item adainit
7569 @findex adainit
7570 You must call this routine to initialize the Ada part of the program by
7571 calling the necessary elaboration routines. A call to @code{adainit} is
7572 required before the first call to an Ada subprogram.
7574 Note that it is assumed that the basic execution environment must be setup
7575 to be appropriate for Ada execution at the point where the first Ada
7576 subprogram is called. In particular, if the Ada code will do any
7577 floating-point operations, then the FPU must be setup in an appropriate
7578 manner. For the case of the x86, for example, full precision mode is
7579 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7580 that the FPU is in the right state.
7582 @item adafinal
7583 @findex adafinal
7584 You must call this routine to perform any library-level finalization
7585 required by the Ada subprograms. A call to @code{adafinal} is required
7586 after the last call to an Ada subprogram, and before the program
7587 terminates.
7588 @end table
7590 @noindent
7591 If the @option{^-n^/NOMAIN^} switch
7592 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7593 @cindex Binder, multiple input files
7594 is given, more than one ALI file may appear on
7595 the command line for @code{gnatbind}. The normal @dfn{closure}
7596 calculation is performed for each of the specified units. Calculating
7597 the closure means finding out the set of units involved by tracing
7598 @code{with} references. The reason it is necessary to be able to
7599 specify more than one ALI file is that a given program may invoke two or
7600 more quite separate groups of Ada units.
7602 The binder takes the name of its output file from the last specified ALI
7603 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7604 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7605 The output is an Ada unit in source form that can
7606 be compiled with GNAT unless the -C switch is used in which case the
7607 output is a C source file, which must be compiled using the C compiler.
7608 This compilation occurs automatically as part of the @command{gnatlink}
7609 processing.
7611 Currently the GNAT run time requires a FPU using 80 bits mode
7612 precision. Under targets where this is not the default it is required to
7613 call GNAT.Float_Control.Reset before using floating point numbers (this
7614 include float computation, float input and output) in the Ada code. A
7615 side effect is that this could be the wrong mode for the foreign code
7616 where floating point computation could be broken after this call.
7618 @node Binding Programs with No Main Subprogram
7619 @subsection Binding Programs with No Main Subprogram
7621 @noindent
7622 It is possible to have an Ada program which does not have a main
7623 subprogram. This program will call the elaboration routines of all the
7624 packages, then the finalization routines.
7626 The following switch is used to bind programs organized in this manner:
7628 @table @option
7629 @item ^-z^/ZERO_MAIN^
7630 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7631 Normally the binder checks that the unit name given on the command line
7632 corresponds to a suitable main subprogram. When this switch is used,
7633 a list of ALI files can be given, and the execution of the program
7634 consists of elaboration of these units in an appropriate order.
7635 @end table
7637 @node Command-Line Access
7638 @section Command-Line Access
7640 @noindent
7641 The package @code{Ada.Command_Line} provides access to the command-line
7642 arguments and program name. In order for this interface to operate
7643 correctly, the two variables
7645 @smallexample
7646 @group
7647 int gnat_argc;
7648 char **gnat_argv;
7649 @end group
7650 @end smallexample
7652 @noindent
7653 @findex gnat_argv
7654 @findex gnat_argc
7655 are declared in one of the GNAT library routines. These variables must
7656 be set from the actual @code{argc} and @code{argv} values passed to the
7657 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7658 generates the C main program to automatically set these variables.
7659 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7660 set these variables. If they are not set, the procedures in
7661 @code{Ada.Command_Line} will not be available, and any attempt to use
7662 them will raise @code{Constraint_Error}. If command line access is
7663 required, your main program must set @code{gnat_argc} and
7664 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7667 @node Search Paths for gnatbind
7668 @section Search Paths for @code{gnatbind}
7670 @noindent
7671 The binder takes the name of an ALI file as its argument and needs to
7672 locate source files as well as other ALI files to verify object consistency.
7674 For source files, it follows exactly the same search rules as @command{gcc}
7675 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7676 directories searched are:
7678 @enumerate
7679 @item
7680 The directory containing the ALI file named in the command line, unless
7681 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7683 @item
7684 All directories specified by @option{^-I^/SEARCH^}
7685 switches on the @code{gnatbind}
7686 command line, in the order given.
7688 @item
7689 @findex ADA_PRJ_OBJECTS_FILE
7690 Each of the directories listed in the text file whose name is given
7691 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7693 @noindent
7694 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7695 driver when project files are used. It should not normally be set
7696 by other means.
7698 @item
7699 @findex ADA_OBJECTS_PATH
7700 Each of the directories listed in the value of the
7701 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7702 @ifset unw
7703 Construct this value
7704 exactly as the @code{PATH} environment variable: a list of directory
7705 names separated by colons (semicolons when working with the NT version
7706 of GNAT).
7707 @end ifset
7708 @ifset vms
7709 Normally, define this value as a logical name containing a comma separated
7710 list of directory names.
7712 This variable can also be defined by means of an environment string
7713 (an argument to the HP C exec* set of functions).
7715 Logical Name:
7716 @smallexample
7717 DEFINE ANOTHER_PATH FOO:[BAG]
7718 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7719 @end smallexample
7721 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7722 first, followed by the standard Ada 95
7723 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7724 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7725 (Text_IO, Sequential_IO, etc)
7726 instead of the Ada95 packages. Thus, in order to get the Ada 95
7727 packages by default, ADA_OBJECTS_PATH must be redefined.
7728 @end ifset
7730 @item
7731 The content of the @file{ada_object_path} file which is part of the GNAT
7732 installation tree and is used to store standard libraries such as the
7733 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7734 specified.
7735 @ifclear vms
7736 @ref{Installing a library}
7737 @end ifclear
7738 @end enumerate
7740 @noindent
7741 In the binder the switch @option{^-I^/SEARCH^}
7742 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7743 is used to specify both source and
7744 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7745 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7746 instead if you want to specify
7747 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7748 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7749 if you want to specify library paths
7750 only. This means that for the binder
7751 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7752 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7753 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7754 The binder generates the bind file (a C language source file) in the
7755 current working directory.
7757 @findex Ada
7758 @findex System
7759 @findex Interfaces
7760 @findex GNAT
7761 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7762 children make up the GNAT Run-Time Library, together with the package
7763 GNAT and its children, which contain a set of useful additional
7764 library functions provided by GNAT. The sources for these units are
7765 needed by the compiler and are kept together in one directory. The ALI
7766 files and object files generated by compiling the RTL are needed by the
7767 binder and the linker and are kept together in one directory, typically
7768 different from the directory containing the sources. In a normal
7769 installation, you need not specify these directory names when compiling
7770 or binding. Either the environment variables or the built-in defaults
7771 cause these files to be found.
7773 Besides simplifying access to the RTL, a major use of search paths is
7774 in compiling sources from multiple directories. This can make
7775 development environments much more flexible.
7777 @node Examples of gnatbind Usage
7778 @section Examples of @code{gnatbind} Usage
7780 @noindent
7781 This section contains a number of examples of using the GNAT binding
7782 utility @code{gnatbind}.
7784 @table @code
7785 @item gnatbind hello
7786 The main program @code{Hello} (source program in @file{hello.adb}) is
7787 bound using the standard switch settings. The generated main program is
7788 @file{b~hello.adb}. This is the normal, default use of the binder.
7790 @ifclear vms
7791 @item gnatbind hello -o mainprog.adb
7792 @end ifclear
7793 @ifset vms
7794 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7795 @end ifset
7796 The main program @code{Hello} (source program in @file{hello.adb}) is
7797 bound using the standard switch settings. The generated main program is
7798 @file{mainprog.adb} with the associated spec in
7799 @file{mainprog.ads}. Note that you must specify the body here not the
7800 spec, in the case where the output is in Ada. Note that if this option
7801 is used, then linking must be done manually, since gnatlink will not
7802 be able to find the generated file.
7804 @ifclear vms
7805 @item gnatbind main -C -o mainprog.c -x
7806 @end ifclear
7807 @ifset vms
7808 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7809 @end ifset
7810 The main program @code{Main} (source program in
7811 @file{main.adb}) is bound, excluding source files from the
7812 consistency checking, generating
7813 the file @file{mainprog.c}.
7815 @ifclear vms
7816 @item gnatbind -x main_program -C -o mainprog.c
7817 This command is exactly the same as the previous example. Switches may
7818 appear anywhere in the command line, and single letter switches may be
7819 combined into a single switch.
7820 @end ifclear
7822 @ifclear vms
7823 @item gnatbind -n math dbase -C -o ada-control.c
7824 @end ifclear
7825 @ifset vms
7826 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7827 @end ifset
7828 The main program is in a language other than Ada, but calls to
7829 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7830 to @code{gnatbind} generates the file @file{ada-control.c} containing
7831 the @code{adainit} and @code{adafinal} routines to be called before and
7832 after accessing the Ada units.
7833 @end table
7835 @c ------------------------------------
7836 @node Linking Using gnatlink
7837 @chapter Linking Using @command{gnatlink}
7838 @c ------------------------------------
7839 @findex gnatlink
7841 @noindent
7842 This chapter discusses @command{gnatlink}, a tool that links
7843 an Ada program and builds an executable file. This utility
7844 invokes the system linker ^(via the @command{gcc} command)^^
7845 with a correct list of object files and library references.
7846 @command{gnatlink} automatically determines the list of files and
7847 references for the Ada part of a program. It uses the binder file
7848 generated by the @command{gnatbind} to determine this list.
7850 @menu
7851 * Running gnatlink::
7852 * Switches for gnatlink::
7853 * Setting Stack Size from gnatlink::
7854 * Setting Heap Size from gnatlink::
7855 @end menu
7857 @node Running gnatlink
7858 @section Running @command{gnatlink}
7860 @noindent
7861 The form of the @command{gnatlink} command is
7863 @smallexample
7864 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7865            [@var{non-Ada objects}] [@var{linker options}]
7866 @end smallexample
7868 @noindent
7869 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
7870 non-Ada objects
7871 or linker options) may be in any order, provided that no non-Ada object may
7872 be mistaken for a main @file{ALI} file.
7873 Any file name @file{F} without the @file{.ali}
7874 extension will be taken as the main @file{ALI} file if a file exists
7875 whose name is the concatenation of @file{F} and @file{.ali}.
7877 @noindent
7878 @file{@var{mainprog}.ali} references the ALI file of the main program.
7879 The @file{.ali} extension of this file can be omitted. From this
7880 reference, @command{gnatlink} locates the corresponding binder file
7881 @file{b~@var{mainprog}.adb} and, using the information in this file along
7882 with the list of non-Ada objects and linker options, constructs a
7883 linker command file to create the executable.
7885 The arguments other than the @command{gnatlink} switches and the main
7886 @file{ALI} file are passed to the linker uninterpreted.
7887 They typically include the names of
7888 object files for units written in other languages than Ada and any library
7889 references required to resolve references in any of these foreign language
7890 units, or in @code{Import} pragmas in any Ada units.
7892 @var{linker options} is an optional list of linker specific
7893 switches.
7894 The default linker called by gnatlink is @var{gcc} which in
7895 turn calls the appropriate system linker.
7896 Standard options for the linker such as @option{-lmy_lib} or
7897 @option{-Ldir} can be added as is.
7898 For options that are not recognized by
7899 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7900 @option{-Wl,}.
7901 Refer to the GCC documentation for
7902 details. Here is an example showing how to generate a linker map:
7904 @ifclear vms
7905 @smallexample
7906 $ gnatlink my_prog -Wl,-Map,MAPFILE
7907 @end smallexample
7908 @end ifclear
7910 @ifset vms
7911 <<Need example for VMS>>
7912 @end ifset
7914 Using @var{linker options} it is possible to set the program stack and
7915 heap size. See @ref{Setting Stack Size from gnatlink} and
7916 @ref{Setting Heap Size from gnatlink}.
7918 @command{gnatlink} determines the list of objects required by the Ada
7919 program and prepends them to the list of objects passed to the linker.
7920 @command{gnatlink} also gathers any arguments set by the use of
7921 @code{pragma Linker_Options} and adds them to the list of arguments
7922 presented to the linker.
7924 @ifset vms
7925 @command{gnatlink} accepts the following types of extra files on the command
7926 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7927 options files (.OPT). These are recognized and handled according to their
7928 extension.
7929 @end ifset
7931 @node Switches for gnatlink
7932 @section Switches for @command{gnatlink}
7934 @noindent
7935 The following switches are available with the @command{gnatlink} utility:
7937 @table @option
7938 @c !sort!
7940 @item ^-A^/BIND_FILE=ADA^
7941 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
7942 The binder has generated code in Ada. This is the default.
7944 @item ^-C^/BIND_FILE=C^
7945 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
7946 If instead of generating a file in Ada, the binder has generated one in
7947 C, then the linker needs to know about it. Use this switch to signal
7948 to @command{gnatlink} that the binder has generated C code rather than
7949 Ada code.
7951 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7952 @cindex Command line length
7953 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
7954 On some targets, the command line length is limited, and @command{gnatlink}
7955 will generate a separate file for the linker if the list of object files
7956 is too long.
7957 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7958 to be generated even if
7959 the limit is not exceeded. This is useful in some cases to deal with
7960 special situations where the command line length is exceeded.
7962 @item ^-g^/DEBUG^
7963 @cindex Debugging information, including
7964 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
7965 The option to include debugging information causes the Ada bind file (in
7966 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7967 @option{^-g^/DEBUG^}.
7968 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7969 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7970 Without @option{^-g^/DEBUG^}, the binder removes these files by
7971 default. The same procedure apply if a C bind file was generated using
7972 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7973 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7975 @item ^-n^/NOCOMPILE^
7976 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
7977 Do not compile the file generated by the binder. This may be used when
7978 a link is rerun with different options, but there is no need to recompile
7979 the binder file.
7981 @item ^-v^/VERBOSE^
7982 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
7983 Causes additional information to be output, including a full list of the
7984 included object files. This switch option is most useful when you want
7985 to see what set of object files are being used in the link step.
7987 @item ^-v -v^/VERBOSE/VERBOSE^
7988 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
7989 Very verbose mode. Requests that the compiler operate in verbose mode when
7990 it compiles the binder file, and that the system linker run in verbose mode.
7992 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7993 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
7994 @var{exec-name} specifies an alternate name for the generated
7995 executable program. If this switch is omitted, the executable has the same
7996 name as the main unit. For example, @code{gnatlink try.ali} creates
7997 an executable called @file{^try^TRY.EXE^}.
7999 @ifclear vms
8000 @item -b @var{target}
8001 @cindex @option{-b} (@command{gnatlink})
8002 Compile your program to run on @var{target}, which is the name of a
8003 system configuration. You must have a GNAT cross-compiler built if
8004 @var{target} is not the same as your host system.
8006 @item -B@var{dir}
8007 @cindex @option{-B} (@command{gnatlink})
8008 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8009 from @var{dir} instead of the default location. Only use this switch
8010 when multiple versions of the GNAT compiler are available. See the
8011 @command{gcc} manual page for further details. You would normally use the
8012 @option{-b} or @option{-V} switch instead.
8014 @item --GCC=@var{compiler_name}
8015 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8016 Program used for compiling the binder file. The default is
8017 @command{gcc}. You need to use quotes around @var{compiler_name} if
8018 @code{compiler_name} contains spaces or other separator characters.
8019 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8020 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8021 inserted after your command name. Thus in the above example the compiler
8022 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8023 A limitation of this syntax is that the name and path name of the executable
8024 itself must not include any embedded spaces. If several
8025 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8026 is taken into account. However, all the additional switches are also taken
8027 into account. Thus,
8028 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8029 @option{--GCC="bar -x -y -z -t"}.
8031 @item --LINK=@var{name}
8032 @cindex @option{--LINK=} (@command{gnatlink})
8033 @var{name} is the name of the linker to be invoked. This is especially
8034 useful in mixed language programs since languages such as C++ require
8035 their own linker to be used. When this switch is omitted, the default
8036 name for the linker is @command{gcc}. When this switch is used, the
8037 specified linker is called instead of @command{gcc} with exactly the same
8038 parameters that would have been passed to @command{gcc} so if the desired
8039 linker requires different parameters it is necessary to use a wrapper
8040 script that massages the parameters before invoking the real linker. It
8041 may be useful to control the exact invocation by using the verbose
8042 switch.
8044 @end ifclear
8046 @ifset vms
8047 @item /DEBUG=TRACEBACK
8048 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8049 This qualifier causes sufficient information to be included in the
8050 executable file to allow a traceback, but does not include the full
8051 symbol information needed by the debugger.
8053 @item /IDENTIFICATION="<string>"
8054 @code{"<string>"} specifies the string to be stored in the image file
8055 identification field in the image header.
8056 It overrides any pragma @code{Ident} specified string.
8058 @item /NOINHIBIT-EXEC
8059 Generate the executable file even if there are linker warnings.
8061 @item /NOSTART_FILES
8062 Don't link in the object file containing the ``main'' transfer address.
8063 Used when linking with a foreign language main program compiled with an
8064 HP compiler.
8066 @item /STATIC
8067 Prefer linking with object libraries over sharable images, even without
8068 /DEBUG.
8069 @end ifset
8071 @end table
8073 @node Setting Stack Size from gnatlink
8074 @section Setting Stack Size from @command{gnatlink}
8076 @noindent
8077 Under Windows systems, it is possible to specify the program stack size from
8078 @command{gnatlink} using either:
8080 @itemize @bullet
8082 @item using @option{-Xlinker} linker option
8084 @smallexample
8085 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
8086 @end smallexample
8088 This sets the stack reserve size to 0x10000 bytes and the stack commit
8089 size to 0x1000 bytes.
8091 @item using @option{-Wl} linker option
8093 @smallexample
8094 $ gnatlink hello -Wl,--stack=0x1000000
8095 @end smallexample
8097 This sets the stack reserve size to 0x1000000 bytes. Note that with
8098 @option{-Wl} option it is not possible to set the stack commit size
8099 because the coma is a separator for this option.
8101 @end itemize
8103 @node Setting Heap Size from gnatlink
8104 @section Setting Heap Size from @command{gnatlink}
8106 @noindent
8107 Under Windows systems, it is possible to specify the program heap size from
8108 @command{gnatlink} using either:
8110 @itemize @bullet
8112 @item using @option{-Xlinker} linker option
8114 @smallexample
8115 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
8116 @end smallexample
8118 This sets the heap reserve size to 0x10000 bytes and the heap commit
8119 size to 0x1000 bytes.
8121 @item using @option{-Wl} linker option
8123 @smallexample
8124 $ gnatlink hello -Wl,--heap=0x1000000
8125 @end smallexample
8127 This sets the heap reserve size to 0x1000000 bytes. Note that with
8128 @option{-Wl} option it is not possible to set the heap commit size
8129 because the coma is a separator for this option.
8131 @end itemize
8133 @node The GNAT Make Program gnatmake
8134 @chapter The GNAT Make Program @command{gnatmake}
8135 @findex gnatmake
8137 @menu
8138 * Running gnatmake::
8139 * Switches for gnatmake::
8140 * Mode Switches for gnatmake::
8141 * Notes on the Command Line::
8142 * How gnatmake Works::
8143 * Examples of gnatmake Usage::
8144 @end menu
8145 @noindent
8146 A typical development cycle when working on an Ada program consists of
8147 the following steps:
8149 @enumerate
8150 @item
8151 Edit some sources to fix bugs.
8153 @item
8154 Add enhancements.
8156 @item
8157 Compile all sources affected.
8159 @item
8160 Rebind and relink.
8162 @item
8163 Test.
8164 @end enumerate
8166 @noindent
8167 The third step can be tricky, because not only do the modified files
8168 @cindex Dependency rules
8169 have to be compiled, but any files depending on these files must also be
8170 recompiled. The dependency rules in Ada can be quite complex, especially
8171 in the presence of overloading, @code{use} clauses, generics and inlined
8172 subprograms.
8174 @command{gnatmake} automatically takes care of the third and fourth steps
8175 of this process. It determines which sources need to be compiled,
8176 compiles them, and binds and links the resulting object files.
8178 Unlike some other Ada make programs, the dependencies are always
8179 accurately recomputed from the new sources. The source based approach of
8180 the GNAT compilation model makes this possible. This means that if
8181 changes to the source program cause corresponding changes in
8182 dependencies, they will always be tracked exactly correctly by
8183 @command{gnatmake}.
8185 @node Running gnatmake
8186 @section Running @command{gnatmake}
8188 @noindent
8189 The usual form of the @command{gnatmake} command is
8191 @smallexample
8192 $ gnatmake [@var{switches}] @var{file_name}
8193       [@var{file_names}] [@var{mode_switches}]
8194 @end smallexample
8196 @noindent
8197 The only required argument is one @var{file_name}, which specifies
8198 a compilation unit that is a main program. Several @var{file_names} can be
8199 specified: this will result in several executables being built.
8200 If @code{switches} are present, they can be placed before the first
8201 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8202 If @var{mode_switches} are present, they must always be placed after
8203 the last @var{file_name} and all @code{switches}.
8205 If you are using standard file extensions (.adb and .ads), then the
8206 extension may be omitted from the @var{file_name} arguments. However, if
8207 you are using non-standard extensions, then it is required that the
8208 extension be given. A relative or absolute directory path can be
8209 specified in a @var{file_name}, in which case, the input source file will
8210 be searched for in the specified directory only. Otherwise, the input
8211 source file will first be searched in the directory where
8212 @command{gnatmake} was invoked and if it is not found, it will be search on
8213 the source path of the compiler as described in
8214 @ref{Search Paths and the Run-Time Library (RTL)}.
8216 All @command{gnatmake} output (except when you specify
8217 @option{^-M^/DEPENDENCIES_LIST^}) is to
8218 @file{stderr}. The output produced by the
8219 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8220 @file{stdout}.
8222 @node Switches for gnatmake
8223 @section Switches for @command{gnatmake}
8225 @noindent
8226 You may specify any of the following switches to @command{gnatmake}:
8228 @table @option
8229 @c !sort!
8230 @ifclear vms
8231 @item --GCC=@var{compiler_name}
8232 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8233 Program used for compiling. The default is `@command{gcc}'. You need to use
8234 quotes around @var{compiler_name} if @code{compiler_name} contains
8235 spaces or other separator characters. As an example @option{--GCC="foo -x
8236 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8237 compiler. A limitation of this syntax is that the name and path name of
8238 the executable itself must not include any embedded spaces. Note that
8239 switch @option{-c} is always inserted after your command name. Thus in the
8240 above example the compiler command that will be used by @command{gnatmake}
8241 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8242 used, only the last @var{compiler_name} is taken into account. However,
8243 all the additional switches are also taken into account. Thus,
8244 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8245 @option{--GCC="bar -x -y -z -t"}.
8247 @item --GNATBIND=@var{binder_name}
8248 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8249 Program used for binding. The default is `@code{gnatbind}'. You need to
8250 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8251 or other separator characters. As an example @option{--GNATBIND="bar -x
8252 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8253 binder. Binder switches that are normally appended by @command{gnatmake}
8254 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8255 A limitation of this syntax is that the name and path name of the executable
8256 itself must not include any embedded spaces.
8258 @item --GNATLINK=@var{linker_name}
8259 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8260 Program used for linking. The default is `@command{gnatlink}'. You need to
8261 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8262 or other separator characters. As an example @option{--GNATLINK="lan -x
8263 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8264 linker. Linker switches that are normally appended by @command{gnatmake} to
8265 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8266 A limitation of this syntax is that the name and path name of the executable
8267 itself must not include any embedded spaces.
8269 @end ifclear
8271 @item ^-a^/ALL_FILES^
8272 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8273 Consider all files in the make process, even the GNAT internal system
8274 files (for example, the predefined Ada library files), as well as any
8275 locked files. Locked files are files whose ALI file is write-protected.
8276 By default,
8277 @command{gnatmake} does not check these files,
8278 because the assumption is that the GNAT internal files are properly up
8279 to date, and also that any write protected ALI files have been properly
8280 installed. Note that if there is an installation problem, such that one
8281 of these files is not up to date, it will be properly caught by the
8282 binder.
8283 You may have to specify this switch if you are working on GNAT
8284 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8285 in conjunction with @option{^-f^/FORCE_COMPILE^}
8286 if you need to recompile an entire application,
8287 including run-time files, using special configuration pragmas,
8288 such as a @code{Normalize_Scalars} pragma.
8290 By default
8291 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8292 internal files with
8293 @ifclear vms
8294 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8295 @end ifclear
8296 @ifset vms
8297 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8298 @end ifset
8300 @item ^-b^/ACTIONS=BIND^
8301 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8302 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8303 compilation and binding, but no link.
8304 Can be combined with @option{^-l^/ACTIONS=LINK^}
8305 to do binding and linking. When not combined with
8306 @option{^-c^/ACTIONS=COMPILE^}
8307 all the units in the closure of the main program must have been previously
8308 compiled and must be up to date. The root unit specified by @var{file_name}
8309 may be given without extension, with the source extension or, if no GNAT
8310 Project File is specified, with the ALI file extension.
8312 @item ^-c^/ACTIONS=COMPILE^
8313 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8314 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8315 is also specified. Do not perform linking, except if both
8316 @option{^-b^/ACTIONS=BIND^} and
8317  @option{^-l^/ACTIONS=LINK^} are also specified.
8318 If the root unit specified by @var{file_name} is not a main unit, this is the
8319 default. Otherwise @command{gnatmake} will attempt binding and linking
8320 unless all objects are up to date and the executable is more recent than
8321 the objects.
8323 @item ^-C^/MAPPING^
8324 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8325 Use a temporary mapping file. A mapping file is a way to communicate to the
8326 compiler two mappings: from unit names to file names (without any directory
8327 information) and from file names to path names (with full directory
8328 information). These mappings are used by the compiler to short-circuit the path
8329 search. When @command{gnatmake} is invoked with this switch, it will create
8330 a temporary mapping file, initially populated by the project manager,
8331 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8332 Each invocation of the compiler will add the newly accessed sources to the
8333 mapping file. This will improve the source search during the next invocation
8334 of the compiler.
8336 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8337 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8338 Use a specific mapping file. The file, specified as a path name (absolute or
8339 relative) by this switch, should already exist, otherwise the switch is
8340 ineffective. The specified mapping file will be communicated to the compiler.
8341 This switch is not compatible with a project file
8342 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8343 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8345 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8346 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8347 Put all object files and ALI file in directory @var{dir}.
8348 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8349 and ALI files go in the current working directory.
8351 This switch cannot be used when using a project file.
8353 @ifclear vms
8354 @item -eL
8355 @cindex @option{-eL} (@command{gnatmake})
8356 Follow all symbolic links when processing project files.
8357 @end ifclear
8359 @item ^-f^/FORCE_COMPILE^
8360 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8361 Force recompilations. Recompile all sources, even though some object
8362 files may be up to date, but don't recompile predefined or GNAT internal
8363 files or locked files (files with a write-protected ALI file),
8364 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8366 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8367 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8368 When using project files, if some errors or warnings are detected during
8369 parsing and verbose mode is not in effect (no use of switch
8370 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8371 file, rather than its simple file name.
8373 @item ^-i^/IN_PLACE^
8374 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8375 In normal mode, @command{gnatmake} compiles all object files and ALI files
8376 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8377 then instead object files and ALI files that already exist are overwritten
8378 in place. This means that once a large project is organized into separate
8379 directories in the desired manner, then @command{gnatmake} will automatically
8380 maintain and update this organization. If no ALI files are found on the
8381 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8382 the new object and ALI files are created in the
8383 directory containing the source being compiled. If another organization
8384 is desired, where objects and sources are kept in different directories,
8385 a useful technique is to create dummy ALI files in the desired directories.
8386 When detecting such a dummy file, @command{gnatmake} will be forced to
8387 recompile the corresponding source file, and it will be put the resulting
8388 object and ALI files in the directory where it found the dummy file.
8390 @item ^-j^/PROCESSES=^@var{n}
8391 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8392 @cindex Parallel make
8393 Use @var{n} processes to carry out the (re)compilations. On a
8394 multiprocessor machine compilations will occur in parallel. In the
8395 event of compilation errors, messages from various compilations might
8396 get interspersed (but @command{gnatmake} will give you the full ordered
8397 list of failing compiles at the end). If this is problematic, rerun
8398 the make process with n set to 1 to get a clean list of messages.
8400 @item ^-k^/CONTINUE_ON_ERROR^
8401 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8402 Keep going. Continue as much as possible after a compilation error. To
8403 ease the programmer's task in case of compilation errors, the list of
8404 sources for which the compile fails is given when @command{gnatmake}
8405 terminates.
8407 If @command{gnatmake} is invoked with several @file{file_names} and with this
8408 switch, if there are compilation errors when building an executable,
8409 @command{gnatmake} will not attempt to build the following executables.
8411 @item ^-l^/ACTIONS=LINK^
8412 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8413 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8414 and linking. Linking will not be performed if combined with
8415 @option{^-c^/ACTIONS=COMPILE^}
8416 but not with @option{^-b^/ACTIONS=BIND^}.
8417 When not combined with @option{^-b^/ACTIONS=BIND^}
8418 all the units in the closure of the main program must have been previously
8419 compiled and must be up to date, and the main program needs to have been bound.
8420 The root unit specified by @var{file_name}
8421 may be given without extension, with the source extension or, if no GNAT
8422 Project File is specified, with the ALI file extension.
8424 @item ^-m^/MINIMAL_RECOMPILATION^
8425 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8426 Specify that the minimum necessary amount of recompilations
8427 be performed. In this mode @command{gnatmake} ignores time
8428 stamp differences when the only
8429 modifications to a source file consist in adding/removing comments,
8430 empty lines, spaces or tabs. This means that if you have changed the
8431 comments in a source file or have simply reformatted it, using this
8432 switch will tell gnatmake not to recompile files that depend on it
8433 (provided other sources on which these files depend have undergone no
8434 semantic modifications). Note that the debugging information may be
8435 out of date with respect to the sources if the @option{-m} switch causes
8436 a compilation to be switched, so the use of this switch represents a
8437 trade-off between compilation time and accurate debugging information.
8439 @item ^-M^/DEPENDENCIES_LIST^
8440 @cindex Dependencies, producing list
8441 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8442 Check if all objects are up to date. If they are, output the object
8443 dependences to @file{stdout} in a form that can be directly exploited in
8444 a @file{Makefile}. By default, each source file is prefixed with its
8445 (relative or absolute) directory name. This name is whatever you
8446 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8447 and @option{^-I^/SEARCH^} switches. If you use
8448 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8449 @option{^-q^/QUIET^}
8450 (see below), only the source file names,
8451 without relative paths, are output. If you just specify the
8452 @option{^-M^/DEPENDENCIES_LIST^}
8453 switch, dependencies of the GNAT internal system files are omitted. This
8454 is typically what you want. If you also specify
8455 the @option{^-a^/ALL_FILES^} switch,
8456 dependencies of the GNAT internal files are also listed. Note that
8457 dependencies of the objects in external Ada libraries (see switch
8458 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8459 are never reported.
8461 @item ^-n^/DO_OBJECT_CHECK^
8462 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8463 Don't compile, bind, or link. Checks if all objects are up to date.
8464 If they are not, the full name of the first file that needs to be
8465 recompiled is printed.
8466 Repeated use of this option, followed by compiling the indicated source
8467 file, will eventually result in recompiling all required units.
8469 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8470 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8471 Output executable name. The name of the final executable program will be
8472 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8473 name for the executable will be the name of the input file in appropriate form
8474 for an executable file on the host system.
8476 This switch cannot be used when invoking @command{gnatmake} with several
8477 @file{file_names}.
8479 @item ^-P^/PROJECT_FILE=^@var{project}
8480 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8481 Use project file @var{project}. Only one such switch can be used.
8482 @xref{gnatmake and Project Files}.
8484 @item ^-q^/QUIET^
8485 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8486 Quiet. When this flag is not set, the commands carried out by
8487 @command{gnatmake} are displayed.
8489 @item ^-s^/SWITCH_CHECK/^
8490 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8491 Recompile if compiler switches have changed since last compilation.
8492 All compiler switches but -I and -o are taken into account in the
8493 following way:
8494 orders between different ``first letter'' switches are ignored, but
8495 orders between same switches are taken into account. For example,
8496 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8497 is equivalent to @option{-O -g}.
8499 This switch is recommended when Integrated Preprocessing is used.
8501 @item ^-u^/UNIQUE^
8502 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8503 Unique. Recompile at most the main files. It implies -c. Combined with
8504 -f, it is equivalent to calling the compiler directly. Note that using
8505 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8506 (@pxref{Project Files and Main Subprograms}).
8508 @item ^-U^/ALL_PROJECTS^
8509 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8510 When used without a project file or with one or several mains on the command
8511 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8512 on the command line, all sources of all project files are checked and compiled
8513 if not up to date, and libraries are rebuilt, if necessary.
8515 @item ^-v^/REASONS^
8516 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8517 Verbose. Display the reason for all recompilations @command{gnatmake}
8518 decides are necessary, with the highest verbosity level.
8520 @item ^-vl^/LOW_VERBOSITY^
8521 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8522 Verbosity level Low. Display fewer lines than in verbosity Medium.
8524 @item ^-vm^/MEDIUM_VERBOSITY^
8525 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8526 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8528 @item ^-vh^/HIGH_VERBOSITY^
8529 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8530 Verbosity level High. Equivalent to ^-v^/REASONS^.
8532 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8533 Indicate the verbosity of the parsing of GNAT project files.
8534 @xref{Switches Related to Project Files}.
8536 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8537 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8538 Indicate that sources that are not part of any Project File may be compiled.
8539 Normally, when using Project Files, only sources that are part of a Project
8540 File may be compile. When this switch is used, a source outside of all Project
8541 Files may be compiled. The ALI file and the object file will be put in the
8542 object directory of the main Project. The compilation switches used will only
8543 be those specified on the command line.
8545 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8546 Indicate that external variable @var{name} has the value @var{value}.
8547 The Project Manager will use this value for occurrences of
8548 @code{external(name)} when parsing the project file.
8549 @xref{Switches Related to Project Files}.
8551 @item ^-z^/NOMAIN^
8552 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8553 No main subprogram. Bind and link the program even if the unit name
8554 given on the command line is a package name. The resulting executable
8555 will execute the elaboration routines of the package and its closure,
8556 then the finalization routines.
8558 @item ^-g^/DEBUG^
8559 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8560 Enable debugging. This switch is simply passed to the compiler and to the
8561 linker.
8563 @end table
8565 @table @asis
8566 @item @command{gcc} @asis{switches}
8567 @ifclear vms
8568 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8569 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8570 @end ifclear
8571 @ifset vms
8572 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8573 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8574 automatically treated as a compiler switch, and passed on to all
8575 compilations that are carried out.
8576 @end ifset
8577 @end table
8579 @noindent
8580 Source and library search path switches:
8582 @table @option
8583 @c !sort!
8584 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8585 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8586 When looking for source files also look in directory @var{dir}.
8587 The order in which source files search is undertaken is
8588 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8590 @item ^-aL^/SKIP_MISSING=^@var{dir}
8591 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8592 Consider @var{dir} as being an externally provided Ada library.
8593 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8594 files have been located in directory @var{dir}. This allows you to have
8595 missing bodies for the units in @var{dir} and to ignore out of date bodies
8596 for the same units. You still need to specify
8597 the location of the specs for these units by using the switches
8598 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8599 or @option{^-I^/SEARCH=^@var{dir}}.
8600 Note: this switch is provided for compatibility with previous versions
8601 of @command{gnatmake}. The easier method of causing standard libraries
8602 to be excluded from consideration is to write-protect the corresponding
8603 ALI files.
8605 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8606 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8607 When searching for library and object files, look in directory
8608 @var{dir}. The order in which library files are searched is described in
8609 @ref{Search Paths for gnatbind}.
8611 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8612 @cindex Search paths, for @command{gnatmake}
8613 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8614 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8615 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8617 @item ^-I^/SEARCH=^@var{dir}
8618 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8619 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8620 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8622 @item ^-I-^/NOCURRENT_DIRECTORY^
8623 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8624 @cindex Source files, suppressing search
8625 Do not look for source files in the directory containing the source
8626 file named in the command line.
8627 Do not look for ALI or object files in the directory
8628 where @command{gnatmake} was invoked.
8630 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8631 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8632 @cindex Linker libraries
8633 Add directory @var{dir} to the list of directories in which the linker
8634 will search for libraries. This is equivalent to
8635 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8636 @ifclear vms
8637 Furthermore, under Windows, the sources pointed to by the libraries path
8638 set in the registry are not searched for.
8639 @end ifclear
8641 @item -nostdinc
8642 @cindex @option{-nostdinc} (@command{gnatmake})
8643 Do not look for source files in the system default directory.
8645 @item -nostdlib
8646 @cindex @option{-nostdlib} (@command{gnatmake})
8647 Do not look for library files in the system default directory.
8649 @item --RTS=@var{rts-path}
8650 @cindex @option{--RTS} (@command{gnatmake})
8651 Specifies the default location of the runtime library. GNAT looks for the
8652 runtime
8653 in the following directories, and stops as soon as a valid runtime is found
8654 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8655 @file{ada_object_path} present):
8657 @itemize @bullet
8658 @item <current directory>/$rts_path
8660 @item <default-search-dir>/$rts_path
8662 @item <default-search-dir>/rts-$rts_path
8663 @end itemize
8665 @noindent
8666 The selected path is handled like a normal RTS path.
8668 @end table
8670 @node Mode Switches for gnatmake
8671 @section Mode Switches for @command{gnatmake}
8673 @noindent
8674 The mode switches (referred to as @code{mode_switches}) allow the
8675 inclusion of switches that are to be passed to the compiler itself, the
8676 binder or the linker. The effect of a mode switch is to cause all
8677 subsequent switches up to the end of the switch list, or up to the next
8678 mode switch, to be interpreted as switches to be passed on to the
8679 designated component of GNAT.
8681 @table @option
8682 @c !sort!
8683 @item -cargs @var{switches}
8684 @cindex @option{-cargs} (@command{gnatmake})
8685 Compiler switches. Here @var{switches} is a list of switches
8686 that are valid switches for @command{gcc}. They will be passed on to
8687 all compile steps performed by @command{gnatmake}.
8689 @item -bargs @var{switches}
8690 @cindex @option{-bargs} (@command{gnatmake})
8691 Binder switches. Here @var{switches} is a list of switches
8692 that are valid switches for @code{gnatbind}. They will be passed on to
8693 all bind steps performed by @command{gnatmake}.
8695 @item -largs @var{switches}
8696 @cindex @option{-largs} (@command{gnatmake})
8697 Linker switches. Here @var{switches} is a list of switches
8698 that are valid switches for @command{gnatlink}. They will be passed on to
8699 all link steps performed by @command{gnatmake}.
8701 @item -margs @var{switches}
8702 @cindex @option{-margs} (@command{gnatmake})
8703 Make switches. The switches are directly interpreted by @command{gnatmake},
8704 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8705 or @option{-largs}.
8706 @end table
8708 @node Notes on the Command Line
8709 @section Notes on the Command Line
8711 @noindent
8712 This section contains some additional useful notes on the operation
8713 of the @command{gnatmake} command.
8715 @itemize @bullet
8716 @item
8717 @cindex Recompilation, by @command{gnatmake}
8718 If @command{gnatmake} finds no ALI files, it recompiles the main program
8719 and all other units required by the main program.
8720 This means that @command{gnatmake}
8721 can be used for the initial compile, as well as during subsequent steps of
8722 the development cycle.
8724 @item
8725 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8726 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8727 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8728 warning.
8730 @item
8731 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8732 is used to specify both source and
8733 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8734 instead if you just want to specify
8735 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8736 if you want to specify library paths
8737 only.
8739 @item
8740 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8741 This may conveniently be used to exclude standard libraries from
8742 consideration and in particular it means that the use of the
8743 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8744 unless @option{^-a^/ALL_FILES^} is also specified.
8746 @item
8747 @command{gnatmake} has been designed to make the use of Ada libraries
8748 particularly convenient. Assume you have an Ada library organized
8749 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8750 of your Ada compilation units,
8751 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8752 specs of these units, but no bodies. Then to compile a unit
8753 stored in @code{main.adb}, which uses this Ada library you would just type
8755 @smallexample
8756 @ifclear vms
8757 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8758 @end ifclear
8759 @ifset vms
8760 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8761            /SKIP_MISSING=@i{[OBJ_DIR]} main
8762 @end ifset
8763 @end smallexample
8765 @item
8766 Using @command{gnatmake} along with the
8767 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8768 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8769 this switch,
8770 you can update the comments/format of your
8771 source files without having to recompile everything. Note, however, that
8772 adding or deleting lines in a source files may render its debugging
8773 info obsolete. If the file in question is a spec, the impact is rather
8774 limited, as that debugging info will only be useful during the
8775 elaboration phase of your program. For bodies the impact can be more
8776 significant. In all events, your debugger will warn you if a source file
8777 is more recent than the corresponding object, and alert you to the fact
8778 that the debugging information may be out of date.
8779 @end itemize
8781 @node How gnatmake Works
8782 @section How @command{gnatmake} Works
8784 @noindent
8785 Generally @command{gnatmake} automatically performs all necessary
8786 recompilations and you don't need to worry about how it works. However,
8787 it may be useful to have some basic understanding of the @command{gnatmake}
8788 approach and in particular to understand how it uses the results of
8789 previous compilations without incorrectly depending on them.
8791 First a definition: an object file is considered @dfn{up to date} if the
8792 corresponding ALI file exists and if all the source files listed in the
8793 dependency section of this ALI file have time stamps matching those in
8794 the ALI file. This means that neither the source file itself nor any
8795 files that it depends on have been modified, and hence there is no need
8796 to recompile this file.
8798 @command{gnatmake} works by first checking if the specified main unit is up
8799 to date. If so, no compilations are required for the main unit. If not,
8800 @command{gnatmake} compiles the main program to build a new ALI file that
8801 reflects the latest sources. Then the ALI file of the main unit is
8802 examined to find all the source files on which the main program depends,
8803 and @command{gnatmake} recursively applies the above procedure on all these
8804 files.
8806 This process ensures that @command{gnatmake} only trusts the dependencies
8807 in an existing ALI file if they are known to be correct. Otherwise it
8808 always recompiles to determine a new, guaranteed accurate set of
8809 dependencies. As a result the program is compiled ``upside down'' from what may
8810 be more familiar as the required order of compilation in some other Ada
8811 systems. In particular, clients are compiled before the units on which
8812 they depend. The ability of GNAT to compile in any order is critical in
8813 allowing an order of compilation to be chosen that guarantees that
8814 @command{gnatmake} will recompute a correct set of new dependencies if
8815 necessary.
8817 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8818 imported by several of the executables, it will be recompiled at most once.
8820 Note: when using non-standard naming conventions
8821 (@pxref{Using Other File Names}), changing through a configuration pragmas
8822 file the version of a source and invoking @command{gnatmake} to recompile may
8823 have no effect, if the previous version of the source is still accessible
8824 by @command{gnatmake}. It may be necessary to use the switch
8825 ^-f^/FORCE_COMPILE^.
8827 @node Examples of gnatmake Usage
8828 @section Examples of @command{gnatmake} Usage
8830 @table @code
8831 @item gnatmake hello.adb
8832 Compile all files necessary to bind and link the main program
8833 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8834 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8836 @item gnatmake main1 main2 main3
8837 Compile all files necessary to bind and link the main programs
8838 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8839 (containing unit @code{Main2}) and @file{main3.adb}
8840 (containing unit @code{Main3}) and bind and link the resulting object files
8841 to generate three executable files @file{^main1^MAIN1.EXE^},
8842 @file{^main2^MAIN2.EXE^}
8843 and @file{^main3^MAIN3.EXE^}.
8845 @ifclear vms
8846 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8847 @end ifclear
8849 @ifset vms
8850 @item gnatmake Main_Unit /QUIET
8851    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8852    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8853 @end ifset
8854 Compile all files necessary to bind and link the main program unit
8855 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8856 be done with optimization level 2 and the order of elaboration will be
8857 listed by the binder. @command{gnatmake} will operate in quiet mode, not
8858 displaying commands it is executing.
8859 @end table
8861 @c *************************
8862 @node Improving Performance
8863 @chapter Improving Performance
8864 @cindex Improving performance
8866 @noindent
8867 This chapter presents several topics related to program performance.
8868 It first describes some of the tradeoffs that need to be considered
8869 and some of the techniques for making your program run faster.
8870 It then documents the @command{gnatelim} tool, which can reduce
8871 the size of program executables.
8873 @ifnottex
8874 @menu
8875 * Performance Considerations::
8876 * Reducing the Size of Ada Executables with gnatelim::
8877 @end menu
8878 @end ifnottex
8880 @c *****************************
8881 @node Performance Considerations
8882 @section Performance Considerations
8884 @noindent
8885 The GNAT system provides a number of options that allow a trade-off
8886 between
8888 @itemize @bullet
8889 @item
8890 performance of the generated code
8892 @item
8893 speed of compilation
8895 @item
8896 minimization of dependences and recompilation
8898 @item
8899 the degree of run-time checking.
8900 @end itemize
8902 @noindent
8903 The defaults (if no options are selected) aim at improving the speed
8904 of compilation and minimizing dependences, at the expense of performance
8905 of the generated code:
8907 @itemize @bullet
8908 @item
8909 no optimization
8911 @item
8912 no inlining of subprogram calls
8914 @item
8915 all run-time checks enabled except overflow and elaboration checks
8916 @end itemize
8918 @noindent
8919 These options are suitable for most program development purposes. This
8920 chapter describes how you can modify these choices, and also provides
8921 some guidelines on debugging optimized code.
8923 @menu
8924 * Controlling Run-Time Checks::
8925 * Use of Restrictions::
8926 * Optimization Levels::
8927 * Debugging Optimized Code::
8928 * Inlining of Subprograms::
8929 * Other Optimization Switches::
8930 * Optimization and Strict Aliasing::
8932 @ifset vms
8933 * Coverage Analysis::
8934 @end ifset
8935 @end menu
8937 @node Controlling Run-Time Checks
8938 @subsection Controlling Run-Time Checks
8940 @noindent
8941 By default, GNAT generates all run-time checks, except arithmetic overflow
8942 checking for integer operations and checks for access before elaboration on
8943 subprogram calls. The latter are not required in default mode, because all
8944 necessary checking is done at compile time.
8945 @cindex @option{-gnatp} (@command{gcc})
8946 @cindex @option{-gnato} (@command{gcc})
8947 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8948 be modified. @xref{Run-Time Checks}.
8950 Our experience is that the default is suitable for most development
8951 purposes.
8953 We treat integer overflow specially because these
8954 are quite expensive and in our experience are not as important as other
8955 run-time checks in the development process. Note that division by zero
8956 is not considered an overflow check, and divide by zero checks are
8957 generated where required by default.
8959 Elaboration checks are off by default, and also not needed by default, since
8960 GNAT uses a static elaboration analysis approach that avoids the need for
8961 run-time checking. This manual contains a full chapter discussing the issue
8962 of elaboration checks, and if the default is not satisfactory for your use,
8963 you should read this chapter.
8965 For validity checks, the minimal checks required by the Ada Reference
8966 Manual (for case statements and assignments to array elements) are on
8967 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8968 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8969 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8970 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8971 are also suppressed entirely if @option{-gnatp} is used.
8973 @cindex Overflow checks
8974 @cindex Checks, overflow
8975 @findex Suppress
8976 @findex Unsuppress
8977 @cindex pragma Suppress
8978 @cindex pragma Unsuppress
8979 Note that the setting of the switches controls the default setting of
8980 the checks. They may be modified using either @code{pragma Suppress} (to
8981 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8982 checks) in the program source.
8984 @node Use of Restrictions
8985 @subsection Use of Restrictions
8987 @noindent
8988 The use of pragma Restrictions allows you to control which features are
8989 permitted in your program. Apart from the obvious point that if you avoid
8990 relatively expensive features like finalization (enforceable by the use
8991 of pragma Restrictions (No_Finalization), the use of this pragma does not
8992 affect the generated code in most cases.
8994 One notable exception to this rule is that the possibility of task abort
8995 results in some distributed overhead, particularly if finalization or
8996 exception handlers are used. The reason is that certain sections of code
8997 have to be marked as non-abortable.
8999 If you use neither the @code{abort} statement, nor asynchronous transfer
9000 of control (@code{select .. then abort}), then this distributed overhead
9001 is removed, which may have a general positive effect in improving
9002 overall performance.  Especially code involving frequent use of tasking
9003 constructs and controlled types will show much improved performance.
9004 The relevant restrictions pragmas are
9006 @smallexample
9007    pragma Restrictions (No_Abort_Statements);
9008    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9009 @end smallexample
9011 @noindent
9012 It is recommended that these restriction pragmas be used if possible. Note
9013 that this also means that you can write code without worrying about the
9014 possibility of an immediate abort at any point.
9016 @node Optimization Levels
9017 @subsection Optimization Levels
9018 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9020 @noindent
9021 The default is optimization off. This results in the fastest compile
9022 times, but GNAT makes absolutely no attempt to optimize, and the
9023 generated programs are considerably larger and slower than when
9024 optimization is enabled. You can use the
9025 @ifclear vms
9026 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
9027 @end ifclear
9028 @ifset vms
9029 @code{OPTIMIZE} qualifier
9030 @end ifset
9031 to @command{gcc} to control the optimization level:
9033 @table @option
9034 @item ^-O0^/OPTIMIZE=NONE^
9035 No optimization (the default);
9036 generates unoptimized code but has
9037 the fastest compilation time.
9039 Note that many other compilers do fairly extensive optimization
9040 even if "no optimization" is specified. When using gcc, it is
9041 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9042 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9043 really does mean no optimization at all. This difference between
9044 gcc and other compilers should be kept in mind when doing
9045 performance comparisons.
9047 @item ^-O1^/OPTIMIZE=SOME^
9048 Moderate optimization;
9049 optimizes reasonably well but does not
9050 degrade compilation time significantly.
9052 @item ^-O2^/OPTIMIZE=ALL^
9053 @ifset vms
9054 @itemx /OPTIMIZE=DEVELOPMENT
9055 @end ifset
9056 Full optimization;
9057 generates highly optimized code and has
9058 the slowest compilation time.
9060 @item ^-O3^/OPTIMIZE=INLINING^
9061 Full optimization as in @option{-O2},
9062 and also attempts automatic inlining of small
9063 subprograms within a unit (@pxref{Inlining of Subprograms}).
9064 @end table
9066 @noindent
9067 Higher optimization levels perform more global transformations on the
9068 program and apply more expensive analysis algorithms in order to generate
9069 faster and more compact code. The price in compilation time, and the
9070 resulting improvement in execution time,
9071 both depend on the particular application and the hardware environment.
9072 You should experiment to find the best level for your application.
9074 Since the precise set of optimizations done at each level will vary from
9075 release to release (and sometime from target to target), it is best to think
9076 of the optimization settings in general terms.
9077 The @cite{Using GNU GCC} manual contains details about
9078 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9079 individually enable or disable specific optimizations.
9081 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9082 been tested extensively at all optimization levels. There are some bugs
9083 which appear only with optimization turned on, but there have also been
9084 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9085 level of optimization does not improve the reliability of the code
9086 generator, which in practice is highly reliable at all optimization
9087 levels.
9089 Note regarding the use of @option{-O3}: The use of this optimization level
9090 is generally discouraged with GNAT, since it often results in larger
9091 executables which run more slowly. See further discussion of this point
9092 in @ref{Inlining of Subprograms}.
9094 @node Debugging Optimized Code
9095 @subsection Debugging Optimized Code
9096 @cindex Debugging optimized code
9097 @cindex Optimization and debugging
9099 @noindent
9100 Although it is possible to do a reasonable amount of debugging at
9101 @ifclear vms
9102 non-zero optimization levels,
9103 the higher the level the more likely that
9104 @end ifclear
9105 @ifset vms
9106 @option{/OPTIMIZE} settings other than @code{NONE},
9107 such settings will make it more likely that
9108 @end ifset
9109 source-level constructs will have been eliminated by optimization.
9110 For example, if a loop is strength-reduced, the loop
9111 control variable may be completely eliminated and thus cannot be
9112 displayed in the debugger.
9113 This can only happen at @option{-O2} or @option{-O3}.
9114 Explicit temporary variables that you code might be eliminated at
9115 ^level^setting^ @option{-O1} or higher.
9117 The use of the @option{^-g^/DEBUG^} switch,
9118 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9119 which is needed for source-level debugging,
9120 affects the size of the program executable on disk,
9121 and indeed the debugging information can be quite large.
9122 However, it has no effect on the generated code (and thus does not
9123 degrade performance)
9125 Since the compiler generates debugging tables for a compilation unit before
9126 it performs optimizations, the optimizing transformations may invalidate some
9127 of the debugging data.  You therefore need to anticipate certain
9128 anomalous situations that may arise while debugging optimized code.
9129 These are the most common cases:
9131 @enumerate
9132 @item
9133 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9134 commands show
9135 the PC bouncing back and forth in the code.  This may result from any of
9136 the following optimizations:
9138 @itemize @bullet
9139 @item
9140 @i{Common subexpression elimination:} using a single instance of code for a
9141 quantity that the source computes several times.  As a result you
9142 may not be able to stop on what looks like a statement.
9144 @item
9145 @i{Invariant code motion:} moving an expression that does not change within a
9146 loop, to the beginning of the loop.
9148 @item
9149 @i{Instruction scheduling:} moving instructions so as to
9150 overlap loads and stores (typically) with other code, or in
9151 general to move computations of values closer to their uses. Often
9152 this causes you to pass an assignment statement without the assignment
9153 happening and then later bounce back to the statement when the
9154 value is actually needed.  Placing a breakpoint on a line of code
9155 and then stepping over it may, therefore, not always cause all the
9156 expected side-effects.
9157 @end itemize
9159 @item
9160 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9161 two identical pieces of code are merged and the program counter suddenly
9162 jumps to a statement that is not supposed to be executed, simply because
9163 it (and the code following) translates to the same thing as the code
9164 that @emph{was} supposed to be executed.  This effect is typically seen in
9165 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9166 a @code{break} in a C @code{^switch^switch^} statement.
9168 @item
9169 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9170 There are various reasons for this effect:
9172 @itemize @bullet
9173 @item
9174 In a subprogram prologue, a parameter may not yet have been moved to its
9175 ``home''.
9177 @item
9178 A variable may be dead, and its register re-used.  This is
9179 probably the most common cause.
9181 @item
9182 As mentioned above, the assignment of a value to a variable may
9183 have been moved.
9185 @item
9186 A variable may be eliminated entirely by value propagation or
9187 other means.  In this case, GCC may incorrectly generate debugging
9188 information for the variable
9189 @end itemize
9191 @noindent
9192 In general, when an unexpected value appears for a local variable or parameter
9193 you should first ascertain if that value was actually computed by
9194 your program, as opposed to being incorrectly reported by the debugger.
9195 Record fields or
9196 array elements in an object designated by an access value
9197 are generally less of a problem, once you have ascertained that the access
9198 value is sensible.
9199 Typically, this means checking variables in the preceding code and in the
9200 calling subprogram to verify that the value observed is explainable from other
9201 values (one must apply the procedure recursively to those
9202 other values); or re-running the code and stopping a little earlier
9203 (perhaps before the call) and stepping to better see how the variable obtained
9204 the value in question; or continuing to step @emph{from} the point of the
9205 strange value to see if code motion had simply moved the variable's
9206 assignments later.
9207 @end enumerate
9209 @noindent
9210 In light of such anomalies, a recommended technique is to use @option{-O0}
9211 early in the software development cycle, when extensive debugging capabilities
9212 are most needed, and then move to @option{-O1} and later @option{-O2} as
9213 the debugger becomes less critical.
9214 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9215 a release management issue.
9216 @ifclear vms
9217 Note that if you use @option{-g} you can then use the @command{strip} program
9218 on the resulting executable,
9219 which removes both debugging information and global symbols.
9220 @end ifclear
9222 @node Inlining of Subprograms
9223 @subsection Inlining of Subprograms
9225 @noindent
9226 A call to a subprogram in the current unit is inlined if all the
9227 following conditions are met:
9229 @itemize @bullet
9230 @item
9231 The optimization level is at least @option{-O1}.
9233 @item
9234 The called subprogram is suitable for inlining: It must be small enough
9235 and not contain nested subprograms or anything else that @command{gcc}
9236 cannot support in inlined subprograms.
9238 @item
9239 The call occurs after the definition of the body of the subprogram.
9241 @item
9242 @cindex pragma Inline
9243 @findex Inline
9244 Either @code{pragma Inline} applies to the subprogram or it is
9245 small and automatic inlining (optimization level @option{-O3}) is
9246 specified.
9247 @end itemize
9249 @noindent
9250 Calls to subprograms in @code{with}'ed units are normally not inlined.
9251 To achieve this level of inlining, the following conditions must all be
9252 true:
9254 @itemize @bullet
9255 @item
9256 The optimization level is at least @option{-O1}.
9258 @item
9259 The called subprogram is suitable for inlining: It must be small enough
9260 and not contain nested subprograms or anything else @command{gcc} cannot
9261 support in inlined subprograms.
9263 @item
9264 The call appears in a body (not in a package spec).
9266 @item
9267 There is a @code{pragma Inline} for the subprogram.
9269 @item
9270 @cindex @option{-gnatn} (@command{gcc})
9271 The @option{^-gnatn^/INLINE^} switch
9272 is used in the @command{gcc} command line
9273 @end itemize
9275 Note that specifying the @option{-gnatn} switch causes additional
9276 compilation dependencies. Consider the following:
9278 @smallexample @c ada
9279 @cartouche
9280 package R is
9281    procedure Q;
9282    pragma Inline (Q);
9283 end R;
9284 package body R is
9285    ...
9286 end R;
9288 with R;
9289 procedure Main is
9290 begin
9291    ...
9292    R.Q;
9293 end Main;
9294 @end cartouche
9295 @end smallexample
9297 @noindent
9298 With the default behavior (no @option{-gnatn} switch specified), the
9299 compilation of the @code{Main} procedure depends only on its own source,
9300 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9301 means that editing the body of @code{R} does not require recompiling
9302 @code{Main}.
9304 On the other hand, the call @code{R.Q} is not inlined under these
9305 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9306 is compiled, the call will be inlined if the body of @code{Q} is small
9307 enough, but now @code{Main} depends on the body of @code{R} in
9308 @file{r.adb} as well as on the spec. This means that if this body is edited,
9309 the main program must be recompiled. Note that this extra dependency
9310 occurs whether or not the call is in fact inlined by @command{gcc}.
9312 The use of front end inlining with @option{-gnatN} generates similar
9313 additional dependencies.
9315 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9316 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9317 can be used to prevent
9318 all inlining. This switch overrides all other conditions and ensures
9319 that no inlining occurs. The extra dependences resulting from
9320 @option{-gnatn} will still be active, even if
9321 this switch is used to suppress the resulting inlining actions.
9323 Note regarding the use of @option{-O3}: There is no difference in inlining
9324 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9325 pragma @code{Inline} assuming the use of @option{-gnatn}
9326 or @option{-gnatN} (the switches that activate inlining). If you have used
9327 pragma @code{Inline} in appropriate cases, then it is usually much better
9328 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9329 in this case only has the effect of inlining subprograms you did not
9330 think should be inlined. We often find that the use of @option{-O3} slows
9331 down code by performing excessive inlining, leading to increased instruction
9332 cache pressure from the increased code size. So the bottom line here is
9333 that you should not automatically assume that @option{-O3} is better than
9334 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9335 it actually improves performance.
9337 @node Other Optimization Switches
9338 @subsection Other Optimization Switches
9339 @cindex Optimization Switches
9341 Since @code{GNAT} uses the @code{gcc} back end, all the specialized
9342 @code{gcc} optimization switches are potentially usable. These switches
9343 have not been extensively tested with GNAT but can generally be expected
9344 to work. Examples of switches in this category are
9345 @option{-funroll-loops} and
9346 the various target-specific @option{-m} options (in particular, it has been
9347 observed that @option{-march=pentium4} can significantly improve performance
9348 on appropriate machines). For full details of these switches, see the
9349 @code{gcc} manual.
9351 @node Optimization and Strict Aliasing
9352 @subsection Optimization and Strict Aliasing
9353 @cindex Aliasing
9354 @cindex Strict Aliasing
9355 @cindex No_Strict_Aliasing
9357 @noindent
9358 The strong typing capabilities of Ada allow an optimizer to generate
9359 efficient code in situations where other languages would be forced to
9360 make worst case assumptions preventing such optimizations. Consider
9361 the following example:
9363 @smallexample @c ada
9364 @cartouche
9365 procedure R is
9366    type Int1 is new Integer;
9367    type Int2 is new Integer;
9368    type Int1A is access Int1;
9369    type Int2A is access Int2;
9370    Int1V : Int1A;
9371    Int2V : Int2A;
9372    ...
9374 begin
9375    ...
9376    for J in Data'Range loop
9377       if Data (J) = Int1V.all then
9378          Int2V.all := Int2V.all + 1;
9379       end if;
9380    end loop;
9381    ...
9382 end R;
9383 @end cartouche
9384 @end smallexample
9386 @noindent
9387 In this example, since the variable @code{Int1V} can only access objects
9388 of type @code{Int1}, and @code{Int2V} can only access objects of type
9389 @code{Int2}, there is no possibility that the assignment to
9390 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9391 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9392 for all iterations of the loop and avoid the extra memory reference
9393 required to dereference it each time through the loop.
9395 This kind of optimization, called strict aliasing analysis, is
9396 triggered by specifying an optimization level of @option{-O2} or
9397 higher and allows @code{GNAT} to generate more efficient code
9398 when access values are involved.
9400 However, although this optimization is always correct in terms of
9401 the formal semantics of the Ada Reference Manual, difficulties can
9402 arise if features like @code{Unchecked_Conversion} are used to break
9403 the typing system. Consider the following complete program example:
9405 @smallexample @c ada
9406 @cartouche
9407 package p1 is
9408    type int1 is new integer;
9409    type int2 is new integer;
9410    type a1 is access int1;
9411    type a2 is access int2;
9412 end p1;
9414 with p1; use p1;
9415 package p2 is
9416    function to_a2 (Input : a1) return a2;
9417 end p2;
9419 with Unchecked_Conversion;
9420 package body p2 is
9421    function to_a2 (Input : a1) return a2 is
9422       function to_a2u is
9423         new Unchecked_Conversion (a1, a2);
9424    begin
9425       return to_a2u (Input);
9426    end to_a2;
9427 end p2;
9429 with p2; use p2;
9430 with p1; use p1;
9431 with Text_IO; use Text_IO;
9432 procedure m is
9433    v1 : a1 := new int1;
9434    v2 : a2 := to_a2 (v1);
9435 begin
9436    v1.all := 1;
9437    v2.all := 0;
9438    put_line (int1'image (v1.all));
9439 end;
9440 @end cartouche
9441 @end smallexample
9443 @noindent
9444 This program prints out 0 in @code{-O0} or @code{-O1}
9445 mode, but it prints out 1 in @code{-O2} mode. That's
9446 because in strict aliasing mode, the compiler can and
9447 does assume that the assignment to @code{v2.all} could not
9448 affect the value of @code{v1.all}, since different types
9449 are involved.
9451 This behavior is not a case of non-conformance with the standard, since
9452 the Ada RM specifies that an unchecked conversion where the resulting
9453 bit pattern is not a correct value of the target type can result in an
9454 abnormal value and attempting to reference an abnormal value makes the
9455 execution of a program erroneous.  That's the case here since the result
9456 does not point to an object of type @code{int2}.  This means that the
9457 effect is entirely unpredictable.
9459 However, although that explanation may satisfy a language
9460 lawyer, in practice an applications programmer expects an
9461 unchecked conversion involving pointers to create true
9462 aliases and the behavior of printing 1 seems plain wrong.
9463 In this case, the strict aliasing optimization is unwelcome.
9465 Indeed the compiler recognizes this possibility, and the
9466 unchecked conversion generates a warning:
9468 @smallexample
9469 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9470 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9471 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9472 @end smallexample
9474 @noindent
9475 Unfortunately the problem is recognized when compiling the body of
9476 package @code{p2}, but the actual "bad" code is generated while
9477 compiling the body of @code{m} and this latter compilation does not see
9478 the suspicious @code{Unchecked_Conversion}.
9480 As implied by the warning message, there are approaches you can use to
9481 avoid the unwanted strict aliasing optimization in a case like this.
9483 One possibility is to simply avoid the use of @code{-O2}, but
9484 that is a bit drastic, since it throws away a number of useful
9485 optimizations that do not involve strict aliasing assumptions.
9487 A less drastic approach is to compile the program using the
9488 option @code{-fno-strict-aliasing}. Actually it is only the
9489 unit containing the dereferencing of the suspicious pointer
9490 that needs to be compiled. So in this case, if we compile
9491 unit @code{m} with this switch, then we get the expected
9492 value of zero printed. Analyzing which units might need
9493 the switch can be painful, so a more reasonable approach
9494 is to compile the entire program with options @code{-O2}
9495 and @code{-fno-strict-aliasing}. If the performance is
9496 satisfactory with this combination of options, then the
9497 advantage is that the entire issue of possible "wrong"
9498 optimization due to strict aliasing is avoided.
9500 To avoid the use of compiler switches, the configuration
9501 pragma @code{No_Strict_Aliasing} with no parameters may be
9502 used to specify that for all access types, the strict
9503 aliasing optimization should be suppressed.
9505 However, these approaches are still overkill, in that they causes
9506 all manipulations of all access values to be deoptimized. A more
9507 refined approach is to concentrate attention on the specific
9508 access type identified as problematic.
9510 First, if a careful analysis of uses of the pointer shows
9511 that there are no possible problematic references, then
9512 the warning can be suppressed by bracketing the
9513 instantiation of @code{Unchecked_Conversion} to turn
9514 the warning off:
9516 @smallexample @c ada
9517    pragma Warnings (Off);
9518    function to_a2u is
9519      new Unchecked_Conversion (a1, a2);
9520    pragma Warnings (On);
9521 @end smallexample
9523 @noindent
9524 Of course that approach is not appropriate for this particular
9525 example, since indeed there is a problematic reference. In this
9526 case we can take one of two other approaches.
9528 The first possibility is to move the instantiation of unchecked
9529 conversion to the unit in which the type is declared. In
9530 this example, we would move the instantiation of
9531 @code{Unchecked_Conversion} from the body of package
9532 @code{p2} to the spec of package @code{p1}. Now the
9533 warning disappears. That's because any use of the
9534 access type knows there is a suspicious unchecked
9535 conversion, and the strict aliasing optimization
9536 is automatically suppressed for the type.
9538 If it is not practical to move the unchecked conversion to the same unit
9539 in which the destination access type is declared (perhaps because the
9540 source type is not visible in that unit), you may use pragma
9541 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9542 same declarative sequence as the declaration of the access type:
9544 @smallexample @c ada
9545    type a2 is access int2;
9546    pragma No_Strict_Aliasing (a2);
9547 @end smallexample
9549 @noindent
9550 Here again, the compiler now knows that the strict aliasing optimization
9551 should be suppressed for any reference to type @code{a2} and the
9552 expected behavior is obtained.
9554 Finally, note that although the compiler can generate warnings for
9555 simple cases of unchecked conversions, there are tricker and more
9556 indirect ways of creating type incorrect aliases which the compiler
9557 cannot detect. Examples are the use of address overlays and unchecked
9558 conversions involving composite types containing access types as
9559 components. In such cases, no warnings are generated, but there can
9560 still be aliasing problems. One safe coding practice is to forbid the
9561 use of address clauses for type overlaying, and to allow unchecked
9562 conversion only for primitive types. This is not really a significant
9563 restriction since any possible desired effect can be achieved by
9564 unchecked conversion of access values.
9566 @ifset vms
9567 @node Coverage Analysis
9568 @subsection Coverage Analysis
9570 @noindent
9571 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
9572 the user to determine the distribution of execution time across a program,
9573 @pxref{Profiling} for details of usage.
9574 @end ifset
9576 @node Reducing the Size of Ada Executables with gnatelim
9577 @section Reducing the Size of Ada Executables with @code{gnatelim}
9578 @findex gnatelim
9580 @noindent
9581 This section describes @command{gnatelim}, a tool which detects unused
9582 subprograms and helps the compiler to create a smaller executable for your
9583 program.
9585 @menu
9586 * About gnatelim::
9587 * Running gnatelim::
9588 * Correcting the List of Eliminate Pragmas::
9589 * Making Your Executables Smaller::
9590 * Summary of the gnatelim Usage Cycle::
9591 @end menu
9593 @node About gnatelim
9594 @subsection About @code{gnatelim}
9596 @noindent
9597 When a program shares a set of Ada
9598 packages with other programs, it may happen that this program uses
9599 only a fraction of the subprograms defined in these packages. The code
9600 created for these unused subprograms increases the size of the executable.
9602 @code{gnatelim} tracks unused subprograms in an Ada program and
9603 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9604 subprograms that are declared but never called. By placing the list of
9605 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9606 recompiling your program, you may decrease the size of its executable,
9607 because the compiler will not generate the code for 'eliminated' subprograms.
9608 See GNAT Reference Manual for more information about this pragma.
9610 @code{gnatelim} needs as its input data the name of the main subprogram
9611 and a bind file for a main subprogram.
9613 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9614 the main subprogram. @code{gnatelim} can work with both Ada and C
9615 bind files; when both are present, it uses the Ada bind file.
9616 The following commands will build the program and create the bind file:
9618 @smallexample
9619 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9620 $ gnatbind main_prog
9621 @end smallexample
9623 Note that @code{gnatelim} needs neither object nor ALI files.
9625 @node Running gnatelim
9626 @subsection Running @code{gnatelim}
9628 @noindent
9629 @code{gnatelim} has the following command-line interface:
9631 @smallexample
9632 $ gnatelim [options] name
9633 @end smallexample
9635 @noindent
9636 @code{name} should be a name of a source file that contains the main subprogram
9637 of a program (partition).
9639 @code{gnatelim} has the following switches:
9641 @table @option
9642 @c !sort!
9643 @item ^-q^/QUIET^
9644 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9645 Quiet mode: by default @code{gnatelim} outputs to the standard error
9646 stream the number of program units left to be processed. This option turns
9647 this trace off.
9649 @item ^-v^/VERBOSE^
9650 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9651 Verbose mode: @code{gnatelim} version information is printed as Ada
9652 comments to the standard output stream. Also, in addition to the number of
9653 program units left @code{gnatelim} will output the name of the current unit
9654 being processed.
9656 @item ^-a^/ALL^
9657 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9658 Also look for subprograms from the GNAT run time that can be eliminated. Note
9659 that when @file{gnat.adc} is produced using this switch, the entire program
9660 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9662 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9663 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9664 When looking for source files also look in directory @var{dir}. Specifying
9665 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9666 sources in the current directory.
9668 @item ^-b^/BIND_FILE=^@var{bind_file}
9669 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9670 Specifies @var{bind_file} as the bind file to process. If not set, the name
9671 of the bind file is computed from the full expanded Ada name
9672 of a main subprogram.
9674 @item ^-C^/CONFIG_FILE=^@var{config_file}
9675 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9676 Specifies a file @var{config_file} that contains configuration pragmas. The
9677 file must be specified with full path.
9679 @item ^--GCC^/COMPILER^=@var{compiler_name}
9680 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9681 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9682 available on the path.
9684 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9685 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9686 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9687 available on the path.
9688 @end table
9690 @noindent
9691 @code{gnatelim} sends its output to the standard output stream, and all the
9692 tracing and debug information is sent to the standard error stream.
9693 In order to produce a proper GNAT configuration file
9694 @file{gnat.adc}, redirection must be used:
9696 @smallexample
9697 @ifset vms
9698 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9699 @end ifset
9700 @ifclear vms
9701 $ gnatelim main_prog.adb > gnat.adc
9702 @end ifclear
9703 @end smallexample
9705 @ifclear vms
9706 @noindent
9709 @smallexample
9710 $ gnatelim main_prog.adb >> gnat.adc
9711 @end smallexample
9713 @noindent
9714 in order to append the @code{gnatelim} output to the existing contents of
9715 @file{gnat.adc}.
9716 @end ifclear
9718 @node Correcting the List of Eliminate Pragmas
9719 @subsection Correcting the List of Eliminate Pragmas
9721 @noindent
9722 In some rare cases @code{gnatelim} may try to eliminate
9723 subprograms that are actually called in the program. In this case, the
9724 compiler will generate an error message of the form:
9726 @smallexample
9727 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9728 @end smallexample
9730 @noindent
9731 You will need to manually remove the wrong @code{Eliminate} pragmas from
9732 the @file{gnat.adc} file. You should recompile your program
9733 from scratch after that, because you need a consistent @file{gnat.adc} file
9734 during the entire compilation.
9736 @node Making Your Executables Smaller
9737 @subsection Making Your Executables Smaller
9739 @noindent
9740 In order to get a smaller executable for your program you now have to
9741 recompile the program completely with the new @file{gnat.adc} file
9742 created by @code{gnatelim} in your current directory:
9744 @smallexample
9745 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9746 @end smallexample
9748 @noindent
9749 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9750 recompile everything
9751 with the set of pragmas @code{Eliminate} that you have obtained with
9752 @command{gnatelim}).
9754 Be aware that the set of @code{Eliminate} pragmas is specific to each
9755 program. It is not recommended to merge sets of @code{Eliminate}
9756 pragmas created for different programs in one @file{gnat.adc} file.
9758 @node Summary of the gnatelim Usage Cycle
9759 @subsection Summary of the gnatelim Usage Cycle
9761 @noindent
9762 Here is a quick summary of the steps to be taken in order to reduce
9763 the size of your executables with @code{gnatelim}. You may use
9764 other GNAT options to control the optimization level,
9765 to produce the debugging information, to set search path, etc.
9767 @enumerate
9768 @item
9769 Produce a bind file
9771 @smallexample
9772 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9773 $ gnatbind main_prog
9774 @end smallexample
9776 @item
9777 Generate a list of @code{Eliminate} pragmas
9778 @smallexample
9779 @ifset vms
9780 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9781 @end ifset
9782 @ifclear vms
9783 $ gnatelim main_prog >[>] gnat.adc
9784 @end ifclear
9785 @end smallexample
9787 @item
9788 Recompile the application
9790 @smallexample
9791 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9792 @end smallexample
9794 @end enumerate
9796 @c ********************************
9797 @node Renaming Files Using gnatchop
9798 @chapter Renaming Files Using @code{gnatchop}
9799 @findex gnatchop
9801 @noindent
9802 This chapter discusses how to handle files with multiple units by using
9803 the @code{gnatchop} utility. This utility is also useful in renaming
9804 files to meet the standard GNAT default file naming conventions.
9806 @menu
9807 * Handling Files with Multiple Units::
9808 * Operating gnatchop in Compilation Mode::
9809 * Command Line for gnatchop::
9810 * Switches for gnatchop::
9811 * Examples of gnatchop Usage::
9812 @end menu
9814 @node Handling Files with Multiple Units
9815 @section Handling Files with Multiple Units
9817 @noindent
9818 The basic compilation model of GNAT requires that a file submitted to the
9819 compiler have only one unit and there be a strict correspondence
9820 between the file name and the unit name.
9822 The @code{gnatchop} utility allows both of these rules to be relaxed,
9823 allowing GNAT to process files which contain multiple compilation units
9824 and files with arbitrary file names. @code{gnatchop}
9825 reads the specified file and generates one or more output files,
9826 containing one unit per file. The unit and the file name correspond,
9827 as required by GNAT.
9829 If you want to permanently restructure a set of ``foreign'' files so that
9830 they match the GNAT rules, and do the remaining development using the
9831 GNAT structure, you can simply use @command{gnatchop} once, generate the
9832 new set of files and work with them from that point on.
9834 Alternatively, if you want to keep your files in the ``foreign'' format,
9835 perhaps to maintain compatibility with some other Ada compilation
9836 system, you can set up a procedure where you use @command{gnatchop} each
9837 time you compile, regarding the source files that it writes as temporary
9838 files that you throw away.
9840 @node Operating gnatchop in Compilation Mode
9841 @section Operating gnatchop in Compilation Mode
9843 @noindent
9844 The basic function of @code{gnatchop} is to take a file with multiple units
9845 and split it into separate files. The boundary between files is reasonably
9846 clear, except for the issue of comments and pragmas. In default mode, the
9847 rule is that any pragmas between units belong to the previous unit, except
9848 that configuration pragmas always belong to the following unit. Any comments
9849 belong to the following unit. These rules
9850 almost always result in the right choice of
9851 the split point without needing to mark it explicitly and most users will
9852 find this default to be what they want. In this default mode it is incorrect to
9853 submit a file containing only configuration pragmas, or one that ends in
9854 configuration pragmas, to @code{gnatchop}.
9856 However, using a special option to activate ``compilation mode'',
9857 @code{gnatchop}
9858 can perform another function, which is to provide exactly the semantics
9859 required by the RM for handling of configuration pragmas in a compilation.
9860 In the absence of configuration pragmas (at the main file level), this
9861 option has no effect, but it causes such configuration pragmas to be handled
9862 in a quite different manner.
9864 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9865 only configuration pragmas, then this file is appended to the
9866 @file{gnat.adc} file in the current directory. This behavior provides
9867 the required behavior described in the RM for the actions to be taken
9868 on submitting such a file to the compiler, namely that these pragmas
9869 should apply to all subsequent compilations in the same compilation
9870 environment. Using GNAT, the current directory, possibly containing a
9871 @file{gnat.adc} file is the representation
9872 of a compilation environment. For more information on the
9873 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
9875 Second, in compilation mode, if @code{gnatchop}
9876 is given a file that starts with
9877 configuration pragmas, and contains one or more units, then these
9878 configuration pragmas are prepended to each of the chopped files. This
9879 behavior provides the required behavior described in the RM for the
9880 actions to be taken on compiling such a file, namely that the pragmas
9881 apply to all units in the compilation, but not to subsequently compiled
9882 units.
9884 Finally, if configuration pragmas appear between units, they are appended
9885 to the previous unit. This results in the previous unit being illegal,
9886 since the compiler does not accept configuration pragmas that follow
9887 a unit. This provides the required RM behavior that forbids configuration
9888 pragmas other than those preceding the first compilation unit of a
9889 compilation.
9891 For most purposes, @code{gnatchop} will be used in default mode. The
9892 compilation mode described above is used only if you need exactly
9893 accurate behavior with respect to compilations, and you have files
9894 that contain multiple units and configuration pragmas. In this
9895 circumstance the use of @code{gnatchop} with the compilation mode
9896 switch provides the required behavior, and is for example the mode
9897 in which GNAT processes the ACVC tests.
9899 @node Command Line for gnatchop
9900 @section Command Line for @code{gnatchop}
9902 @noindent
9903 The @code{gnatchop} command has the form:
9905 @smallexample
9906 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9907       [@var{directory}]
9908 @end smallexample
9910 @noindent
9911 The only required argument is the file name of the file to be chopped.
9912 There are no restrictions on the form of this file name. The file itself
9913 contains one or more Ada units, in normal GNAT format, concatenated
9914 together. As shown, more than one file may be presented to be chopped.
9916 When run in default mode, @code{gnatchop} generates one output file in
9917 the current directory for each unit in each of the files.
9919 @var{directory}, if specified, gives the name of the directory to which
9920 the output files will be written. If it is not specified, all files are
9921 written to the current directory.
9923 For example, given a
9924 file called @file{hellofiles} containing
9926 @smallexample @c ada
9927 @group
9928 @cartouche
9929 procedure hello;
9931 with Text_IO; use Text_IO;
9932 procedure hello is
9933 begin
9934    Put_Line ("Hello");
9935 end hello;
9936 @end cartouche
9937 @end group
9938 @end smallexample
9940 @noindent
9941 the command
9943 @smallexample
9944 $ gnatchop ^hellofiles^HELLOFILES.^
9945 @end smallexample
9947 @noindent
9948 generates two files in the current directory, one called
9949 @file{hello.ads} containing the single line that is the procedure spec,
9950 and the other called @file{hello.adb} containing the remaining text. The
9951 original file is not affected. The generated files can be compiled in
9952 the normal manner.
9954 @noindent
9955 When gnatchop is invoked on a file that is empty or that contains only empty
9956 lines and/or comments, gnatchop will not fail, but will not produce any
9957 new sources.
9959 For example, given a
9960 file called @file{toto.txt} containing
9962 @smallexample @c ada
9963 @group
9964 @cartouche
9965 --  Just a comment
9966 @end cartouche
9967 @end group
9968 @end smallexample
9970 @noindent
9971 the command
9973 @smallexample
9974 $ gnatchop ^toto.txt^TOT.TXT^
9975 @end smallexample
9977 @noindent
9978 will not produce any new file and will result in the following warnings:
9980 @smallexample
9981 toto.txt:1:01: warning: empty file, contains no compilation units
9982 no compilation units found
9983 no source files written
9984 @end smallexample
9986 @node Switches for gnatchop
9987 @section Switches for @code{gnatchop}
9989 @noindent
9990 @command{gnatchop} recognizes the following switches:
9992 @table @option
9993 @c !sort!
9995 @item ^-c^/COMPILATION^
9996 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9997 Causes @code{gnatchop} to operate in compilation mode, in which
9998 configuration pragmas are handled according to strict RM rules. See
9999 previous section for a full description of this mode.
10001 @ifclear vms
10002 @item -gnatxxx
10003 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10004 used to parse the given file. Not all @code{xxx} options make sense,
10005 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10006 process a source file that uses Latin-2 coding for identifiers.
10007 @end ifclear
10009 @item ^-h^/HELP^
10010 Causes @code{gnatchop} to generate a brief help summary to the standard
10011 output file showing usage information.
10013 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10014 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10015 Limit generated file names to the specified number @code{mm}
10016 of characters.
10017 This is useful if the
10018 resulting set of files is required to be interoperable with systems
10019 which limit the length of file names.
10020 @ifset vms
10021 If no value is given, or
10022 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10023 a default of 39, suitable for OpenVMS Alpha
10024 Systems, is assumed
10025 @end ifset
10026 @ifclear vms
10027 No space is allowed between the @option{-k} and the numeric value. The numeric
10028 value may be omitted in which case a default of @option{-k8},
10029 suitable for use
10030 with DOS-like file systems, is used. If no @option{-k} switch
10031 is present then
10032 there is no limit on the length of file names.
10033 @end ifclear
10035 @item ^-p^/PRESERVE^
10036 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10037 Causes the file ^modification^creation^ time stamp of the input file to be
10038 preserved and used for the time stamp of the output file(s). This may be
10039 useful for preserving coherency of time stamps in an environment where
10040 @code{gnatchop} is used as part of a standard build process.
10042 @item ^-q^/QUIET^
10043 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10044 Causes output of informational messages indicating the set of generated
10045 files to be suppressed. Warnings and error messages are unaffected.
10047 @item ^-r^/REFERENCE^
10048 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10049 @findex Source_Reference
10050 Generate @code{Source_Reference} pragmas. Use this switch if the output
10051 files are regarded as temporary and development is to be done in terms
10052 of the original unchopped file. This switch causes
10053 @code{Source_Reference} pragmas to be inserted into each of the
10054 generated files to refers back to the original file name and line number.
10055 The result is that all error messages refer back to the original
10056 unchopped file.
10057 In addition, the debugging information placed into the object file (when
10058 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10059 specified)
10060 also refers back to this original file so that tools like profilers and
10061 debuggers will give information in terms of the original unchopped file.
10063 If the original file to be chopped itself contains
10064 a @code{Source_Reference}
10065 pragma referencing a third file, then gnatchop respects
10066 this pragma, and the generated @code{Source_Reference} pragmas
10067 in the chopped file refer to the original file, with appropriate
10068 line numbers. This is particularly useful when @code{gnatchop}
10069 is used in conjunction with @code{gnatprep} to compile files that
10070 contain preprocessing statements and multiple units.
10072 @item ^-v^/VERBOSE^
10073 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10074 Causes @code{gnatchop} to operate in verbose mode. The version
10075 number and copyright notice are output, as well as exact copies of
10076 the gnat1 commands spawned to obtain the chop control information.
10078 @item ^-w^/OVERWRITE^
10079 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10080 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10081 fatal error if there is already a file with the same name as a
10082 file it would otherwise output, in other words if the files to be
10083 chopped contain duplicated units. This switch bypasses this
10084 check, and causes all but the last instance of such duplicated
10085 units to be skipped.
10087 @ifclear vms
10088 @item --GCC=xxxx
10089 @cindex @option{--GCC=} (@code{gnatchop})
10090 Specify the path of the GNAT parser to be used. When this switch is used,
10091 no attempt is made to add the prefix to the GNAT parser executable.
10092 @end ifclear
10093 @end table
10095 @node Examples of gnatchop Usage
10096 @section Examples of @code{gnatchop} Usage
10098 @table @code
10099 @ifset vms
10100 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10101 @end ifset
10102 @ifclear vms
10103 @item gnatchop -w hello_s.ada prerelease/files
10104 @end ifclear
10106 Chops the source file @file{hello_s.ada}. The output files will be
10107 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10108 overwriting any
10109 files with matching names in that directory (no files in the current
10110 directory are modified).
10112 @item gnatchop ^archive^ARCHIVE.^
10113 Chops the source file @file{^archive^ARCHIVE.^}
10114 into the current directory. One
10115 useful application of @code{gnatchop} is in sending sets of sources
10116 around, for example in email messages. The required sources are simply
10117 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10118 command), and then
10119 @code{gnatchop} is used at the other end to reconstitute the original
10120 file names.
10122 @item gnatchop file1 file2 file3 direc
10123 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10124 the resulting files in the directory @file{direc}. Note that if any units
10125 occur more than once anywhere within this set of files, an error message
10126 is generated, and no files are written. To override this check, use the
10127 @option{^-w^/OVERWRITE^} switch,
10128 in which case the last occurrence in the last file will
10129 be the one that is output, and earlier duplicate occurrences for a given
10130 unit will be skipped.
10131 @end table
10133 @node Configuration Pragmas
10134 @chapter Configuration Pragmas
10135 @cindex Configuration pragmas
10136 @cindex Pragmas, configuration
10138 @noindent
10139 In Ada 95, configuration pragmas include those pragmas described as
10140 such in the Ada 95 Reference Manual, as well as
10141 implementation-dependent pragmas that are configuration pragmas. See the
10142 individual descriptions of pragmas in the GNAT Reference Manual for
10143 details on these additional GNAT-specific configuration pragmas. Most
10144 notably, the pragma @code{Source_File_Name}, which allows
10145 specifying non-default names for source files, is a configuration
10146 pragma. The following is a complete list of configuration pragmas
10147 recognized by @code{GNAT}:
10149 @smallexample
10150    Ada_83
10151    Ada_95
10152    Ada_05
10153    C_Pass_By_Copy
10154    Component_Alignment
10155    Detect_Blocking
10156    Discard_Names
10157    Elaboration_Checks
10158    Eliminate
10159    Extend_System
10160    External_Name_Casing
10161    Float_Representation
10162    Initialize_Scalars
10163    Interrupt_State
10164    License
10165    Locking_Policy
10166    Long_Float
10167    Normalize_Scalars
10168    Persistent_BSS
10169    Polling
10170    Profile
10171    Profile_Warnings
10172    Propagate_Exceptions
10173    Queuing_Policy
10174    Ravenscar
10175    Restricted_Run_Time
10176    Restrictions
10177    Restrictions_Warnings
10178    Reviewable
10179    Source_File_Name
10180    Style_Checks
10181    Suppress
10182    Task_Dispatching_Policy
10183    Universal_Data
10184    Unsuppress
10185    Use_VADS_Size
10186    Warnings
10187    Validity_Checks
10188 @end smallexample
10190 @menu
10191 * Handling of Configuration Pragmas::
10192 * The Configuration Pragmas Files::
10193 @end menu
10195 @node Handling of Configuration Pragmas
10196 @section Handling of Configuration Pragmas
10198 Configuration pragmas may either appear at the start of a compilation
10199 unit, in which case they apply only to that unit, or they may apply to
10200 all compilations performed in a given compilation environment.
10202 GNAT also provides the @code{gnatchop} utility to provide an automatic
10203 way to handle configuration pragmas following the semantics for
10204 compilations (that is, files with multiple units), described in the RM.
10205 See @ref{Operating gnatchop in Compilation Mode} for details.
10206 However, for most purposes, it will be more convenient to edit the
10207 @file{gnat.adc} file that contains configuration pragmas directly,
10208 as described in the following section.
10210 @node The Configuration Pragmas Files
10211 @section The Configuration Pragmas Files
10212 @cindex @file{gnat.adc}
10214 @noindent
10215 In GNAT a compilation environment is defined by the current
10216 directory at the time that a compile command is given. This current
10217 directory is searched for a file whose name is @file{gnat.adc}. If
10218 this file is present, it is expected to contain one or more
10219 configuration pragmas that will be applied to the current compilation.
10220 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10221 considered.
10223 Configuration pragmas may be entered into the @file{gnat.adc} file
10224 either by running @code{gnatchop} on a source file that consists only of
10225 configuration pragmas, or more conveniently  by
10226 direct editing of the @file{gnat.adc} file, which is a standard format
10227 source file.
10229 In addition to @file{gnat.adc}, one additional file containing configuration
10230 pragmas may be applied to the current compilation using the switch
10231 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10232 contains only configuration pragmas. These configuration pragmas are
10233 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10234 is present and switch @option{-gnatA} is not used).
10236 It is allowed to specify several switches @option{-gnatec}, however only
10237 the last one on the command line will be taken into account.
10239 If you are using project file, a separate mechanism is provided using
10240 project attributes, see @ref{Specifying Configuration Pragmas} for more
10241 details.
10243 @ifset vms
10244 Of special interest to GNAT OpenVMS Alpha is the following
10245 configuration pragma:
10247 @smallexample @c ada
10248 @cartouche
10249 pragma Extend_System (Aux_DEC);
10250 @end cartouche
10251 @end smallexample
10253 @noindent
10254 In the presence of this pragma, GNAT adds to the definition of the
10255 predefined package SYSTEM all the additional types and subprograms that are
10256 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10257 @end ifset
10259 @node Handling Arbitrary File Naming Conventions Using gnatname
10260 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10261 @cindex Arbitrary File Naming Conventions
10263 @menu
10264 * Arbitrary File Naming Conventions::
10265 * Running gnatname::
10266 * Switches for gnatname::
10267 * Examples of gnatname Usage::
10268 @end menu
10270 @node Arbitrary File Naming Conventions
10271 @section Arbitrary File Naming Conventions
10273 @noindent
10274 The GNAT compiler must be able to know the source file name of a compilation
10275 unit.  When using the standard GNAT default file naming conventions
10276 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10277 does not need additional information.
10279 @noindent
10280 When the source file names do not follow the standard GNAT default file naming
10281 conventions, the GNAT compiler must be given additional information through
10282 a configuration pragmas file (@pxref{Configuration Pragmas})
10283 or a project file.
10284 When the non standard file naming conventions are well-defined,
10285 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10286 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10287 if the file naming conventions are irregular or arbitrary, a number
10288 of pragma @code{Source_File_Name} for individual compilation units
10289 must be defined.
10290 To help maintain the correspondence between compilation unit names and
10291 source file names within the compiler,
10292 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10293 set of files.
10295 @node Running gnatname
10296 @section Running @code{gnatname}
10298 @noindent
10299 The usual form of the @code{gnatname} command is
10301 @smallexample
10302 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10303 @end smallexample
10305 @noindent
10306 All of the arguments are optional. If invoked without any argument,
10307 @code{gnatname} will display its usage.
10309 @noindent
10310 When used with at least one naming pattern, @code{gnatname} will attempt to
10311 find all the compilation units in files that follow at least one of the
10312 naming patterns. To find these compilation units,
10313 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10314 regular files.
10316 @noindent
10317 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10318 Each Naming Pattern is enclosed between double quotes.
10319 A Naming Pattern is a regular expression similar to the wildcard patterns
10320 used in file names by the Unix shells or the DOS prompt.
10322 @noindent
10323 Examples of Naming Patterns are
10325 @smallexample
10326    "*.[12].ada"
10327    "*.ad[sb]*"
10328    "body_*"    "spec_*"
10329 @end smallexample
10331 @noindent
10332 For a more complete description of the syntax of Naming Patterns,
10333 see the second kind of regular expressions described in @file{g-regexp.ads}
10334 (the ``Glob'' regular expressions).
10336 @noindent
10337 When invoked with no switches, @code{gnatname} will create a configuration
10338 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10339 @code{Source_File_Name} for each file that contains a valid Ada unit.
10341 @node Switches for gnatname
10342 @section Switches for @code{gnatname}
10344 @noindent
10345 Switches for @code{gnatname} must precede any specified Naming Pattern.
10347 @noindent
10348 You may specify any of the following switches to @code{gnatname}:
10350 @table @option
10351 @c !sort!
10353 @item ^-c^/CONFIG_FILE=^@file{file}
10354 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10355 Create a configuration pragmas file @file{file} (instead of the default
10356 @file{gnat.adc}).
10357 @ifclear vms
10358 There may be zero, one or more space between @option{-c} and
10359 @file{file}.
10360 @end ifclear
10361 @file{file} may include directory information. @file{file} must be
10362 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10363 When a switch @option{^-c^/CONFIG_FILE^} is
10364 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10366 @item ^-d^/SOURCE_DIRS=^@file{dir}
10367 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10368 Look for source files in directory @file{dir}. There may be zero, one or more
10369 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10370 When a switch @option{^-d^/SOURCE_DIRS^}
10371 is specified, the current working directory will not be searched for source
10372 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10373 or @option{^-D^/DIR_FILES^} switch.
10374 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10375 If @file{dir} is a relative path, it is relative to the directory of
10376 the configuration pragmas file specified with switch
10377 @option{^-c^/CONFIG_FILE^},
10378 or to the directory of the project file specified with switch
10379 @option{^-P^/PROJECT_FILE^} or,
10380 if neither switch @option{^-c^/CONFIG_FILE^}
10381 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10382 current working directory. The directory
10383 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10385 @item ^-D^/DIRS_FILE=^@file{file}
10386 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10387 Look for source files in all directories listed in text file @file{file}.
10388 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10389 and @file{file}.
10390 @file{file} must be an existing, readable text file.
10391 Each non empty line in @file{file} must be a directory.
10392 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10393 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10394 @file{file}.
10396 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10397 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10398 Foreign patterns. Using this switch, it is possible to add sources of languages
10399 other than Ada to the list of sources of a project file.
10400 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10401 For example,
10402 @smallexample
10403 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10404 @end smallexample
10405 @noindent
10406 will look for Ada units in all files with the @file{.ada} extension,
10407 and will add to the list of file for project @file{prj.gpr} the C files
10408 with extension ".^c^C^".
10410 @item ^-h^/HELP^
10411 @cindex @option{^-h^/HELP^} (@code{gnatname})
10412 Output usage (help) information. The output is written to @file{stdout}.
10414 @item ^-P^/PROJECT_FILE=^@file{proj}
10415 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10416 Create or update project file @file{proj}. There may be zero, one or more space
10417 between @option{-P} and @file{proj}. @file{proj} may include directory
10418 information. @file{proj} must be writable.
10419 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10420 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10421 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10423 @item ^-v^/VERBOSE^
10424 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10425 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10426 This includes name of the file written, the name of the directories to search
10427 and, for each file in those directories whose name matches at least one of
10428 the Naming Patterns, an indication of whether the file contains a unit,
10429 and if so the name of the unit.
10431 @item ^-v -v^/VERBOSE /VERBOSE^
10432 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10433 Very Verbose mode. In addition to the output produced in verbose mode,
10434 for each file in the searched directories whose name matches none of
10435 the Naming Patterns, an indication is given that there is no match.
10437 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10438 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10439 Excluded patterns. Using this switch, it is possible to exclude some files
10440 that would match the name patterns. For example,
10441 @smallexample
10442 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10443 @end smallexample
10444 @noindent
10445 will look for Ada units in all files with the @file{.ada} extension,
10446 except those whose names end with @file{_nt.ada}.
10448 @end table
10450 @node Examples of gnatname Usage
10451 @section Examples of @code{gnatname} Usage
10453 @ifset vms
10454 @smallexample
10455 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10456 @end smallexample
10457 @end ifset
10459 @ifclear vms
10460 @smallexample
10461 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10462 @end smallexample
10463 @end ifclear
10465 @noindent
10466 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10467 and be writable. In addition, the directory
10468 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10469 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10471 @ifclear vms
10472 Note the optional spaces after @option{-c} and @option{-d}.
10473 @end ifclear
10475 @smallexample
10476 @ifclear vms
10477 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10478   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10479 @end ifclear
10480 @ifset vms
10481 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10482   /EXCLUDED_PATTERN=*_nt_body.ada
10483   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10484   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10485 @end ifset
10486 @end smallexample
10488 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10489 even in conjunction with one or several switches
10490 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10491 are used in this example.
10493 @c *****************************************
10494 @c * G N A T  P r o j e c t  M a n a g e r *
10495 @c *****************************************
10496 @node GNAT Project Manager
10497 @chapter GNAT Project Manager
10499 @menu
10500 * Introduction::
10501 * Examples of Project Files::
10502 * Project File Syntax::
10503 * Objects and Sources in Project Files::
10504 * Importing Projects::
10505 * Project Extension::
10506 * Project Hierarchy Extension::
10507 * External References in Project Files::
10508 * Packages in Project Files::
10509 * Variables from Imported Projects::
10510 * Naming Schemes::
10511 * Library Projects::
10512 * Stand-alone Library Projects::
10513 * Switches Related to Project Files::
10514 * Tools Supporting Project Files::
10515 * An Extended Example::
10516 * Project File Complete Syntax::
10517 @end menu
10519 @c ****************
10520 @c * Introduction *
10521 @c ****************
10523 @node Introduction
10524 @section Introduction
10526 @noindent
10527 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10528 you to manage complex builds involving a number of source files, directories,
10529 and compilation options for different system configurations. In particular,
10530 project files allow you to specify:
10531 @itemize @bullet
10532 @item
10533 The directory or set of directories containing the source files, and/or the
10534 names of the specific source files themselves
10535 @item
10536 The directory in which the compiler's output
10537 (@file{ALI} files, object files, tree files) is to be placed
10538 @item
10539 The directory in which the executable programs is to be placed
10540 @item
10541 ^Switch^Switch^ settings for any of the project-enabled tools
10542 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10543 @code{gnatfind}); you can apply these settings either globally or to individual
10544 compilation units.
10545 @item
10546 The source files containing the main subprogram(s) to be built
10547 @item
10548 The source programming language(s) (currently Ada and/or C)
10549 @item
10550 Source file naming conventions; you can specify these either globally or for
10551 individual compilation units
10552 @end itemize
10554 @menu
10555 * Project Files::
10556 @end menu
10558 @node Project Files
10559 @subsection Project Files
10561 @noindent
10562 Project files are written in a syntax close to that of Ada, using  familiar
10563 notions such as packages, context clauses, declarations, default values,
10564 assignments, and inheritance. Finally, project files can be built
10565 hierarchically from other project files, simplifying complex system
10566 integration and project reuse.
10568 A @dfn{project} is a specific set of values for various compilation properties.
10569 The settings for a given project are described by means of
10570 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10571 Property values in project files are either strings or lists of strings.
10572 Properties that are not explicitly set receive default values.  A project
10573 file may interrogate the values of @dfn{external variables} (user-defined
10574 command-line switches or environment variables), and it may specify property
10575 settings conditionally, based on the value of such variables.
10577 In simple cases, a project's source files depend only on other source files
10578 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10579 used in
10580 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10581 the Project Manager also allows more sophisticated arrangements,
10582 where the source files in one project depend on source files in other
10583 projects:
10584 @itemize @bullet
10585 @item
10586 One project can @emph{import} other projects containing needed source files.
10587 @item
10588 You can organize GNAT projects in a hierarchy: a @emph{child} project
10589 can extend a @emph{parent} project, inheriting the parent's source files and
10590 optionally overriding any of them with alternative versions
10591 @end itemize
10593 @noindent
10594 More generally, the Project Manager lets you structure large development
10595 efforts into hierarchical subsystems, where build decisions are delegated
10596 to the subsystem level, and thus different compilation environments
10597 (^switch^switch^ settings) used for different subsystems.
10599 The Project Manager is invoked through the
10600 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10601 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10602 @ifclear vms
10603 There may be zero, one or more spaces between @option{-P} and
10604 @option{@emph{projectfile}}.
10605 @end ifclear
10606 If you want to define (on the command line) an external variable that is
10607 queried by the project file, you must use the
10608 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10609 The Project Manager parses and interprets the project file, and drives the
10610 invoked tool based on the project settings.
10612 The Project Manager supports a wide range of development strategies,
10613 for systems of all sizes.  Here are some typical practices that are
10614 easily handled:
10615 @itemize @bullet
10616 @item
10617 Using a common set of source files, but generating object files in different
10618 directories via different ^switch^switch^ settings
10619 @item
10620 Using a mostly-shared set of source files, but with different versions of
10621 some unit or units
10622 @end itemize
10624 @noindent
10625 The destination of an executable can be controlled inside a project file
10626 using the @option{^-o^-o^}
10627 ^switch^switch^.
10628 In the absence of such a ^switch^switch^ either inside
10629 the project file or on the command line, any executable files generated by
10630 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10631 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10632 in the object directory of the project.
10634 You can use project files to achieve some of the effects of a source
10635 versioning system (for example, defining separate projects for
10636 the different sets of sources that comprise different releases) but the
10637 Project Manager is independent of any source configuration management tools
10638 that might be used by the developers.
10640 The next section introduces the main features of GNAT's project facility
10641 through a sequence of examples; subsequent sections will present the syntax
10642 and semantics in more detail. A more formal description of the project
10643 facility appears in the GNAT Reference Manual.
10645 @c *****************************
10646 @c * Examples of Project Files *
10647 @c *****************************
10649 @node Examples of Project Files
10650 @section Examples of Project Files
10651 @noindent
10652 This section illustrates some of the typical uses of project files and
10653 explains their basic structure and behavior.
10655 @menu
10656 * Common Sources with Different ^Switches^Switches^ and Directories::
10657 * Using External Variables::
10658 * Importing Other Projects::
10659 * Extending a Project::
10660 @end menu
10662 @node Common Sources with Different ^Switches^Switches^ and Directories
10663 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10665 @menu
10666 * Source Files::
10667 * Specifying the Object Directory::
10668 * Specifying the Exec Directory::
10669 * Project File Packages::
10670 * Specifying ^Switch^Switch^ Settings::
10671 * Main Subprograms::
10672 * Executable File Names::
10673 * Source File Naming Conventions::
10674 * Source Language(s)::
10675 @end menu
10677 @noindent
10678 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10679 @file{proc.adb} are in the @file{/common} directory.  The file
10680 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10681 package @code{Pack}.  We want to compile these source files under two sets
10682 of ^switches^switches^:
10683 @itemize @bullet
10684 @item
10685 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10686 and the @option{^-gnata^-gnata^},
10687 @option{^-gnato^-gnato^},
10688 and @option{^-gnatE^-gnatE^} switches to the
10689 compiler; the compiler's output is to appear in @file{/common/debug}
10690 @item
10691 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10692 to the compiler; the compiler's output is to appear in @file{/common/release}
10693 @end itemize
10695 @noindent
10696 The GNAT project files shown below, respectively @file{debug.gpr} and
10697 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10699 Schematically:
10700 @smallexample
10701 @group
10702 ^/common^[COMMON]^
10703   debug.gpr
10704   release.gpr
10705   pack.ads
10706   pack.adb
10707   proc.adb
10708 @end group
10709 @group
10710 ^/common/debug^[COMMON.DEBUG]^
10711   proc.ali, proc.o
10712   pack.ali, pack.o
10713 @end group
10714 @group
10715 ^/common/release^[COMMON.RELEASE]^
10716   proc.ali, proc.o
10717   pack.ali, pack.o
10718 @end group
10719 @end smallexample
10720 Here are the corresponding project files:
10722 @smallexample @c projectfile
10723 @group
10724 project Debug is
10725   for Object_Dir use "debug";
10726   for Main use ("proc");
10728   package Builder is
10729     for ^Default_Switches^Default_Switches^ ("Ada")
10730         use ("^-g^-g^");
10731     for Executable ("proc.adb") use "proc1";
10732   end Builder;
10733 @end group
10735 @group
10736   package Compiler is
10737     for ^Default_Switches^Default_Switches^ ("Ada")
10738        use ("-fstack-check",
10739             "^-gnata^-gnata^",
10740             "^-gnato^-gnato^",
10741             "^-gnatE^-gnatE^");
10742   end Compiler;
10743 end Debug;
10744 @end group
10745 @end smallexample
10747 @smallexample @c projectfile
10748 @group
10749 project Release is
10750   for Object_Dir use "release";
10751   for Exec_Dir use ".";
10752   for Main use ("proc");
10754   package Compiler is
10755     for ^Default_Switches^Default_Switches^ ("Ada")
10756         use ("^-O2^-O2^");
10757   end Compiler;
10758 end Release;
10759 @end group
10760 @end smallexample
10762 @noindent
10763 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10764 insensitive), and analogously the project defined by @file{release.gpr} is
10765 @code{"Release"}.  For consistency the file should have the same name as the
10766 project, and the project file's extension should be @code{"gpr"}. These
10767 conventions are not required, but a warning is issued if they are not followed.
10769 If the current directory is @file{^/temp^[TEMP]^}, then the command
10770 @smallexample
10771 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10772 @end smallexample
10774 @noindent
10775 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10776 as well as the @code{^proc1^PROC1.EXE^} executable,
10777 using the ^switch^switch^ settings defined in the project file.
10779 Likewise, the command
10780 @smallexample
10781 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10782 @end smallexample
10784 @noindent
10785 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10786 and the @code{^proc^PROC.EXE^}
10787 executable in @file{^/common^[COMMON]^},
10788 using the ^switch^switch^ settings from the project file.
10790 @node Source Files
10791 @unnumberedsubsubsec Source Files
10793 @noindent
10794 If a project file does not explicitly specify a set of source directories or
10795 a set of source files, then by default the project's source files are the
10796 Ada source files in the project file directory.  Thus @file{pack.ads},
10797 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10799 @node Specifying the Object Directory
10800 @unnumberedsubsubsec Specifying the Object Directory
10802 @noindent
10803 Several project properties are modeled by Ada-style @emph{attributes};
10804 a property is defined by supplying the equivalent of an Ada attribute
10805 definition clause in the project file.
10806 A project's object directory is another such a property; the corresponding
10807 attribute is @code{Object_Dir}, and its value is also a string expression,
10808 specified either as absolute or relative. In the later case,
10809 it is relative to the project file directory. Thus the compiler's
10810 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10811 (for the @code{Debug} project)
10812 and to @file{^/common/release^[COMMON.RELEASE]^}
10813 (for the @code{Release} project).
10814 If @code{Object_Dir} is not specified, then the default is the project file
10815 directory itself.
10817 @node Specifying the Exec Directory
10818 @unnumberedsubsubsec Specifying the Exec Directory
10820 @noindent
10821 A project's exec directory is another property; the corresponding
10822 attribute is @code{Exec_Dir}, and its value is also a string expression,
10823 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10824 then the default is the object directory (which may also be the project file
10825 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10826 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10827 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10828 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10830 @node Project File Packages
10831 @unnumberedsubsubsec Project File Packages
10833 @noindent
10834 A GNAT tool that is integrated with the Project Manager is modeled by a
10835 corresponding package in the project file. In the example above,
10836 The @code{Debug} project defines the packages @code{Builder}
10837 (for @command{gnatmake}) and @code{Compiler};
10838 the @code{Release} project defines only the @code{Compiler} package.
10840 The Ada-like package syntax is not to be taken literally.  Although packages in
10841 project files bear a surface resemblance to packages in Ada source code, the
10842 notation is simply a way to convey a grouping of properties for a named
10843 entity.  Indeed, the package names permitted in project files are restricted
10844 to a predefined set, corresponding to the project-aware tools, and the contents
10845 of packages are limited to a small set of constructs.
10846 The packages in the example above contain attribute definitions.
10848 @node Specifying ^Switch^Switch^ Settings
10849 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10851 @noindent
10852 ^Switch^Switch^ settings for a project-aware tool can be specified through
10853 attributes in the package that corresponds to the tool.
10854 The example above illustrates one of the relevant attributes,
10855 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10856 in both project files.
10857 Unlike simple attributes like @code{Source_Dirs},
10858 @code{^Default_Switches^Default_Switches^} is
10859 known as an @emph{associative array}.  When you define this attribute, you must
10860 supply an ``index'' (a literal string), and the effect of the attribute
10861 definition is to set the value of the array at the specified index.
10862 For the @code{^Default_Switches^Default_Switches^} attribute,
10863 the index is a programming language (in our case, Ada),
10864 and the value specified (after @code{use}) must be a list
10865 of string expressions.
10867 The attributes permitted in project files are restricted to a predefined set.
10868 Some may appear at project level, others in packages.
10869 For any attribute that is an associative array, the index must always be a
10870 literal string, but the restrictions on this string (e.g., a file name or a
10871 language name) depend on the individual attribute.
10872 Also depending on the attribute, its specified value will need to be either a
10873 string or a string list.
10875 In the @code{Debug} project, we set the switches for two tools,
10876 @command{gnatmake} and the compiler, and thus we include the two corresponding
10877 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10878 attribute with index @code{"Ada"}.
10879 Note that the package corresponding to
10880 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10881 similar, but only includes the @code{Compiler} package.
10883 In project @code{Debug} above, the ^switches^switches^ starting with
10884 @option{-gnat} that are specified in package @code{Compiler}
10885 could have been placed in package @code{Builder}, since @command{gnatmake}
10886 transmits all such ^switches^switches^ to the compiler.
10888 @node Main Subprograms
10889 @unnumberedsubsubsec Main Subprograms
10891 @noindent
10892 One of the specifiable properties of a project is a list of files that contain
10893 main subprograms.  This property is captured in the @code{Main} attribute,
10894 whose value is a list of strings.  If a project defines the @code{Main}
10895 attribute, it is not necessary to identify the main subprogram(s) when
10896 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
10898 @node Executable File Names
10899 @unnumberedsubsubsec Executable File Names
10901 @noindent
10902 By default, the executable file name corresponding to a main source is
10903 deduced from the main source file name. Through the attributes
10904 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10905 it is possible to change this default.
10906 In project @code{Debug} above, the executable file name
10907 for main source @file{^proc.adb^PROC.ADB^} is
10908 @file{^proc1^PROC1.EXE^}.
10909 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10910 of the the executable files, when no attribute @code{Executable} applies:
10911 its value replace the platform-specific executable suffix.
10912 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10913 specify a non default executable file name when several mains are built at once
10914 in a single @command{gnatmake} command.
10916 @node Source File Naming Conventions
10917 @unnumberedsubsubsec Source File Naming Conventions
10919 @noindent
10920 Since the project files above do not specify any source file naming
10921 conventions, the GNAT defaults are used.  The mechanism for defining source
10922 file naming conventions -- a package named @code{Naming} --
10923 is described below (@pxref{Naming Schemes}).
10925 @node Source Language(s)
10926 @unnumberedsubsubsec Source Language(s)
10928 @noindent
10929 Since the project files do not specify a @code{Languages} attribute, by
10930 default the GNAT tools assume that the language of the project file is Ada.
10931 More generally, a project can comprise source files
10932 in Ada, C, and/or other languages.
10934 @node Using External Variables
10935 @subsection Using External Variables
10937 @noindent
10938 Instead of supplying different project files for debug and release, we can
10939 define a single project file that queries an external variable (set either
10940 on the command line or via an ^environment variable^logical name^) in order to
10941 conditionally define the appropriate settings.  Again, assume that the
10942 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10943 located in directory @file{^/common^[COMMON]^}.  The following project file,
10944 @file{build.gpr}, queries the external variable named @code{STYLE} and
10945 defines an object directory and ^switch^switch^ settings based on whether
10946 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10947 the default is @code{"deb"}.
10949 @smallexample @c projectfile
10950 @group
10951 project Build is
10952   for Main use ("proc");
10954   type Style_Type is ("deb", "rel");
10955   Style : Style_Type := external ("STYLE", "deb");
10957   case Style is
10958     when "deb" =>
10959       for Object_Dir use "debug";
10961     when "rel" =>
10962       for Object_Dir use "release";
10963       for Exec_Dir use ".";
10964   end case;
10965 @end group
10967 @group
10968   package Builder is
10970     case Style is
10971       when "deb" =>
10972         for ^Default_Switches^Default_Switches^ ("Ada")
10973             use ("^-g^-g^");
10974         for Executable ("proc") use "proc1";
10975       when others =>
10976         null;
10977     end case;
10979   end Builder;
10980 @end group
10982 @group
10983   package Compiler is
10985     case Style is
10986       when "deb" =>
10987         for ^Default_Switches^Default_Switches^ ("Ada")
10988             use ("^-gnata^-gnata^",
10989                  "^-gnato^-gnato^",
10990                  "^-gnatE^-gnatE^");
10992       when "rel" =>
10993         for ^Default_Switches^Default_Switches^ ("Ada")
10994             use ("^-O2^-O2^");
10995     end case;
10997   end Compiler;
10999 end Build;
11000 @end group
11001 @end smallexample
11003 @noindent
11004 @code{Style_Type} is an example of a @emph{string type}, which is the project
11005 file analog of an Ada enumeration type but whose components are string literals
11006 rather than identifiers.  @code{Style} is declared as a variable of this type.
11008 The form @code{external("STYLE", "deb")} is known as an
11009 @emph{external reference}; its first argument is the name of an
11010 @emph{external variable}, and the second argument is a default value to be
11011 used if the external variable doesn't exist.  You can define an external
11012 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11013 or you can use ^an environment variable^a logical name^
11014 as an external variable.
11016 Each @code{case} construct is expanded by the Project Manager based on the
11017 value of @code{Style}. Thus the command
11018 @ifclear vms
11019 @smallexample
11020 gnatmake -P/common/build.gpr -XSTYLE=deb
11021 @end smallexample
11022 @end ifclear
11024 @ifset vms
11025 @smallexample
11026 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11027 @end smallexample
11028 @end ifset
11030 @noindent
11031 is equivalent to the @command{gnatmake} invocation using the project file
11032 @file{debug.gpr} in the earlier example.  So is the command
11033 @smallexample
11034 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11035 @end smallexample
11037 @noindent
11038 since @code{"deb"} is the default for @code{STYLE}.
11040 Analogously,
11042 @ifclear vms
11043 @smallexample
11044 gnatmake -P/common/build.gpr -XSTYLE=rel
11045 @end smallexample
11046 @end ifclear
11048 @ifset vms
11049 @smallexample
11050 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11051 @end smallexample
11052 @end ifset
11054 @noindent
11055 is equivalent to the @command{gnatmake} invocation using the project file
11056 @file{release.gpr} in the earlier example.
11058 @node Importing Other Projects
11059 @subsection Importing Other Projects
11060 @cindex @code{ADA_PROJECT_PATH}
11062 @noindent
11063 A compilation unit in a source file in one project may depend on compilation
11064 units in source files in other projects.  To compile this unit under
11065 control of a project file, the
11066 dependent project must @emph{import} the projects containing the needed source
11067 files.
11068 This effect is obtained using syntax similar to an Ada @code{with} clause,
11069 but where @code{with}ed entities are strings that denote project files.
11071 As an example, suppose that the two projects @code{GUI_Proj} and
11072 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11073 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11074 and @file{^/comm^[COMM]^}, respectively.
11075 Suppose that the source files for @code{GUI_Proj} are
11076 @file{gui.ads} and @file{gui.adb}, and that the source files for
11077 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11078 files is located in its respective project file directory.  Schematically:
11080 @smallexample
11081 @group
11082 ^/gui^[GUI]^
11083   gui_proj.gpr
11084   gui.ads
11085   gui.adb
11086 @end group
11088 @group
11089 ^/comm^[COMM]^
11090   comm_proj.gpr
11091   comm.ads
11092   comm.adb
11093 @end group
11094 @end smallexample
11096 @noindent
11097 We want to develop an application in directory @file{^/app^[APP]^} that
11098 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11099 the corresponding project files (e.g. the ^switch^switch^ settings
11100 and object directory).
11101 Skeletal code for a main procedure might be something like the following:
11103 @smallexample @c ada
11104 @group
11105 with GUI, Comm;
11106 procedure App_Main is
11107    ...
11108 begin
11109    ...
11110 end App_Main;
11111 @end group
11112 @end smallexample
11114 @noindent
11115 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11116 effect:
11118 @smallexample @c projectfile
11119 @group
11120 with "/gui/gui_proj", "/comm/comm_proj";
11121 project App_Proj is
11122    for Main use ("app_main");
11123 end App_Proj;
11124 @end group
11125 @end smallexample
11127 @noindent
11128 Building an executable is achieved through the command:
11129 @smallexample
11130 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11131 @end smallexample
11132 @noindent
11133 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11134 in the directory where @file{app_proj.gpr} resides.
11136 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11137 (as illustrated above) the @code{with} clause can omit the extension.
11139 Our example specified an absolute path for each imported project file.
11140 Alternatively, the directory name of an imported object can be omitted
11141 if either
11142 @itemize @bullet
11143 @item
11144 The imported project file is in the same directory as the importing project
11145 file, or
11146 @item
11147 You have defined ^an environment variable^a logical name^
11148 that includes the directory containing
11149 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11150 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11151 directory names separated by colons (semicolons on Windows).
11152 @end itemize
11154 @noindent
11155 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11156 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11157 as follows:
11159 @smallexample @c projectfile
11160 @group
11161 with "gui_proj", "comm_proj";
11162 project App_Proj is
11163    for Main use ("app_main");
11164 end App_Proj;
11165 @end group
11166 @end smallexample
11168 @noindent
11169 Importing other projects can create ambiguities.
11170 For example, the same unit might be present in different imported projects, or
11171 it might be present in both the importing project and in an imported project.
11172 Both of these conditions are errors.  Note that in the current version of
11173 the Project Manager, it is illegal to have an ambiguous unit even if the
11174 unit is never referenced by the importing project.  This restriction may be
11175 relaxed in a future release.
11177 @node Extending a Project
11178 @subsection Extending a Project
11180 @noindent
11181 In large software systems it is common to have multiple
11182 implementations of a common interface; in Ada terms, multiple versions of a
11183 package body for the same specification.  For example, one implementation
11184 might be safe for use in tasking programs, while another might only be used
11185 in sequential applications.  This can be modeled in GNAT using the concept
11186 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11187 another project (the ``parent'') then by default all source files of the
11188 parent project are inherited by the child, but the child project can
11189 override any of the parent's source files with new versions, and can also
11190 add new files.  This facility is the project analog of a type extension in
11191 Object-Oriented Programming.  Project hierarchies are permitted (a child
11192 project may be the parent of yet another project), and a project that
11193 inherits one project can also import other projects.
11195 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11196 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11197 @file{pack.adb}, and @file{proc.adb}:
11199 @smallexample
11200 @group
11201 ^/seq^[SEQ]^
11202   pack.ads
11203   pack.adb
11204   proc.adb
11205   seq_proj.gpr
11206 @end group
11207 @end smallexample
11209 @noindent
11210 Note that the project file can simply be empty (that is, no attribute or
11211 package is defined):
11213 @smallexample @c projectfile
11214 @group
11215 project Seq_Proj is
11216 end Seq_Proj;
11217 @end group
11218 @end smallexample
11220 @noindent
11221 implying that its source files are all the Ada source files in the project
11222 directory.
11224 Suppose we want to supply an alternate version of @file{pack.adb}, in
11225 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11226 @file{pack.ads} and @file{proc.adb}.  We can define a project
11227 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11229 @smallexample
11230 @group
11231 ^/tasking^[TASKING]^
11232   pack.adb
11233   tasking_proj.gpr
11234 @end group
11236 @group
11237 project Tasking_Proj extends "/seq/seq_proj" is
11238 end Tasking_Proj;
11239 @end group
11240 @end smallexample
11242 @noindent
11243 The version of @file{pack.adb} used in a build depends on which project file
11244 is specified.
11246 Note that we could have obtained the desired behavior using project import
11247 rather than project inheritance; a @code{base} project would contain the
11248 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11249 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11250 would import @code{base} and add a different version of @file{pack.adb}.  The
11251 choice depends on whether other sources in the original project need to be
11252 overridden.  If they do, then project extension is necessary, otherwise,
11253 importing is sufficient.
11255 @noindent
11256 In a project file that extends another project file, it is possible to
11257 indicate that an inherited source is not part of the sources of the extending
11258 project. This is necessary sometimes when a package spec has been overloaded
11259 and no longer requires a body: in this case, it is necessary to indicate that
11260 the inherited body is not part of the sources of the project, otherwise there
11261 will be a compilation error when compiling the spec.
11263 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11264 Its value is a string list: a list of file names.
11266 @smallexample @c @projectfile
11267 project B extends "a" is
11268    for Source_Files use ("pkg.ads");
11269    --  New spec of Pkg does not need a completion
11270    for Locally_Removed_Files use ("pkg.adb");
11271 end B;
11272 @end smallexample
11274 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11275 is still needed: if it is possible to build using @command{gnatmake} when such
11276 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11277 it is possible to remove the source completely from a system that includes
11278 project P.
11280 @c ***********************
11281 @c * Project File Syntax *
11282 @c ***********************
11284 @node Project File Syntax
11285 @section Project File Syntax
11287 @menu
11288 * Basic Syntax::
11289 * Packages::
11290 * Expressions::
11291 * String Types::
11292 * Variables::
11293 * Attributes::
11294 * Associative Array Attributes::
11295 * case Constructions::
11296 @end menu
11298 @noindent
11299 This section describes the structure of project files.
11301 A project may be an @emph{independent project}, entirely defined by a single
11302 project file. Any Ada source file in an independent project depends only
11303 on the predefined library and other Ada source files in the same project.
11305 @noindent
11306 A project may also @dfn{depend on} other projects, in either or both of
11307 the following ways:
11308 @itemize @bullet
11309 @item It may import any number of projects
11310 @item It may extend at most one other project
11311 @end itemize
11313 @noindent
11314 The dependence relation is a directed acyclic graph (the subgraph reflecting
11315 the ``extends'' relation is a tree).
11317 A project's @dfn{immediate sources} are the source files directly defined by
11318 that project, either implicitly by residing in the project file's directory,
11319 or explicitly through any of the source-related attributes described below.
11320 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11321 of @var{proj} together with the immediate sources (unless overridden) of any
11322 project on which @var{proj} depends (either directly or indirectly).
11324 @node Basic Syntax
11325 @subsection Basic Syntax
11327 @noindent
11328 As seen in the earlier examples, project files have an Ada-like syntax.
11329 The minimal project file is:
11330 @smallexample @c projectfile
11331 @group
11332 project Empty is
11334 end Empty;
11335 @end group
11336 @end smallexample
11338 @noindent
11339 The identifier @code{Empty} is the name of the project.
11340 This project name must be present after the reserved
11341 word @code{end} at the end of the project file, followed by a semi-colon.
11343 Any name in a project file, such as the project name or a variable name,
11344 has the same syntax as an Ada identifier.
11346 The reserved words of project files are the Ada reserved words plus
11347 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11348 reserved words currently used in project file syntax are:
11350 @itemize @bullet
11351 @item
11352 @code{case}
11353 @item
11354 @code{end}
11355 @item
11356 @code{for}
11357 @item
11358 @code{is}
11359 @item
11360 @code{others}
11361 @item
11362 @code{package}
11363 @item
11364 @code{renames}
11365 @item
11366 @code{type}
11367 @item
11368 @code{use}
11369 @item
11370 @code{when}
11371 @item
11372 @code{with}
11373 @end itemize
11375 @noindent
11376 Comments in project files have the same syntax as in Ada, two consecutives
11377 hyphens through the end of the line.
11379 @node Packages
11380 @subsection Packages
11382 @noindent
11383 A project file may contain @emph{packages}. The name of a package must be one
11384 of the identifiers from the following list. A package
11385 with a given name may only appear once in a project file. Package names are
11386 case insensitive. The following package names are legal:
11388 @itemize @bullet
11389 @item
11390 @code{Naming}
11391 @item
11392 @code{Builder}
11393 @item
11394 @code{Compiler}
11395 @item
11396 @code{Binder}
11397 @item
11398 @code{Linker}
11399 @item
11400 @code{Finder}
11401 @item
11402 @code{Cross_Reference}
11403 @item
11404 @code{Eliminate}
11405 @item
11406 @code{Pretty_Printer}
11407 @item
11408 @code{Metrics}
11409 @item
11410 @code{gnatls}
11411 @item
11412 @code{gnatstub}
11413 @item
11414 @code{IDE}
11415 @item
11416 @code{Language_Processing}
11417 @end itemize
11419 @noindent
11420 In its simplest form, a package may be empty:
11422 @smallexample @c projectfile
11423 @group
11424 project Simple is
11425   package Builder is
11426   end Builder;
11427 end Simple;
11428 @end group
11429 @end smallexample
11431 @noindent
11432 A package may contain @emph{attribute declarations},
11433 @emph{variable declarations} and @emph{case constructions}, as will be
11434 described below.
11436 When there is ambiguity between a project name and a package name,
11437 the name always designates the project. To avoid possible confusion, it is
11438 always a good idea to avoid naming a project with one of the
11439 names allowed for packages or any name that starts with @code{gnat}.
11441 @node Expressions
11442 @subsection Expressions
11444 @noindent
11445 An @emph{expression} is either a @emph{string expression} or a
11446 @emph{string list expression}.
11448 A @emph{string expression} is either a @emph{simple string expression} or a
11449 @emph{compound string expression}.
11451 A @emph{simple string expression} is one of the following:
11452 @itemize @bullet
11453 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11454 @item A string-valued variable reference (@pxref{Variables})
11455 @item A string-valued attribute reference (@pxref{Attributes})
11456 @item An external reference (@pxref{External References in Project Files})
11457 @end itemize
11459 @noindent
11460 A @emph{compound string expression} is a concatenation of string expressions,
11461 using the operator @code{"&"}
11462 @smallexample
11463        Path & "/" & File_Name & ".ads"
11464 @end smallexample
11466 @noindent
11467 A @emph{string list expression} is either a
11468 @emph{simple string list expression} or a
11469 @emph{compound string list expression}.
11471 A @emph{simple string list expression} is one of the following:
11472 @itemize @bullet
11473 @item A parenthesized list of zero or more string expressions,
11474 separated by commas
11475 @smallexample
11476    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11477    Empty_List := ();
11478 @end smallexample
11479 @item A string list-valued variable reference
11480 @item A string list-valued attribute reference
11481 @end itemize
11483 @noindent
11484 A @emph{compound string list expression} is the concatenation (using
11485 @code{"&"}) of a simple string list expression and an expression.  Note that
11486 each term in a compound string list expression, except the first, may be
11487 either a string expression or a string list expression.
11489 @smallexample @c projectfile
11490 @group
11491    File_Name_List := () & File_Name; --  One string in this list
11492    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11493    --  Two strings
11494    Big_List := File_Name_List & Extended_File_Name_List;
11495    --  Concatenation of two string lists: three strings
11496    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11497    --  Illegal: must start with a string list
11498 @end group
11499 @end smallexample
11501 @node String Types
11502 @subsection String Types
11504 @noindent
11505 A @emph{string type declaration} introduces a discrete set of string literals.
11506 If a string variable is declared to have this type, its value
11507 is restricted to the given set of literals.
11509 Here is an example of a string type declaration:
11511 @smallexample @c projectfile
11512    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11513 @end smallexample
11515 @noindent
11516 Variables of a string type are called @emph{typed variables}; all other
11517 variables are called @emph{untyped variables}. Typed variables are
11518 particularly useful in @code{case} constructions, to support conditional
11519 attribute declarations.
11520 (@pxref{case Constructions}).
11522 The string literals in the list are case sensitive and must all be different.
11523 They may include any graphic characters allowed in Ada, including spaces.
11525 A string type may only be declared at the project level, not inside a package.
11527 A string type may be referenced by its name if it has been declared in the same
11528 project file, or by an expanded name whose prefix is the name of the project
11529 in which it is declared.
11531 @node Variables
11532 @subsection Variables
11534 @noindent
11535 A variable may be declared at the project file level, or within a package.
11536 Here are some examples of variable declarations:
11538 @smallexample @c projectfile
11539 @group
11540    This_OS : OS := external ("OS"); --  a typed variable declaration
11541    That_OS := "GNU/Linux";          --  an untyped variable declaration
11542 @end group
11543 @end smallexample
11545 @noindent
11546 The syntax of a @emph{typed variable declaration} is identical to the Ada
11547 syntax for an object declaration. By contrast, the syntax of an untyped
11548 variable declaration is identical to an Ada assignment statement. In fact,
11549 variable declarations in project files have some of the characteristics of
11550 an assignment, in that successive declarations for the same variable are
11551 allowed. Untyped variable declarations do establish the expected kind of the
11552 variable (string or string list), and successive declarations for it must
11553 respect the initial kind.
11555 @noindent
11556 A string variable declaration (typed or untyped) declares a variable
11557 whose value is a string. This variable may be used as a string expression.
11558 @smallexample @c projectfile
11559    File_Name       := "readme.txt";
11560    Saved_File_Name := File_Name & ".saved";
11561 @end smallexample
11563 @noindent
11564 A string list variable declaration declares a variable whose value is a list
11565 of strings. The list may contain any number (zero or more) of strings.
11567 @smallexample @c projectfile
11568    Empty_List := ();
11569    List_With_One_Element := ("^-gnaty^-gnaty^");
11570    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11571    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11572                  "pack2.ada", "util_.ada", "util.ada");
11573 @end smallexample
11575 @noindent
11576 The same typed variable may not be declared more than once at project level,
11577 and it may not be declared more than once in any package; it is in effect
11578 a constant.
11580 The same untyped variable may be declared several times. Declarations are
11581 elaborated in the order in which they appear, so  the new value replaces
11582 the old one, and any subsequent reference to the variable uses the new value.
11583 However, as noted above, if a variable has been declared as a string, all
11584 subsequent
11585 declarations must give it a string value. Similarly, if a variable has
11586 been declared as a string list, all subsequent declarations
11587 must give it a string list value.
11589 A @emph{variable reference} may take several forms:
11591 @itemize @bullet
11592 @item The simple variable name, for a variable in the current package (if any)
11593 or in the current project
11594 @item An expanded name, whose prefix is a context name.
11595 @end itemize
11597 @noindent
11598 A @emph{context} may be one of the following:
11600 @itemize @bullet
11601 @item The name of an existing package in the current project
11602 @item The name of an imported project of the current project
11603 @item The name of an ancestor project (i.e., a project extended by the current
11604 project, either directly or indirectly)
11605 @item An expanded name whose prefix is an imported/parent project name, and
11606 whose selector is a package name in that project.
11607 @end itemize
11609 @noindent
11610 A variable reference may be used in an expression.
11612 @node Attributes
11613 @subsection Attributes
11615 @noindent
11616 A project (and its packages) may have @emph{attributes} that define
11617 the project's properties.  Some attributes have values that are strings;
11618 others have values that are string lists.
11620 There are two categories of attributes: @emph{simple attributes}
11621 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11623 Legal project attribute names, and attribute names for each legal package are
11624 listed below. Attributes names are case-insensitive.
11626 The following attributes are defined on projects (all are simple attributes):
11628 @multitable @columnfractions .4 .3
11629 @item @emph{Attribute Name}
11630 @tab @emph{Value}
11631 @item @code{Source_Files}
11632 @tab string list
11633 @item @code{Source_Dirs}
11634 @tab string list
11635 @item @code{Source_List_File}
11636 @tab string
11637 @item @code{Object_Dir}
11638 @tab string
11639 @item @code{Exec_Dir}
11640 @tab string
11641 @item @code{Locally_Removed_Files}
11642 @tab string list
11643 @item @code{Languages}
11644 @tab string list
11645 @item @code{Main}
11646 @tab string list
11647 @item @code{Library_Dir}
11648 @tab string
11649 @item @code{Library_Name}
11650 @tab string
11651 @item @code{Library_Kind}
11652 @tab string
11653 @item @code{Library_Version}
11654 @tab string
11655 @item @code{Library_Interface}
11656 @tab string
11657 @item @code{Library_Auto_Init}
11658 @tab string
11659 @item @code{Library_Options}
11660 @tab string list
11661 @item @code{Library_Src_Dir}
11662 @tab string
11663 @item @code{Library_ALI_Dir}
11664 @tab string
11665 @item @code{Library_GCC}
11666 @tab string
11667 @item @code{Library_Symbol_File}
11668 @tab string
11669 @item @code{Library_Symbol_Policy}
11670 @tab string
11671 @item @code{Library_Reference_Symbol_File}
11672 @tab string
11673 @item @code{Externally_Built}
11674 @tab string
11675 @end multitable
11677 @noindent
11678 The following attributes are defined for package  @code{Naming}
11679 (@pxref{Naming Schemes}):
11681 @multitable @columnfractions .4 .2 .2 .2
11682 @item Attribute Name @tab Category @tab Index @tab Value
11683 @item @code{Spec_Suffix}
11684 @tab associative array
11685 @tab language name
11686 @tab string
11687 @item @code{Body_Suffix}
11688 @tab associative array
11689 @tab language name
11690 @tab string
11691 @item @code{Separate_Suffix}
11692 @tab simple attribute
11693 @tab n/a
11694 @tab string
11695 @item @code{Casing}
11696 @tab simple attribute
11697 @tab n/a
11698 @tab string
11699 @item @code{Dot_Replacement}
11700 @tab simple attribute
11701 @tab n/a
11702 @tab string
11703 @item @code{Spec}
11704 @tab associative array
11705 @tab Ada unit name
11706 @tab string
11707 @item @code{Body}
11708 @tab associative array
11709 @tab Ada unit name
11710 @tab string
11711 @item @code{Specification_Exceptions}
11712 @tab associative array
11713 @tab language name
11714 @tab string list
11715 @item @code{Implementation_Exceptions}
11716 @tab associative array
11717 @tab language name
11718 @tab string list
11719 @end multitable
11721 @noindent
11722 The following attributes are defined for packages @code{Builder},
11723 @code{Compiler}, @code{Binder},
11724 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11725 (@pxref{^Switches^Switches^ and Project Files}).
11727 @multitable @columnfractions .4 .2 .2 .2
11728 @item Attribute Name @tab Category @tab Index @tab Value
11729 @item @code{^Default_Switches^Default_Switches^}
11730 @tab associative array
11731 @tab language name
11732 @tab string list
11733 @item @code{^Switches^Switches^}
11734 @tab associative array
11735 @tab file name
11736 @tab string list
11737 @end multitable
11739 @noindent
11740 In addition, package @code{Compiler} has a single string attribute
11741 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11742 string attribute @code{Global_Configuration_Pragmas}.
11744 @noindent
11745 Each simple attribute has a default value: the empty string (for string-valued
11746 attributes) and the empty list (for string list-valued attributes).
11748 An attribute declaration defines a new value for an attribute.
11750 Examples of simple attribute declarations:
11752 @smallexample @c projectfile
11753    for Object_Dir use "objects";
11754    for Source_Dirs use ("units", "test/drivers");
11755 @end smallexample
11757 @noindent
11758 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11759 attribute definition clause in Ada.
11761 Attributes references may be appear in expressions.
11762 The general form for such a reference is @code{<entity>'<attribute>}:
11763 Associative array attributes are functions. Associative
11764 array attribute references must have an argument that is a string literal.
11766 Examples are:
11768 @smallexample @c projectfile
11769   project'Object_Dir
11770   Naming'Dot_Replacement
11771   Imported_Project'Source_Dirs
11772   Imported_Project.Naming'Casing
11773   Builder'^Default_Switches^Default_Switches^("Ada")
11774 @end smallexample
11776 @noindent
11777 The prefix of an attribute may be:
11778 @itemize @bullet
11779 @item @code{project} for an attribute of the current project
11780 @item The name of an existing package of the current project
11781 @item The name of an imported project
11782 @item The name of a parent project that is extended by the current project
11783 @item An expanded name whose prefix is imported/parent project name,
11784       and whose selector is a package name
11785 @end itemize
11787 @noindent
11788 Example:
11789 @smallexample @c projectfile
11790 @group
11791    project Prj is
11792      for Source_Dirs use project'Source_Dirs & "units";
11793      for Source_Dirs use project'Source_Dirs & "test/drivers"
11794    end Prj;
11795 @end group
11796 @end smallexample
11798 @noindent
11799 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11800 has the default value: an empty string list. After this declaration,
11801 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11802 After the second attribute declaration @code{Source_Dirs} is a string list of
11803 two elements: @code{"units"} and @code{"test/drivers"}.
11805 Note: this example is for illustration only. In practice,
11806 the project file would contain only one attribute declaration:
11808 @smallexample @c projectfile
11809    for Source_Dirs use ("units", "test/drivers");
11810 @end smallexample
11812 @node Associative Array Attributes
11813 @subsection Associative Array Attributes
11815 @noindent
11816 Some attributes are defined as @emph{associative arrays}. An associative
11817 array may be regarded as a function that takes a string as a parameter
11818 and delivers a string or string list value as its result.
11820 Here are some examples of single associative array attribute associations:
11822 @smallexample @c projectfile
11823    for Body ("main") use "Main.ada";
11824    for ^Switches^Switches^ ("main.ada")
11825        use ("^-v^-v^",
11826             "^-gnatv^-gnatv^");
11827    for ^Switches^Switches^ ("main.ada")
11828             use Builder'^Switches^Switches^ ("main.ada")
11829               & "^-g^-g^";
11830 @end smallexample
11832 @noindent
11833 Like untyped variables and simple attributes, associative array attributes
11834 may be declared several times. Each declaration supplies a new value for the
11835 attribute, and replaces the previous setting.
11837 @noindent
11838 An associative array attribute may be declared as a full associative array
11839 declaration, with the value of the same attribute in an imported or extended
11840 project.
11842 @smallexample @c projectfile
11843    package Builder is
11844       for Default_Switches use Default.Builder'Default_Switches;
11845    end Builder;
11846 @end smallexample
11848 @noindent
11849 In this example, @code{Default} must be either an project imported by the
11850 current project, or the project that the current project extends. If the
11851 attribute is in a package (in this case, in package @code{Builder}), the same
11852 package needs to be specified.
11854 @noindent
11855 A full associative array declaration replaces any other declaration for the
11856 attribute, including other full associative array declaration. Single
11857 associative array associations may be declare after a full associative
11858 declaration, modifying the value for a single association of the attribute.
11860 @node case Constructions
11861 @subsection @code{case} Constructions
11863 @noindent
11864 A @code{case} construction is used in a project file to effect conditional
11865 behavior.
11866 Here is a typical example:
11868 @smallexample @c projectfile
11869 @group
11870 project MyProj is
11871    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11873    OS : OS_Type := external ("OS", "GNU/Linux");
11874 @end group
11876 @group
11877    package Compiler is
11878      case OS is
11879        when "GNU/Linux" | "Unix" =>
11880          for ^Default_Switches^Default_Switches^ ("Ada")
11881              use ("^-gnath^-gnath^");
11882        when "NT" =>
11883          for ^Default_Switches^Default_Switches^ ("Ada")
11884              use ("^-gnatP^-gnatP^");
11885        when others =>
11886      end case;
11887    end Compiler;
11888 end MyProj;
11889 @end group
11890 @end smallexample
11892 @noindent
11893 The syntax of a @code{case} construction is based on the Ada case statement
11894 (although there is no @code{null} construction for empty alternatives).
11896 The case expression must a typed string variable.
11897 Each alternative comprises the reserved word @code{when}, either a list of
11898 literal strings separated by the @code{"|"} character or the reserved word
11899 @code{others},  and the @code{"=>"} token.
11900 Each literal string must belong to the string type that is the type of the
11901 case variable.
11902 An @code{others} alternative, if present, must occur last.
11904 After each @code{=>}, there are zero or more constructions.  The only
11905 constructions allowed in a case construction are other case constructions and
11906 attribute declarations. String type declarations, variable declarations and
11907 package declarations are not allowed.
11909 The value of the case variable is often given by an external reference
11910 (@pxref{External References in Project Files}).
11912 @c ****************************************
11913 @c * Objects and Sources in Project Files *
11914 @c ****************************************
11916 @node Objects and Sources in Project Files
11917 @section Objects and Sources in Project Files
11919 @menu
11920 * Object Directory::
11921 * Exec Directory::
11922 * Source Directories::
11923 * Source File Names::
11924 @end menu
11926 @noindent
11927 Each project has exactly one object directory and one or more source
11928 directories. The source directories must contain at least one source file,
11929 unless  the project file explicitly specifies that no source files are present
11930 (@pxref{Source File Names}).
11932 @node Object Directory
11933 @subsection Object Directory
11935 @noindent
11936 The object directory for a project is the directory containing the compiler's
11937 output (such as @file{ALI} files and object files) for the project's immediate
11938 sources.
11940 The object directory is given by the value of the attribute @code{Object_Dir}
11941 in the project file.
11943 @smallexample @c projectfile
11944    for Object_Dir use "objects";
11945 @end smallexample
11947 @noindent
11948 The attribute @var{Object_Dir} has a string value, the path name of the object
11949 directory. The path name may be absolute or relative to the directory of the
11950 project file. This directory must already exist, and be readable and writable.
11952 By default, when the attribute @code{Object_Dir} is not given an explicit value
11953 or when its value is the empty string, the object directory is the same as the
11954 directory containing the project file.
11956 @node Exec Directory
11957 @subsection Exec Directory
11959 @noindent
11960 The exec directory for a project is the directory containing the executables
11961 for the project's main subprograms.
11963 The exec directory is given by the value of the attribute @code{Exec_Dir}
11964 in the project file.
11966 @smallexample @c projectfile
11967    for Exec_Dir use "executables";
11968 @end smallexample
11970 @noindent
11971 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11972 directory. The path name may be absolute or relative to the directory of the
11973 project file. This directory must already exist, and be writable.
11975 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11976 or when its value is the empty string, the exec directory is the same as the
11977 object directory of the project file.
11979 @node Source Directories
11980 @subsection Source Directories
11982 @noindent
11983 The source directories of a project are specified by the project file
11984 attribute @code{Source_Dirs}.
11986 This attribute's value is a string list. If the attribute is not given an
11987 explicit value, then there is only one source directory, the one where the
11988 project file resides.
11990 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11991 as in
11993 @smallexample @c projectfile
11994     for Source_Dirs use ();
11995 @end smallexample
11997 @noindent
11998 indicates that the project contains no source files.
12000 Otherwise, each string in the string list designates one or more
12001 source directories.
12003 @smallexample @c projectfile
12004    for Source_Dirs use ("sources", "test/drivers");
12005 @end smallexample
12007 @noindent
12008 If a string in the list ends with @code{"/**"},  then the directory whose path
12009 name precedes the two asterisks, as well as all its subdirectories
12010 (recursively), are source directories.
12012 @smallexample @c projectfile
12013    for Source_Dirs use ("/system/sources/**");
12014 @end smallexample
12016 @noindent
12017 Here the directory @code{/system/sources} and all of its subdirectories
12018 (recursively) are source directories.
12020 To specify that the source directories are the directory of the project file
12021 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12022 @smallexample @c projectfile
12023    for Source_Dirs use ("./**");
12024 @end smallexample
12026 @noindent
12027 Each of the source directories must exist and be readable.
12029 @node Source File Names
12030 @subsection Source File Names
12032 @noindent
12033 In a project that contains source files, their names may be specified by the
12034 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12035 (a string). Source file names never include any directory information.
12037 If the attribute @code{Source_Files} is given an explicit value, then each
12038 element of the list is a source file name.
12040 @smallexample @c projectfile
12041    for Source_Files use ("main.adb");
12042    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12043 @end smallexample
12045 @noindent
12046 If the attribute @code{Source_Files} is not given an explicit value,
12047 but the attribute @code{Source_List_File} is given a string value,
12048 then the source file names are contained in the text file whose path name
12049 (absolute or relative to the directory of the project file) is the
12050 value of the attribute @code{Source_List_File}.
12052 Each line in the file that is not empty or is not a comment
12053 contains a source file name.
12055 @smallexample @c projectfile
12056    for Source_List_File use "source_list.txt";
12057 @end smallexample
12059 @noindent
12060 By default, if neither the attribute @code{Source_Files} nor the attribute
12061 @code{Source_List_File} is given an explicit value, then each file in the
12062 source directories that conforms to the project's naming scheme
12063 (@pxref{Naming Schemes}) is an immediate source of the project.
12065 A warning is issued if both attributes @code{Source_Files} and
12066 @code{Source_List_File} are given explicit values. In this case, the attribute
12067 @code{Source_Files} prevails.
12069 Each source file name must be the name of one existing source file
12070 in one of the source directories.
12072 A @code{Source_Files} attribute whose value is an empty list
12073 indicates that there are no source files in the project.
12075 If the order of the source directories is known statically, that is if
12076 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12077 be several files with the same source file name. In this case, only the file
12078 in the first directory is considered as an immediate source of the project
12079 file. If the order of the source directories is not known statically, it is
12080 an error to have several files with the same source file name.
12082 Projects can be specified to have no Ada source
12083 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12084 list, or the @code{"Ada"} may be absent from @code{Languages}:
12086 @smallexample @c projectfile
12087    for Source_Dirs use ();
12088    for Source_Files use ();
12089    for Languages use ("C", "C++");
12090 @end smallexample
12092 @noindent
12093 Otherwise, a project must contain at least one immediate source.
12095 Projects with no source files are useful as template packages
12096 (@pxref{Packages in Project Files}) for other projects; in particular to
12097 define a package @code{Naming} (@pxref{Naming Schemes}).
12099 @c ****************************
12100 @c * Importing Projects *
12101 @c ****************************
12103 @node  Importing Projects
12104 @section Importing Projects
12105 @cindex @code{ADA_PROJECT_PATH}
12107 @noindent
12108 An immediate source of a project P may depend on source files that
12109 are neither immediate sources of P nor in the predefined library.
12110 To get this effect, P must @emph{import} the projects that contain the needed
12111 source files.
12113 @smallexample @c projectfile
12114 @group
12115   with "project1", "utilities.gpr";
12116   with "/namings/apex.gpr";
12117   project Main is
12118     ...
12119 @end group
12120 @end smallexample
12122 @noindent
12123 As can be seen in this example, the syntax for importing projects is similar
12124 to the syntax for importing compilation units in Ada. However, project files
12125 use literal strings instead of names, and the @code{with} clause identifies
12126 project files rather than packages.
12128 Each literal string is the file name or path name (absolute or relative) of a
12129 project file. If a string corresponds to a file name, with no path or a
12130 relative path, then its location is determined by the @emph{project path}. The
12131 latter can be queried using @code{gnatls -v}. It contains:
12133 @itemize @bullet
12134 @item
12135 In first position, the directory containing the current project file.
12136 @item
12137 In last position, the default project directory. This default project directory
12138 is part of the GNAT installation and is the standard place to install project
12139 files giving access to standard support libraries.
12140 @ifclear vms
12141 @ref{Installing a library}
12142 @end ifclear
12144 @item
12145 In between, all the directories referenced in the
12146 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12147 @end itemize
12149 @noindent
12150 If a relative pathname is used, as in
12152 @smallexample @c projectfile
12153   with "tests/proj";
12154 @end smallexample
12156 @noindent
12157 then the full path for the project is constructed by concatenating this
12158 relative path to those in the project path, in order, until a matching file is
12159 found. Any symbolic link will be fully resolved in the directory of the
12160 importing project file before the imported project file is examined.
12162 If the @code{with}'ed project file name does not have an extension,
12163 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12164 then the file name as specified in the @code{with} clause (no extension) will
12165 be used. In the above example, if a file @code{project1.gpr} is found, then it
12166 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12167 then it will be used; if neither file exists, this is an error.
12169 A warning is issued if the name of the project file does not match the
12170 name of the project; this check is case insensitive.
12172 Any source file that is an immediate source of the imported project can be
12173 used by the immediate sources of the importing project, transitively. Thus
12174 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12175 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12176 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12177 because if and when @code{B} ceases to import @code{C}, some sources in
12178 @code{A} will no longer compile.
12180 A side effect of this capability is that normally cyclic dependencies are not
12181 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12182 is not allowed to import @code{A}. However, there are cases when cyclic
12183 dependencies would be beneficial. For these cases, another form of import
12184 between projects exists, the @code{limited with}: a project @code{A} that
12185 imports a project @code{B} with a straigh @code{with} may also be imported,
12186 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12187 to @code{A} include at least one @code{limited with}.
12189 @smallexample @c 0projectfile
12190 with "../b/b.gpr";
12191 with "../c/c.gpr";
12192 project A is
12193 end A;
12195 limited with "../a/a.gpr";
12196 project B is
12197 end B;
12199 with "../d/d.gpr";
12200 project C is
12201 end C;
12203 limited with "../a/a.gpr";
12204 project D is
12205 end D;
12206 @end smallexample
12208 @noindent
12209 In the above legal example, there are two project cycles:
12210 @itemize @bullet
12211 @item A-> B-> A
12212 @item A -> C -> D -> A
12213 @end itemize
12215 @noindent
12216 In each of these cycle there is one @code{limited with}: import of @code{A}
12217 from @code{B} and import of @code{A} from @code{D}.
12219 The difference between straight @code{with} and @code{limited with} is that
12220 the name of a project imported with a @code{limited with} cannot be used in the
12221 project that imports it. In particular, its packages cannot be renamed and
12222 its variables cannot be referred to.
12224 An exception to the above rules for @code{limited with} is that for the main
12225 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12226 @code{limited with} is equivalent to a straight @code{with}. For example,
12227 in the example above, projects @code{B} and @code{D} could not be main
12228 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12229 each have a @code{limited with} that is the only one in a cycle of importing
12230 projects.
12232 @c *********************
12233 @c * Project Extension *
12234 @c *********************
12236 @node Project Extension
12237 @section Project Extension
12239 @noindent
12240 During development of a large system, it is sometimes necessary to use
12241 modified versions of some of the source files, without changing the original
12242 sources. This can be achieved through the @emph{project extension} facility.
12244 @smallexample @c projectfile
12245    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12246 @end smallexample
12248 @noindent
12249 A project extension declaration introduces an extending project
12250 (the @emph{child}) and a project being extended (the @emph{parent}).
12252 By default, a child project inherits all the sources of its parent.
12253 However, inherited sources can be overridden: a unit in a parent is hidden
12254 by a unit of the same name in the child.
12256 Inherited sources are considered to be sources (but not immediate sources)
12257 of the child project; see @ref{Project File Syntax}.
12259 An inherited source file retains any switches specified in the parent project.
12261 For example if the project @code{Utilities} contains the specification and the
12262 body of an Ada package @code{Util_IO}, then the project
12263 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12264 The original body of @code{Util_IO} will not be considered in program builds.
12265 However, the package specification will still be found in the project
12266 @code{Utilities}.
12268 A child project can have only one parent but it may import any number of other
12269 projects.
12271 A project is not allowed to import directly or indirectly at the same time a
12272 child project and any of its ancestors.
12274 @c *******************************
12275 @c * Project Hierarchy Extension *
12276 @c *******************************
12278 @node Project Hierarchy Extension
12279 @section Project Hierarchy Extension
12281 @noindent
12282 When extending a large system spanning multiple projects, it is often
12283 inconvenient to extend every project in the hierarchy that is impacted by a
12284 small change introduced. In such cases, it is possible to create a virtual
12285 extension of entire hierarchy using @code{extends all} relationship.
12287 When the project is extended using @code{extends all} inheritance, all projects
12288 that are imported by it, both directly and indirectly, are considered virtually
12289 extended. That is, the Project Manager creates "virtual projects"
12290 that extend every project in the hierarchy; all these virtual projects have
12291 no sources of their own and have as object directory the object directory of
12292 the root of "extending all" project.
12294 It is possible to explicitly extend one or more projects in the hierarchy
12295 in order to modify the sources. These extending projects must be imported by
12296 the "extending all" project, which will replace the corresponding virtual
12297 projects with the explicit ones.
12299 When building such a project hierarchy extension, the Project Manager will
12300 ensure that both modified sources and sources in virtual extending projects
12301 that depend on them, are recompiled.
12303 By means of example, consider the following hierarchy of projects.
12305 @enumerate
12306 @item
12307 project A, containing package P1
12308 @item
12309 project B importing A and containing package P2 which depends on P1
12310 @item
12311 project C importing B and containing package P3 which depends on P2
12312 @end enumerate
12314 @noindent
12315 We want to modify packages P1 and P3.
12317 This project hierarchy will need to be extended as follows:
12319 @enumerate
12320 @item
12321 Create project A1 that extends A, placing modified P1 there:
12323 @smallexample @c 0projectfile
12324 project A1 extends "(...)/A" is
12325 end A1;
12326 @end smallexample
12328 @item
12329 Create project C1 that "extends all" C and imports A1, placing modified
12330 P3 there:
12332 @smallexample @c 0projectfile
12333 with "(...)/A1";
12334 project C1 extends all "(...)/C" is
12335 end C1;
12336 @end smallexample
12337 @end enumerate
12339 When you build project C1, your entire modified project space will be
12340 recompiled, including the virtual project B1 that has been impacted by the
12341 "extending all" inheritance of project C.
12343 Note that if a Library Project in the hierarchy is virtually extended,
12344 the virtual project that extends the Library Project is not a Library Project.
12346 @c ****************************************
12347 @c * External References in Project Files *
12348 @c ****************************************
12350 @node  External References in Project Files
12351 @section External References in Project Files
12353 @noindent
12354 A project file may contain references to external variables; such references
12355 are called @emph{external references}.
12357 An external variable is either defined as part of the environment (an
12358 environment variable in Unix, for example) or else specified on the command
12359 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12360 If both, then the command line value is used.
12362 The value of an external reference is obtained by means of the built-in
12363 function @code{external}, which returns a string value.
12364 This function has two forms:
12365 @itemize @bullet
12366 @item @code{external (external_variable_name)}
12367 @item @code{external (external_variable_name, default_value)}
12368 @end itemize
12370 @noindent
12371 Each parameter must be a string literal.  For example:
12373 @smallexample @c projectfile
12374    external ("USER")
12375    external ("OS", "GNU/Linux")
12376 @end smallexample
12378 @noindent
12379 In the form with one parameter, the function returns the value of
12380 the external variable given as parameter. If this name is not present in the
12381 environment, the function returns an empty string.
12383 In the form with two string parameters, the second argument is
12384 the value returned when the variable given as the first argument is not
12385 present in the environment. In the example above, if @code{"OS"} is not
12386 the name of ^an environment variable^a logical name^ and is not passed on
12387 the command line, then the returned value is @code{"GNU/Linux"}.
12389 An external reference may be part of a string expression or of a string
12390 list expression, and can therefore appear in a variable declaration or
12391 an attribute declaration.
12393 @smallexample @c projectfile
12394 @group
12395    type Mode_Type is ("Debug", "Release");
12396    Mode : Mode_Type := external ("MODE");
12397    case Mode is
12398      when "Debug" =>
12399         ...
12400 @end group
12401 @end smallexample
12403 @c *****************************
12404 @c * Packages in Project Files *
12405 @c *****************************
12407 @node  Packages in Project Files
12408 @section Packages in Project Files
12410 @noindent
12411 A @emph{package} defines the settings for project-aware tools within a
12412 project.
12413 For each such tool one can declare a package; the names for these
12414 packages are preset (@pxref{Packages}).
12415 A package may contain variable declarations, attribute declarations, and case
12416 constructions.
12418 @smallexample @c projectfile
12419 @group
12420    project Proj is
12421       package Builder is  -- used by gnatmake
12422          for ^Default_Switches^Default_Switches^ ("Ada")
12423              use ("^-v^-v^",
12424                   "^-g^-g^");
12425       end Builder;
12426    end Proj;
12427 @end group
12428 @end smallexample
12430 @noindent
12431 The syntax of package declarations mimics that of package in Ada.
12433 Most of the packages have an attribute
12434 @code{^Default_Switches^Default_Switches^}.
12435 This attribute is an associative array, and its value is a string list.
12436 The index of the associative array is the name of a programming language (case
12437 insensitive). This attribute indicates the ^switch^switch^
12438 or ^switches^switches^ to be used
12439 with the corresponding tool.
12441 Some packages also have another attribute, @code{^Switches^Switches^},
12442 an associative array whose value is a string list.
12443 The index is the name of a source file.
12444 This attribute indicates the ^switch^switch^
12445 or ^switches^switches^ to be used by the corresponding
12446 tool when dealing with this specific file.
12448 Further information on these ^switch^switch^-related attributes is found in
12449 @ref{^Switches^Switches^ and Project Files}.
12451 A package may be declared as a @emph{renaming} of another package; e.g., from
12452 the project file for an imported project.
12454 @smallexample @c projectfile
12455 @group
12456   with "/global/apex.gpr";
12457   project Example is
12458     package Naming renames Apex.Naming;
12459     ...
12460   end Example;
12461 @end group
12462 @end smallexample
12464 @noindent
12465 Packages that are renamed in other project files often come from project files
12466 that have no sources: they are just used as templates. Any modification in the
12467 template will be reflected automatically in all the project files that rename
12468 a package from the template.
12470 In addition to the tool-oriented packages, you can also declare a package
12471 named @code{Naming} to establish specialized source file naming conventions
12472 (@pxref{Naming Schemes}).
12474 @c ************************************
12475 @c * Variables from Imported Projects *
12476 @c ************************************
12478 @node Variables from Imported Projects
12479 @section Variables from Imported Projects
12481 @noindent
12482 An attribute or variable defined in an imported or parent project can
12483 be used in expressions in the importing / extending project.
12484 Such an attribute or variable is denoted by an expanded name whose prefix
12485 is either the name of the project or the expanded name of a package within
12486 a project.
12488 @smallexample @c projectfile
12489 @group
12490   with "imported";
12491   project Main extends "base" is
12492      Var1 := Imported.Var;
12493      Var2 := Base.Var & ".new";
12494 @end group
12496 @group
12497      package Builder is
12498         for ^Default_Switches^Default_Switches^ ("Ada")
12499             use Imported.Builder.Ada_^Switches^Switches^ &
12500                 "^-gnatg^-gnatg^" &
12501                 "^-v^-v^";
12502      end Builder;
12503 @end group
12505 @group
12506      package Compiler is
12507         for ^Default_Switches^Default_Switches^ ("Ada")
12508             use Base.Compiler.Ada_^Switches^Switches^;
12509      end Compiler;
12510   end Main;
12511 @end group
12512 @end smallexample
12514 @noindent
12515 In this example:
12517 @itemize @bullet
12518 @item
12519 The value of @code{Var1} is a copy of the variable @code{Var} defined
12520 in the project file @file{"imported.gpr"}
12521 @item
12522 the value of @code{Var2} is a copy of the value of variable @code{Var}
12523 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12524 @item
12525 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12526 @code{Builder} is a string list that includes in its value a copy of the value
12527 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12528 in project file @file{imported.gpr} plus two new elements:
12529 @option{"^-gnatg^-gnatg^"}
12530 and @option{"^-v^-v^"};
12531 @item
12532 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12533 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12534 defined in the @code{Compiler} package in project file @file{base.gpr},
12535 the project being extended.
12536 @end itemize
12538 @c ******************
12539 @c * Naming Schemes *
12540 @c ******************
12542 @node  Naming Schemes
12543 @section Naming Schemes
12545 @noindent
12546 Sometimes an Ada software system is ported from a foreign compilation
12547 environment to GNAT, and the file names do not use the default GNAT
12548 conventions. Instead of changing all the file names (which for a variety
12549 of reasons might not be possible), you can define the relevant file
12550 naming scheme in the @code{Naming} package in your project file.
12552 @noindent
12553 Note that the use of pragmas described in
12554 @ref{Alternative File Naming Schemes} by mean of a configuration
12555 pragmas file is not supported when using project files. You must use
12556 the features described in this paragraph. You can however use specify
12557 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12559 @ifclear vms
12560 For example, the following
12561 package models the Apex file naming rules:
12563 @smallexample @c projectfile
12564 @group
12565   package Naming is
12566     for Casing               use "lowercase";
12567     for Dot_Replacement      use ".";
12568     for Spec_Suffix ("Ada")  use ".1.ada";
12569     for Body_Suffix ("Ada")  use ".2.ada";
12570   end Naming;
12571 @end group
12572 @end smallexample
12573 @end ifclear
12575 @ifset vms
12576 For example, the following package models the HP Ada file naming rules:
12578 @smallexample @c projectfile
12579 @group
12580   package Naming is
12581     for Casing               use "lowercase";
12582     for Dot_Replacement      use "__";
12583     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12584     for Body_Suffix ("Ada")  use ".^ada^ada^";
12585   end Naming;
12586 @end group
12587 @end smallexample
12589 @noindent
12590 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12591 names in lower case)
12592 @end ifset
12594 @noindent
12595 You can define the following attributes in package @code{Naming}:
12597 @table @code
12599 @item @var{Casing}
12600 This must be a string with one of the three values @code{"lowercase"},
12601 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12603 @noindent
12604 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12606 @item @var{Dot_Replacement}
12607 This must be a string whose value satisfies the following conditions:
12609 @itemize @bullet
12610 @item It must not be empty
12611 @item It cannot start or end with an alphanumeric character
12612 @item It cannot be a single underscore
12613 @item It cannot start with an underscore followed by an alphanumeric
12614 @item It cannot contain a dot @code{'.'} except if the entire string
12615 is @code{"."}
12616 @end itemize
12618 @noindent
12619 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12621 @item @var{Spec_Suffix}
12622 This is an associative array (indexed by the programming language name, case
12623 insensitive) whose value is a string that must satisfy the following
12624 conditions:
12626 @itemize @bullet
12627 @item It must not be empty
12628 @item It must include at least one dot
12629 @end itemize
12630 @noindent
12631 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12632 @code{"^.ads^.ADS^"}.
12634 @item @var{Body_Suffix}
12635 This is an associative array (indexed by the programming language name, case
12636 insensitive) whose value is a string that must satisfy the following
12637 conditions:
12639 @itemize @bullet
12640 @item It must not be empty
12641 @item It must include at least one dot
12642 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12643 @end itemize
12644 @noindent
12645 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12646 @code{"^.adb^.ADB^"}.
12648 @item @var{Separate_Suffix}
12649 This must be a string whose value satisfies the same conditions as
12650 @code{Body_Suffix}.
12652 @noindent
12653 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12654 value as @code{Body_Suffix ("Ada")}.
12656 @item @var{Spec}
12657 @noindent
12658 You can use the associative array attribute @code{Spec}  to define
12659 the source file name for an individual Ada compilation unit's spec. The array
12660 index must be a string literal that identifies the Ada unit (case insensitive).
12661 The value of this attribute must be a string that identifies the file that
12662 contains this unit's spec (case sensitive or insensitive depending on the
12663 operating system).
12665 @smallexample @c projectfile
12666    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12667 @end smallexample
12669 @item @var{Body}
12671 You can use the associative array attribute @code{Body} to
12672 define the source file name for an individual Ada compilation unit's body
12673 (possibly a subunit).  The array index must be a string literal that identifies
12674 the Ada unit (case insensitive).  The value of this attribute must be a string
12675 that identifies the file that contains this unit's body or subunit (case
12676 sensitive or insensitive depending on the operating system).
12678 @smallexample @c projectfile
12679    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12680 @end smallexample
12681 @end table
12683 @c ********************
12684 @c * Library Projects *
12685 @c ********************
12687 @node Library Projects
12688 @section Library Projects
12690 @noindent
12691 @emph{Library projects} are projects whose object code is placed in a library.
12692 (Note that this facility is not yet supported on all platforms)
12694 To create a library project, you need to define in its project file
12695 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12696 Additionally, you may define other library-related attributes such as
12697 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12698 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12700 The @code{Library_Name} attribute has a string value. There is no restriction
12701 on the name of a library. It is the responsibility of the developer to
12702 choose a name that will be accepted by the platform. It is recommended to
12703 choose names that could be Ada identifiers; such names are almost guaranteed
12704 to be acceptable on all platforms.
12706 The @code{Library_Dir} attribute has a string value that designates the path
12707 (absolute or relative) of the directory where the library will reside.
12708 It must designate an existing directory, and this directory must be writable,
12709 different from the project's object directory and from any source directory
12710 in the project tree.
12712 If both @code{Library_Name} and @code{Library_Dir} are specified and
12713 are legal, then the project file defines a library project.  The optional
12714 library-related attributes are checked only for such project files.
12716 The @code{Library_Kind} attribute has a string value that must be one of the
12717 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12718 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12719 attribute is not specified, the library is a static library, that is
12720 an archive of object files that can be potentially linked into an
12721 static executable. Otherwise, the library may be dynamic or
12722 relocatable, that is a library that is loaded only at the start of execution.
12724 If you need to build both a static and a dynamic library, you should use two
12725 different object directories, since in some cases some extra code needs to
12726 be generated for the latter. For such cases, it is recommended to either use
12727 two different project files, or a single one which uses external variables
12728 to indicate what kind of library should be build.
12730 The @code{Library_ALI_Dir} attribute may be specified to indicate the
12731 directory where the ALI files of the libriry will be copied. When it is
12732 not specified, the ALI files are copied ti the directory specified in
12733 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
12734 must be writable and different from the project's object directory and from
12735 any source directory in the project tree.
12737 The @code{Library_Version} attribute has a string value whose interpretation
12738 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12739 used only for dynamic/relocatable libraries as the internal name of the
12740 library (the @code{"soname"}). If the library file name (built from the
12741 @code{Library_Name}) is different from the @code{Library_Version}, then the
12742 library file will be a symbolic link to the actual file whose name will be
12743 @code{Library_Version}.
12745 Example (on Unix):
12747 @smallexample @c projectfile
12748 @group
12749 project Plib is
12751    Version := "1";
12753    for Library_Dir use "lib_dir";
12754    for Library_Name use "dummy";
12755    for Library_Kind use "relocatable";
12756    for Library_Version use "libdummy.so." & Version;
12758 end Plib;
12759 @end group
12760 @end smallexample
12762 @noindent
12763 Directory @file{lib_dir} will contain the internal library file whose name
12764 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12765 @file{libdummy.so.1}.
12767 When @command{gnatmake} detects that a project file
12768 is a library project file, it will check all immediate sources of the project
12769 and rebuild the library if any of the sources have been recompiled.
12771 Standard project files can import library project files. In such cases,
12772 the libraries will only be rebuild if some of its sources are recompiled
12773 because they are in the closure of some other source in an importing project.
12774 Sources of the library project files that are not in such a closure will
12775 not be checked, unless the full library is checked, because one of its sources
12776 needs to be recompiled.
12778 For instance, assume the project file @code{A} imports the library project file
12779 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12780 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12781 @file{l2.ads}, @file{l2.adb}.
12783 If @file{l1.adb} has been modified, then the library associated with @code{L}
12784 will be rebuild when compiling all the immediate sources of @code{A} only
12785 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12786 @code{"with L1;"}.
12788 To be sure that all the sources in the library associated with @code{L} are
12789 up to date, and that all the sources of project @code{A} are also up to date,
12790 the following two commands needs to be used:
12792 @smallexample
12793 gnatmake -Pl.gpr
12794 gnatmake -Pa.gpr
12795 @end smallexample
12797 When a library is built or rebuilt, an attempt is made first to delete all
12798 files in the library directory.
12799 All @file{ALI} files will also be copied from the object directory to the
12800 library directory. To build executables, @command{gnatmake} will use the
12801 library rather than the individual object files.
12803 @ifclear vms
12804 It is also possible to create library project files for third-party libraries
12805 that are precompiled and cannot be compiled locally thanks to the
12806 @code{externally_built} attribute. (See @ref{Installing a library}).
12807 @end ifclear
12809 @c *******************************
12810 @c * Stand-alone Library Projects *
12811 @c *******************************
12813 @node Stand-alone Library Projects
12814 @section Stand-alone Library Projects
12816 @noindent
12817 A Stand-alone Library is a library that contains the necessary code to
12818 elaborate the Ada units that are included in the library. A Stand-alone
12819 Library is suitable to be used in an executable when the main is not
12820 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12821 subprogram.
12823 A Stand-alone Library Project is a Library Project where the library is
12824 a Stand-alone Library.
12826 To be a Stand-alone Library Project, in addition to the two attributes
12827 that make a project a Library Project (@code{Library_Name} and
12828 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12829 @code{Library_Interface} must be defined.
12831 @smallexample @c projectfile
12832 @group
12833    for Library_Dir use "lib_dir";
12834    for Library_Name use "dummy";
12835    for Library_Interface use ("int1", "int1.child");
12836 @end group
12837 @end smallexample
12839 Attribute @code{Library_Interface} has a non empty string list value,
12840 each string in the list designating a unit contained in an immediate source
12841 of the project file.
12843 When a Stand-alone Library is built, first the binder is invoked to build
12844 a package whose name depends on the library name
12845 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12846 This binder-generated package includes initialization and
12847 finalization procedures whose
12848 names depend on the library name (dummyinit and dummyfinal in the example
12849 above). The object corresponding to this package is included in the library.
12851 A dynamic or relocatable Stand-alone Library is automatically initialized
12852 if automatic initialization of Stand-alone Libraries is supported on the
12853 platform and if attribute @code{Library_Auto_Init} is not specified or
12854 is specified with the value "true". A static Stand-alone Library is never
12855 automatically initialized.
12857 Single string attribute @code{Library_Auto_Init} may be specified with only
12858 two possible values: "false" or "true" (case-insensitive). Specifying
12859 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12860 initialization of dynamic or relocatable libraries.
12862 When a non automatically initialized Stand-alone Library is used
12863 in an executable, its initialization procedure must be called before
12864 any service of the library is used.
12865 When the main subprogram is in Ada, it may mean that the initialization
12866 procedure has to be called during elaboration of another package.
12868 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12869 (those that are listed in attribute @code{Library_Interface}) are copied to
12870 the Library Directory. As a consequence, only the Interface Units may be
12871 imported from Ada units outside of the library. If other units are imported,
12872 the binding phase will fail.
12874 When a Stand-Alone Library is bound, the switches that are specified in
12875 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12876 used in the call to @command{gnatbind}.
12878 The string list attribute @code{Library_Options} may be used to specified
12879 additional switches to the call to @command{gcc} to link the library.
12881 The attribute @code{Library_Src_Dir}, may be specified for a
12882 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12883 single string value. Its value must be the path (absolute or relative to the
12884 project directory) of an existing directory. This directory cannot be the
12885 object directory or one of the source directories, but it can be the same as
12886 the library directory. The sources of the Interface
12887 Units of the library, necessary to an Ada client of the library, will be
12888 copied to the designated directory, called Interface Copy directory.
12889 These sources includes the specs of the Interface Units, but they may also
12890 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12891 are used, or when there is a generic units in the spec. Before the sources
12892 are copied to the Interface Copy directory, an attempt is made to delete all
12893 files in the Interface Copy directory.
12895 @c *************************************
12896 @c * Switches Related to Project Files *
12897 @c *************************************
12898 @node Switches Related to Project Files
12899 @section Switches Related to Project Files
12901 @noindent
12902 The following switches are used by GNAT tools that support project files:
12904 @table @option
12906 @item ^-P^/PROJECT_FILE=^@var{project}
12907 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12908 Indicates the name of a project file. This project file will be parsed with
12909 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12910 if any, and using the external references indicated
12911 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12912 @ifclear vms
12913 There may zero, one or more spaces between @option{-P} and @var{project}.
12914 @end ifclear
12916 @noindent
12917 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12919 @noindent
12920 Since the Project Manager parses the project file only after all the switches
12921 on the command line are checked, the order of the switches
12922 @option{^-P^/PROJECT_FILE^},
12923 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12924 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12926 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12927 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12928 Indicates that external variable @var{name} has the value @var{value}.
12929 The Project Manager will use this value for occurrences of
12930 @code{external(name)} when parsing the project file.
12932 @ifclear vms
12933 @noindent
12934 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12935 put between quotes.
12936 @smallexample
12937   -XOS=NT
12938   -X"user=John Doe"
12939 @end smallexample
12940 @end ifclear
12942 @noindent
12943 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12944 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12945 @var{name}, only the last one is used.
12947 @noindent
12948 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12949 takes precedence over the value of the same name in the environment.
12951 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12952 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12953 @c Previous line uses code vs option command, to stay less than 80 chars
12954 Indicates the verbosity of the parsing of GNAT project files.
12956 @ifclear vms
12957 @option{-vP0} means Default;
12958 @option{-vP1} means Medium;
12959 @option{-vP2} means High.
12960 @end ifclear
12962 @ifset vms
12963 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12964 HIGH.
12965 @end ifset
12967 @noindent
12968 The default is ^Default^DEFAULT^: no output for syntactically correct
12969 project files.
12970 @noindent
12971 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12972 only the last one is used.
12974 @end table
12976 @c **********************************
12977 @c * Tools Supporting Project Files *
12978 @c **********************************
12980 @node  Tools Supporting Project Files
12981 @section Tools Supporting Project Files
12983 @menu
12984 * gnatmake and Project Files::
12985 * The GNAT Driver and Project Files::
12986 @ifclear vms
12987 * Glide and Project Files::
12988 @end ifclear
12989 @end menu
12991 @node gnatmake and Project Files
12992 @subsection gnatmake and Project Files
12994 @noindent
12995 This section covers several topics related to @command{gnatmake} and
12996 project files: defining ^switches^switches^ for @command{gnatmake}
12997 and for the tools that it invokes; specifying configuration pragmas;
12998 the use of the @code{Main} attribute; building and rebuilding library project
12999 files.
13001 @menu
13002 * ^Switches^Switches^ and Project Files::
13003 * Specifying Configuration Pragmas::
13004 * Project Files and Main Subprograms::
13005 * Library Project Files::
13006 @end menu
13008 @node ^Switches^Switches^ and Project Files
13009 @subsubsection ^Switches^Switches^ and Project Files
13011 @ifset vms
13012 It is not currently possible to specify VMS style qualifiers in the project
13013 files; only Unix style ^switches^switches^ may be specified.
13014 @end ifset
13016 @noindent
13017 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13018 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13019 attribute, a @code{^Switches^Switches^} attribute, or both;
13020 as their names imply, these ^switch^switch^-related
13021 attributes affect the ^switches^switches^ that are used for each of these GNAT
13022 components when
13023 @command{gnatmake} is invoked.  As will be explained below, these
13024 component-specific ^switches^switches^ precede
13025 the ^switches^switches^ provided on the @command{gnatmake} command line.
13027 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13028 array indexed by language name (case insensitive) whose value is a string list.
13029 For example:
13031 @smallexample @c projectfile
13032 @group
13033 package Compiler is
13034   for ^Default_Switches^Default_Switches^ ("Ada")
13035       use ("^-gnaty^-gnaty^",
13036            "^-v^-v^");
13037 end Compiler;
13038 @end group
13039 @end smallexample
13041 @noindent
13042 The @code{^Switches^Switches^} attribute is also an associative array,
13043 indexed by a file name (which may or may not be case sensitive, depending
13044 on the operating system) whose value is a string list.  For example:
13046 @smallexample @c projectfile
13047 @group
13048 package Builder is
13049    for ^Switches^Switches^ ("main1.adb")
13050        use ("^-O2^-O2^");
13051    for ^Switches^Switches^ ("main2.adb")
13052        use ("^-g^-g^");
13053 end Builder;
13054 @end group
13055 @end smallexample
13057 @noindent
13058 For the @code{Builder} package, the file names must designate source files
13059 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
13060 file names must designate @file{ALI} or source files for main subprograms.
13061 In each case just the file name without an explicit extension is acceptable.
13063 For each tool used in a program build (@command{gnatmake}, the compiler, the
13064 binder, and the linker), the corresponding package @dfn{contributes} a set of
13065 ^switches^switches^ for each file on which the tool is invoked, based on the
13066 ^switch^switch^-related attributes defined in the package.
13067 In particular, the ^switches^switches^
13068 that each of these packages contributes for a given file @var{f} comprise:
13070 @itemize @bullet
13071 @item
13072 the value of attribute @code{^Switches^Switches^ (@var{f})},
13073 if it is specified in the package for the given file,
13074 @item
13075 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13076 if it is specified in the package.
13077 @end itemize
13079 @noindent
13080 If neither of these attributes is defined in the package, then the package does
13081 not contribute any ^switches^switches^ for the given file.
13083 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13084 two sets, in the following order: those contributed for the file
13085 by the @code{Builder} package;
13086 and the switches passed on the command line.
13088 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13089 the ^switches^switches^ passed to the tool comprise three sets,
13090 in the following order:
13092 @enumerate
13093 @item
13094 the applicable ^switches^switches^ contributed for the file
13095 by the @code{Builder} package in the project file supplied on the command line;
13097 @item
13098 those contributed for the file by the package (in the relevant project file --
13099 see below) corresponding to the tool; and
13101 @item
13102 the applicable switches passed on the command line.
13103 @end enumerate
13105 @noindent
13106 The term @emph{applicable ^switches^switches^} reflects the fact that
13107 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13108 tools, depending on the individual ^switch^switch^.
13110 @command{gnatmake} may invoke the compiler on source files from different
13111 projects. The Project Manager will use the appropriate project file to
13112 determine the @code{Compiler} package for each source file being compiled.
13113 Likewise for the @code{Binder} and @code{Linker} packages.
13115 As an example, consider the following package in a project file:
13117 @smallexample @c projectfile
13118 @group
13119 project Proj1 is
13120    package Compiler is
13121       for ^Default_Switches^Default_Switches^ ("Ada")
13122           use ("^-g^-g^");
13123       for ^Switches^Switches^ ("a.adb")
13124           use ("^-O1^-O1^");
13125       for ^Switches^Switches^ ("b.adb")
13126           use ("^-O2^-O2^",
13127                "^-gnaty^-gnaty^");
13128    end Compiler;
13129 end Proj1;
13130 @end group
13131 @end smallexample
13133 @noindent
13134 If @command{gnatmake} is invoked with this project file, and it needs to
13135 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13136 @file{a.adb} will be compiled with the ^switch^switch^
13137 @option{^-O1^-O1^},
13138 @file{b.adb} with ^switches^switches^
13139 @option{^-O2^-O2^}
13140 and @option{^-gnaty^-gnaty^},
13141 and @file{c.adb} with @option{^-g^-g^}.
13143 The following example illustrates the ordering of the ^switches^switches^
13144 contributed by different packages:
13146 @smallexample @c projectfile
13147 @group
13148 project Proj2 is
13149    package Builder is
13150       for ^Switches^Switches^ ("main.adb")
13151           use ("^-g^-g^",
13152                "^-O1^-)1^",
13153                "^-f^-f^");
13154    end Builder;
13155 @end group
13157 @group
13158    package Compiler is
13159       for ^Switches^Switches^ ("main.adb")
13160           use ("^-O2^-O2^");
13161    end Compiler;
13162 end Proj2;
13163 @end group
13164 @end smallexample
13166 @noindent
13167 If you issue the command:
13169 @smallexample
13170     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13171 @end smallexample
13173 @noindent
13174 then the compiler will be invoked on @file{main.adb} with the following
13175 sequence of ^switches^switches^
13177 @smallexample
13178    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13179 @end smallexample
13181 with the last @option{^-O^-O^}
13182 ^switch^switch^ having precedence over the earlier ones;
13183 several other ^switches^switches^
13184 (such as @option{^-c^-c^}) are added implicitly.
13186 The ^switches^switches^
13187 @option{^-g^-g^}
13188 and @option{^-O1^-O1^} are contributed by package
13189 @code{Builder},  @option{^-O2^-O2^} is contributed
13190 by the package @code{Compiler}
13191 and @option{^-O0^-O0^} comes from the command line.
13193 The @option{^-g^-g^}
13194 ^switch^switch^ will also be passed in the invocation of
13195 @command{Gnatlink.}
13197 A final example illustrates switch contributions from packages in different
13198 project files:
13200 @smallexample @c projectfile
13201 @group
13202 project Proj3 is
13203    for Source_Files use ("pack.ads", "pack.adb");
13204    package Compiler is
13205       for ^Default_Switches^Default_Switches^ ("Ada")
13206           use ("^-gnata^-gnata^");
13207    end Compiler;
13208 end Proj3;
13209 @end group
13211 @group
13212 with "Proj3";
13213 project Proj4 is
13214    for Source_Files use ("foo_main.adb", "bar_main.adb");
13215    package Builder is
13216       for ^Switches^Switches^ ("foo_main.adb")
13217           use ("^-s^-s^",
13218                "^-g^-g^");
13219    end Builder;
13220 end Proj4;
13221 @end group
13223 @group
13224 -- Ada source file:
13225 with Pack;
13226 procedure Foo_Main is
13227    ...
13228 end Foo_Main;
13229 @end group
13230 @end smallexample
13232 If the command is
13233 @smallexample
13234 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13235 @end smallexample
13237 @noindent
13238 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13239 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13240 @option{^-gnato^-gnato^} (passed on the command line).
13241 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13242 are @option{^-g^-g^} from @code{Proj4.Builder},
13243 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13244 and @option{^-gnato^-gnato^} from the command line.
13246 @noindent
13247 When using @command{gnatmake} with project files, some ^switches^switches^ or
13248 arguments may be expressed as relative paths. As the working directory where
13249 compilation occurs may change, these relative paths are converted to absolute
13250 paths. For the ^switches^switches^ found in a project file, the relative paths
13251 are relative to the project file directory, for the switches on the command
13252 line, they are relative to the directory where @command{gnatmake} is invoked.
13253 The ^switches^switches^ for which this occurs are:
13254 ^-I^-I^,
13255 ^-A^-A^,
13256 ^-L^-L^,
13257 ^-aO^-aO^,
13258 ^-aL^-aL^,
13259 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13260 ^switch^switch^
13261 ^-o^-o^, object files specified in package @code{Linker} or after
13262 -largs on the command line). The exception to this rule is the ^switch^switch^
13263 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13265 @node Specifying Configuration Pragmas
13266 @subsubsection Specifying Configuration Pragmas
13268 When using @command{gnatmake} with project files, if there exists a file
13269 @file{gnat.adc} that contains configuration pragmas, this file will be
13270 ignored.
13272 Configuration pragmas can be defined by means of the following attributes in
13273 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13274 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13276 Both these attributes are single string attributes. Their values is the path
13277 name of a file containing configuration pragmas. If a path name is relative,
13278 then it is relative to the project directory of the project file where the
13279 attribute is defined.
13281 When compiling a source, the configuration pragmas used are, in order,
13282 those listed in the file designated by attribute
13283 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13284 project file, if it is specified, and those listed in the file designated by
13285 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13286 the project file of the source, if it exists.
13288 @node Project Files and Main Subprograms
13289 @subsubsection Project Files and Main Subprograms
13291 @noindent
13292 When using a project file, you can invoke @command{gnatmake}
13293 with one or several main subprograms, by specifying their source files on the
13294 command line.
13296 @smallexample
13297     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13298 @end smallexample
13300 @noindent
13301 Each of these needs to be a source file of the same project, except
13302 when the switch ^-u^/UNIQUE^ is used.
13304 @noindent
13305 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13306 same project, one of the project in the tree rooted at the project specified
13307 on the command line. The package @code{Builder} of this common project, the
13308 "main project" is the one that is considered by @command{gnatmake}.
13310 @noindent
13311 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13312 imported directly or indirectly by the project specified on the command line.
13313 Note that if such a source file is not part of the project specified on the
13314 command line, the ^switches^switches^ found in package @code{Builder} of the
13315 project specified on the command line, if any, that are transmitted
13316 to the compiler will still be used, not those found in the project file of
13317 the source file.
13319 @noindent
13320 When using a project file, you can also invoke @command{gnatmake} without
13321 explicitly specifying any main, and the effect depends on whether you have
13322 defined the @code{Main} attribute.  This attribute has a string list value,
13323 where each element in the list is the name of a source file (the file
13324 extension is optional) that contains a unit that can be a main subprogram.
13326 If the @code{Main} attribute is defined in a project file as a non-empty
13327 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13328 line, then invoking @command{gnatmake} with this project file but without any
13329 main on the command line is equivalent to invoking @command{gnatmake} with all
13330 the file names in the @code{Main} attribute on the command line.
13332 Example:
13333 @smallexample @c projectfile
13334 @group
13335    project Prj is
13336       for Main use ("main1", "main2", "main3");
13337    end Prj;
13338 @end group
13339 @end smallexample
13341 @noindent
13342 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13343 is equivalent to
13344 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13346 When the project attribute @code{Main} is not specified, or is specified
13347 as an empty string list, or when the switch @option{-u} is used on the command
13348 line, then invoking @command{gnatmake} with no main on the command line will
13349 result in all immediate sources of the project file being checked, and
13350 potentially recompiled. Depending on the presence of the switch @option{-u},
13351 sources from other project files on which the immediate sources of the main
13352 project file depend are also checked and potentially recompiled. In other
13353 words, the @option{-u} switch is applied to all of the immediate sources of the
13354 main project file.
13356 When no main is specified on the command line and attribute @code{Main} exists
13357 and includes several mains, or when several mains are specified on the
13358 command line, the default ^switches^switches^ in package @code{Builder} will
13359 be used for all mains, even if there are specific ^switches^switches^
13360 specified for one or several mains.
13362 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13363 the specific ^switches^switches^ for each main, if they are specified.
13365 @node Library Project Files
13366 @subsubsection Library Project Files
13368 @noindent
13369 When @command{gnatmake} is invoked with a main project file that is a library
13370 project file, it is not allowed to specify one or more mains on the command
13371 line.
13373 @noindent
13374 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13375 ^-l^/ACTION=LINK^ have special meanings.
13377 @itemize @bullet
13378 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13379 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13380 library.
13382 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13383 to @command{gnatmake} that the binder generated file should be compiled
13384 (in the case of a stand-alone library) and that the library should be built.
13386 @end itemize
13388 @node The GNAT Driver and Project Files
13389 @subsection The GNAT Driver and Project Files
13391 @noindent
13392 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13393 are project-aware:
13394 @command{^gnatbind^gnatbind^},
13395 @command{^gnatfind^gnatfind^},
13396 @command{^gnatlink^gnatlink^},
13397 @command{^gnatls^gnatls^},
13398 @command{^gnatelim^gnatelim^},
13399 @command{^gnatpp^gnatpp^},
13400 @command{^gnatmetric^gnatmetric^},
13401 @command{^gnatstub^gnatstub^},
13402 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13403 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13404 They must be invoked through the @command{gnat} driver.
13406 The @command{gnat} driver is a front-end that accepts a number of commands and
13407 call the corresponding tool. It has been designed initially for VMS to convert
13408 VMS style qualifiers to Unix style switches, but it is now available to all
13409 the GNAT supported platforms.
13411 On non VMS platforms, the @command{gnat} driver accepts the following commands
13412 (case insensitive):
13414 @itemize @bullet
13415 @item
13416 BIND to invoke @command{^gnatbind^gnatbind^}
13417 @item
13418 CHOP to invoke @command{^gnatchop^gnatchop^}
13419 @item
13420 CLEAN to invoke @command{^gnatclean^gnatclean^}
13421 @item
13422 COMP or COMPILE to invoke the compiler
13423 @item
13424 ELIM to invoke @command{^gnatelim^gnatelim^}
13425 @item
13426 FIND to invoke @command{^gnatfind^gnatfind^}
13427 @item
13428 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13429 @item
13430 LINK to invoke @command{^gnatlink^gnatlink^}
13431 @item
13432 LS or LIST to invoke @command{^gnatls^gnatls^}
13433 @item
13434 MAKE to invoke @command{^gnatmake^gnatmake^}
13435 @item
13436 NAME to invoke @command{^gnatname^gnatname^}
13437 @item
13438 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13439 @item
13440 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13441 @item
13442 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13443 @item
13444 STUB to invoke @command{^gnatstub^gnatstub^}
13445 @item
13446 XREF to invoke @command{^gnatxref^gnatxref^}
13447 @end itemize
13449 @noindent
13450 (note that the compiler is invoked using the command
13451 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13453 @noindent
13454 On non VMS platforms, between @command{gnat} and the command, two
13455 special switches may be used:
13457 @itemize @bullet
13458 @item
13459 @command{-v} to display the invocation of the tool.
13460 @item
13461 @command{-dn} to prevent the @command{gnat} driver from removing
13462 the temporary files it has created. These temporary files are
13463 configuration files and temporary file list files.
13464 @end itemize
13466 @noindent
13467 The command may be followed by switches and arguments for the invoked
13468 tool.
13470 @smallexample
13471   gnat bind -C main.ali
13472   gnat ls -a main
13473   gnat chop foo.txt
13474 @end smallexample
13476 @noindent
13477 Switches may also be put in text files, one switch per line, and the text
13478 files may be specified with their path name preceded by '@@'.
13480 @smallexample
13481    gnat bind @@args.txt main.ali
13482 @end smallexample
13484 @noindent
13485 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13486 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13487 (@option{^-P^/PROJECT_FILE^},
13488 @option{^-X^/EXTERNAL_REFERENCE^} and
13489 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13490 the switches of the invoking tool.
13492 @noindent
13493 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13494 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13495 the immediate sources of the specified project file.
13497 @noindent
13498 When GNAT METRIC is used with a project file, but with no source
13499 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13500 with all the immediate sources of the specified project file and with
13501 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13502 of the project.
13504 @noindent
13505 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13506 a project file, no source is specified on the command line and
13507 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13508 the underlying tool (^gnatpp^gnatpp^ or
13509 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13510 not only for the immediate sources of the main project.
13511 @ifclear vms
13512 (-U stands for Universal or Union of the project files of the project tree)
13513 @end ifclear
13515 @noindent
13516 For each of the following commands, there is optionally a corresponding
13517 package in the main project.
13519 @itemize @bullet
13520 @item
13521 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13523 @item
13524 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13526 @item
13527 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13529 @item
13530 package @code{Eliminate} for command ELIM (invoking
13531 @code{^gnatelim^gnatelim^})
13533 @item
13534 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13536 @item
13537 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13539 @item
13540 package @code{Metrics} for command METRIC
13541 (invoking @code{^gnatmetric^gnatmetric^})
13543 @item
13544 package @code{Pretty_Printer} for command PP or PRETTY
13545 (invoking @code{^gnatpp^gnatpp^})
13547 @item
13548 package @code{Gnatstub} for command STUB
13549 (invoking @code{^gnatstub^gnatstub^})
13551 @item
13552 package @code{Cross_Reference} for command XREF (invoking
13553 @code{^gnatxref^gnatxref^})
13555 @end itemize
13557 @noindent
13558 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13559 a simple variable with a string list value. It contains ^switches^switches^
13560 for the invocation of @code{^gnatls^gnatls^}.
13562 @smallexample @c projectfile
13563 @group
13564 project Proj1 is
13565    package gnatls is
13566       for ^Switches^Switches^
13567           use ("^-a^-a^",
13568                "^-v^-v^");
13569    end gnatls;
13570 end Proj1;
13571 @end group
13572 @end smallexample
13574 @noindent
13575 All other packages have two attribute @code{^Switches^Switches^} and
13576 @code{^Default_Switches^Default_Switches^}.
13578 @noindent
13579 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13580 source file name, that has a string list value: the ^switches^switches^ to be
13581 used when the tool corresponding to the package is invoked for the specific
13582 source file.
13584 @noindent
13585 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13586 indexed by  the programming language that has a string list value.
13587 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13588 ^switches^switches^ for the invocation of the tool corresponding
13589 to the package, except if a specific @code{^Switches^Switches^} attribute
13590 is specified for the source file.
13592 @smallexample @c projectfile
13593 @group
13594 project Proj is
13596    for Source_Dirs use ("./**");
13598    package gnatls is
13599       for ^Switches^Switches^ use
13600           ("^-a^-a^",
13601            "^-v^-v^");
13602    end gnatls;
13603 @end group
13604 @group
13606    package Compiler is
13607       for ^Default_Switches^Default_Switches^ ("Ada")
13608           use ("^-gnatv^-gnatv^",
13609                "^-gnatwa^-gnatwa^");
13610    end Binder;
13611 @end group
13612 @group
13614    package Binder is
13615       for ^Default_Switches^Default_Switches^ ("Ada")
13616           use ("^-C^-C^",
13617                "^-e^-e^");
13618    end Binder;
13619 @end group
13620 @group
13622    package Linker is
13623       for ^Default_Switches^Default_Switches^ ("Ada")
13624           use ("^-C^-C^");
13625       for ^Switches^Switches^ ("main.adb")
13626           use ("^-C^-C^",
13627                "^-v^-v^",
13628                "^-v^-v^");
13629    end Linker;
13630 @end group
13631 @group
13633    package Finder is
13634       for ^Default_Switches^Default_Switches^ ("Ada")
13635            use ("^-a^-a^",
13636                 "^-f^-f^");
13637    end Finder;
13638 @end group
13639 @group
13641    package Cross_Reference is
13642       for ^Default_Switches^Default_Switches^ ("Ada")
13643           use ("^-a^-a^",
13644                "^-f^-f^",
13645                "^-d^-d^",
13646                "^-u^-u^");
13647    end Cross_Reference;
13648 end Proj;
13649 @end group
13650 @end smallexample
13652 @noindent
13653 With the above project file, commands such as
13655 @smallexample
13656    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13657    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13658    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13659    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13660    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13661 @end smallexample
13663 @noindent
13664 will set up the environment properly and invoke the tool with the switches
13665 found in the package corresponding to the tool:
13666 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13667 except @code{^Switches^Switches^ ("main.adb")}
13668 for @code{^gnatlink^gnatlink^}.
13670 @ifclear vms
13671 @node Glide and Project Files
13672 @subsection Glide and Project Files
13674 @noindent
13675 Glide will automatically recognize the @file{.gpr} extension for
13676 project files, and will
13677 convert them to its own internal format automatically. However, it
13678 doesn't provide a syntax-oriented editor for modifying these
13679 files.
13680 The project file will be loaded as text when you select the menu item
13681 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13682 You can edit this text and save the @file{gpr} file;
13683 when you next select this project file in Glide it
13684 will be automatically reloaded.
13685 @end ifclear
13687 @c **********************
13688 @node An Extended Example
13689 @section An Extended Example
13691 @noindent
13692 Suppose that we have two programs, @var{prog1} and @var{prog2},
13693 whose sources are in corresponding directories. We would like
13694 to build them with a single @command{gnatmake} command, and we want to place
13695 their object files into @file{build} subdirectories of the source directories.
13696 Furthermore, we want to have to have two separate subdirectories
13697 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13698 the object files compiled with different set of compilation flags.
13700 In other words, we have the following structure:
13702 @smallexample
13703 @group
13704    main
13705      |- prog1
13706      |    |- build
13707      |         | debug
13708      |         | release
13709      |- prog2
13710           |- build
13711                | debug
13712                | release
13713 @end group
13714 @end smallexample
13716 @noindent
13717 Here are the project files that we must place in a directory @file{main}
13718 to maintain this structure:
13720 @enumerate
13722 @item We create a @code{Common} project with a package @code{Compiler} that
13723 specifies the compilation ^switches^switches^:
13725 @smallexample
13726 File "common.gpr":
13727 @group
13728 @b{project} Common @b{is}
13730    @b{for} Source_Dirs @b{use} (); -- No source files
13731 @end group
13733 @group
13734    @b{type} Build_Type @b{is} ("release", "debug");
13735    Build : Build_Type := External ("BUILD", "debug");
13736 @end group
13737 @group
13738    @b{package} Compiler @b{is}
13739       @b{case} Build @b{is}
13740          @b{when} "release" =>
13741            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13742                    @b{use} ("^-O2^-O2^");
13743          @b{when} "debug"   =>
13744            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13745                    @b{use} ("^-g^-g^");
13746       @b{end case};
13747    @b{end} Compiler;
13749 @b{end} Common;
13750 @end group
13751 @end smallexample
13753 @item We create separate projects for the two programs:
13755 @smallexample
13756 @group
13757 File "prog1.gpr":
13759 @b{with} "common";
13760 @b{project} Prog1 @b{is}
13762     @b{for} Source_Dirs @b{use} ("prog1");
13763     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13765     @b{package} Compiler @b{renames} Common.Compiler;
13767 @b{end} Prog1;
13768 @end group
13769 @end smallexample
13771 @smallexample
13772 @group
13773 File "prog2.gpr":
13775 @b{with} "common";
13776 @b{project} Prog2 @b{is}
13778     @b{for} Source_Dirs @b{use} ("prog2");
13779     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13781     @b{package} Compiler @b{renames} Common.Compiler;
13783 @end group
13784 @b{end} Prog2;
13785 @end smallexample
13787 @item We create a wrapping project @code{Main}:
13789 @smallexample
13790 @group
13791 File "main.gpr":
13793 @b{with} "common";
13794 @b{with} "prog1";
13795 @b{with} "prog2";
13796 @b{project} Main @b{is}
13798    @b{package} Compiler @b{renames} Common.Compiler;
13800 @b{end} Main;
13801 @end group
13802 @end smallexample
13804 @item Finally we need to create a dummy procedure that @code{with}s (either
13805 explicitly or implicitly) all the sources of our two programs.
13807 @end enumerate
13809 @noindent
13810 Now we can build the programs using the command
13812 @smallexample
13813    gnatmake ^-P^/PROJECT_FILE=^main dummy
13814 @end smallexample
13816 @noindent
13817 for the Debug mode, or
13819 @ifclear vms
13820 @smallexample
13821    gnatmake -Pmain -XBUILD=release
13822 @end smallexample
13823 @end ifclear
13825 @ifset vms
13826 @smallexample
13827    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13828 @end smallexample
13829 @end ifset
13831 @noindent
13832 for the Release mode.
13834 @c ********************************
13835 @c * Project File Complete Syntax *
13836 @c ********************************
13838 @node Project File Complete Syntax
13839 @section Project File Complete Syntax
13841 @smallexample
13842 project ::=
13843   context_clause project_declaration
13845 context_clause ::=
13846   @{with_clause@}
13848 with_clause ::=
13849   @b{with} path_name @{ , path_name @} ;
13851 path_name ::=
13852    string_literal
13854 project_declaration ::=
13855   simple_project_declaration | project_extension
13857 simple_project_declaration ::=
13858   @b{project} <project_>simple_name @b{is}
13859     @{declarative_item@}
13860   @b{end} <project_>simple_name;
13862 project_extension ::=
13863   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13864     @{declarative_item@}
13865   @b{end} <project_>simple_name;
13867 declarative_item ::=
13868   package_declaration |
13869   typed_string_declaration |
13870   other_declarative_item
13872 package_declaration ::=
13873   package_specification | package_renaming
13875 package_specification ::=
13876   @b{package} package_identifier @b{is}
13877     @{simple_declarative_item@}
13878   @b{end} package_identifier ;
13880 package_identifier ::=
13881   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13882   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13883   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13885 package_renaming ::==
13886   @b{package} package_identifier @b{renames}
13887        <project_>simple_name.package_identifier ;
13889 typed_string_declaration ::=
13890   @b{type} <typed_string_>_simple_name @b{is}
13891    ( string_literal @{, string_literal@} );
13893 other_declarative_item ::=
13894   attribute_declaration |
13895   typed_variable_declaration |
13896   variable_declaration |
13897   case_construction
13899 attribute_declaration ::=
13900   full_associative_array_declaration |
13901   @b{for} attribute_designator @b{use} expression ;
13903 full_associative_array_declaration ::=
13904   @b{for} <associative_array_attribute_>simple_name @b{use}
13905   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13907 attribute_designator ::=
13908   <simple_attribute_>simple_name |
13909   <associative_array_attribute_>simple_name ( string_literal )
13911 typed_variable_declaration ::=
13912   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13914 variable_declaration ::=
13915   <variable_>simple_name := expression;
13917 expression ::=
13918   term @{& term@}
13920 term ::=
13921   literal_string |
13922   string_list |
13923   <variable_>name |
13924   external_value |
13925   attribute_reference
13927 string_literal ::=
13928   (same as Ada)
13930 string_list ::=
13931   ( <string_>expression @{ , <string_>expression @} )
13933 external_value ::=
13934   @b{external} ( string_literal [, string_literal] )
13936 attribute_reference ::=
13937   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13939 attribute_prefix ::=
13940   @b{project} |
13941   <project_>simple_name | package_identifier |
13942   <project_>simple_name . package_identifier
13944 case_construction ::=
13945   @b{case} <typed_variable_>name @b{is}
13946     @{case_item@}
13947   @b{end case} ;
13949 case_item ::=
13950   @b{when} discrete_choice_list =>
13951       @{case_construction | attribute_declaration@}
13953 discrete_choice_list ::=
13954   string_literal @{| string_literal@} |
13955   @b{others}
13957 name ::=
13958   simple_name @{. simple_name@}
13960 simple_name ::=
13961   identifier (same as Ada)
13963 @end smallexample
13965 @node The Cross-Referencing Tools gnatxref and gnatfind
13966 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13967 @findex gnatxref
13968 @findex gnatfind
13970 @noindent
13971 The compiler generates cross-referencing information (unless
13972 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13973 This information indicates where in the source each entity is declared and
13974 referenced. Note that entities in package Standard are not included, but
13975 entities in all other predefined units are included in the output.
13977 Before using any of these two tools, you need to compile successfully your
13978 application, so that GNAT gets a chance to generate the cross-referencing
13979 information.
13981 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13982 information to provide the user with the capability to easily locate the
13983 declaration and references to an entity. These tools are quite similar,
13984 the difference being that @code{gnatfind} is intended for locating
13985 definitions and/or references to a specified entity or entities, whereas
13986 @code{gnatxref} is oriented to generating a full report of all
13987 cross-references.
13989 To use these tools, you must not compile your application using the
13990 @option{-gnatx} switch on the @command{gnatmake} command line
13991 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13992 information will not be generated.
13994 @menu
13995 * gnatxref Switches::
13996 * gnatfind Switches::
13997 * Project Files for gnatxref and gnatfind::
13998 * Regular Expressions in gnatfind and gnatxref::
13999 * Examples of gnatxref Usage::
14000 * Examples of gnatfind Usage::
14001 @end menu
14003 @node gnatxref Switches
14004 @section @code{gnatxref} Switches
14006 @noindent
14007 The command invocation for @code{gnatxref} is:
14008 @smallexample
14009 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
14010 @end smallexample
14012 @noindent
14013 where
14015 @table @code
14016 @item sourcefile1, sourcefile2
14017 identifies the source files for which a report is to be generated. The
14018 ``with''ed units will be processed too. You must provide at least one file.
14020 These file names are considered to be regular expressions, so for instance
14021 specifying @file{source*.adb} is the same as giving every file in the current
14022 directory whose name starts with @file{source} and whose extension is
14023 @file{adb}.
14025 You shouldn't specify any directory name, just base names. @command{gnatxref}
14026 and @command{gnatfind} will be able to locate these files by themselves using
14027 the source path. If you specify directories, no result is produced.
14029 @end table
14031 @noindent
14032 The switches can be :
14033 @table @option
14034 @c !sort!
14035 @item ^-a^/ALL_FILES^
14036 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14037 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14038 the read-only files found in the library search path. Otherwise, these files
14039 will be ignored. This option can be used to protect Gnat sources or your own
14040 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14041 much faster, and their output much smaller. Read-only here refers to access
14042 or permissions status in the file system for the current user.
14044 @item -aIDIR
14045 @cindex @option{-aIDIR} (@command{gnatxref})
14046 When looking for source files also look in directory DIR. The order in which
14047 source file search is undertaken is the same as for @command{gnatmake}.
14049 @item -aODIR
14050 @cindex @option{-aODIR} (@command{gnatxref})
14051 When searching for library and object files, look in directory
14052 DIR. The order in which library files are searched is the same as for
14053 @command{gnatmake}.
14055 @item -nostdinc
14056 @cindex @option{-nostdinc} (@command{gnatxref})
14057 Do not look for sources in the system default directory.
14059 @item -nostdlib
14060 @cindex @option{-nostdlib} (@command{gnatxref})
14061 Do not look for library files in the system default directory.
14063 @item --RTS=@var{rts-path}
14064 @cindex @option{--RTS} (@command{gnatxref})
14065 Specifies the default location of the runtime library. Same meaning as the
14066 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14068 @item ^-d^/DERIVED_TYPES^
14069 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14070 If this switch is set @code{gnatxref} will output the parent type
14071 reference for each matching derived types.
14073 @item ^-f^/FULL_PATHNAME^
14074 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14075 If this switch is set, the output file names will be preceded by their
14076 directory (if the file was found in the search path). If this switch is
14077 not set, the directory will not be printed.
14079 @item ^-g^/IGNORE_LOCALS^
14080 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14081 If this switch is set, information is output only for library-level
14082 entities, ignoring local entities. The use of this switch may accelerate
14083 @code{gnatfind} and @code{gnatxref}.
14085 @item -IDIR
14086 @cindex @option{-IDIR} (@command{gnatxref})
14087 Equivalent to @samp{-aODIR -aIDIR}.
14089 @item -pFILE
14090 @cindex @option{-pFILE} (@command{gnatxref})
14091 Specify a project file to use @xref{Project Files}. These project files are
14092 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
14093 project files, you should use gnatxref through the GNAT driver
14094 (@command{gnat xref -Pproject}).
14096 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14097 project file in the current directory.
14099 If a project file is either specified or found by the tools, then the content
14100 of the source directory and object directory lines are added as if they
14101 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14102 and @samp{^-aO^OBJECT_SEARCH^}.
14103 @item ^-u^/UNUSED^
14104 Output only unused symbols. This may be really useful if you give your
14105 main compilation unit on the command line, as @code{gnatxref} will then
14106 display every unused entity and 'with'ed package.
14108 @ifclear vms
14109 @item -v
14110 Instead of producing the default output, @code{gnatxref} will generate a
14111 @file{tags} file that can be used by vi. For examples how to use this
14112 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14113 to the standard output, thus you will have to redirect it to a file.
14114 @end ifclear
14116 @end table
14118 @noindent
14119 All these switches may be in any order on the command line, and may even
14120 appear after the file names. They need not be separated by spaces, thus
14121 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14122 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14124 @node gnatfind Switches
14125 @section @code{gnatfind} Switches
14127 @noindent
14128 The command line for @code{gnatfind} is:
14130 @smallexample
14131 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14132       [file1 file2 ...]
14133 @end smallexample
14135 @noindent
14136 where
14138 @table @code
14139 @item pattern
14140 An entity will be output only if it matches the regular expression found
14141 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14143 Omitting the pattern is equivalent to specifying @samp{*}, which
14144 will match any entity. Note that if you do not provide a pattern, you
14145 have to provide both a sourcefile and a line.
14147 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14148 for matching purposes. At the current time there is no support for
14149 8-bit codes other than Latin-1, or for wide characters in identifiers.
14151 @item sourcefile
14152 @code{gnatfind} will look for references, bodies or declarations
14153 of symbols referenced in @file{sourcefile}, at line @samp{line}
14154 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14155 for syntax examples.
14157 @item line
14158 is a decimal integer identifying the line number containing
14159 the reference to the entity (or entities) to be located.
14161 @item column
14162 is a decimal integer identifying the exact location on the
14163 line of the first character of the identifier for the
14164 entity reference. Columns are numbered from 1.
14166 @item file1 file2 ...
14167 The search will be restricted to these source files. If none are given, then
14168 the search will be done for every library file in the search path.
14169 These file must appear only after the pattern or sourcefile.
14171 These file names are considered to be regular expressions, so for instance
14172 specifying 'source*.adb' is the same as giving every file in the current
14173 directory whose name starts with 'source' and whose extension is 'adb'.
14175 The location of the spec of the entity will always be displayed, even if it
14176 isn't in one of file1, file2,... The occurrences of the entity in the
14177 separate units of the ones given on the command line will also be displayed.
14179 Note that if you specify at least one file in this part, @code{gnatfind} may
14180 sometimes not be able to find the body of the subprograms...
14182 @end table
14184 @noindent
14185 At least one of 'sourcefile' or 'pattern' has to be present on
14186 the command line.
14188 The following switches are available:
14189 @table @option
14190 @c !sort!
14192 @item ^-a^/ALL_FILES^
14193 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14194 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14195 the read-only files found in the library search path. Otherwise, these files
14196 will be ignored. This option can be used to protect Gnat sources or your own
14197 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14198 much faster, and their output much smaller. Read-only here refers to access
14199 or permission status in the file system for the current user.
14201 @item -aIDIR
14202 @cindex @option{-aIDIR} (@command{gnatfind})
14203 When looking for source files also look in directory DIR. The order in which
14204 source file search is undertaken is the same as for @command{gnatmake}.
14206 @item -aODIR
14207 @cindex @option{-aODIR} (@command{gnatfind})
14208 When searching for library and object files, look in directory
14209 DIR. The order in which library files are searched is the same as for
14210 @command{gnatmake}.
14212 @item -nostdinc
14213 @cindex @option{-nostdinc} (@command{gnatfind})
14214 Do not look for sources in the system default directory.
14216 @item -nostdlib
14217 @cindex @option{-nostdlib} (@command{gnatfind})
14218 Do not look for library files in the system default directory.
14220 @item --RTS=@var{rts-path}
14221 @cindex @option{--RTS} (@command{gnatfind})
14222 Specifies the default location of the runtime library. Same meaning as the
14223 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14225 @item ^-d^/DERIVED_TYPE_INFORMATION^
14226 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14227 If this switch is set, then @code{gnatfind} will output the parent type
14228 reference for each matching derived types.
14230 @item ^-e^/EXPRESSIONS^
14231 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14232 By default, @code{gnatfind} accept the simple regular expression set for
14233 @samp{pattern}. If this switch is set, then the pattern will be
14234 considered as full Unix-style regular expression.
14236 @item ^-f^/FULL_PATHNAME^
14237 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14238 If this switch is set, the output file names will be preceded by their
14239 directory (if the file was found in the search path). If this switch is
14240 not set, the directory will not be printed.
14242 @item ^-g^/IGNORE_LOCALS^
14243 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14244 If this switch is set, information is output only for library-level
14245 entities, ignoring local entities. The use of this switch may accelerate
14246 @code{gnatfind} and @code{gnatxref}.
14248 @item -IDIR
14249 @cindex @option{-IDIR} (@command{gnatfind})
14250 Equivalent to @samp{-aODIR -aIDIR}.
14252 @item -pFILE
14253 @cindex @option{-pFILE} (@command{gnatfind})
14254 Specify a project file (@pxref{Project Files}) to use.
14255 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14256 project file in the current directory.
14258 If a project file is either specified or found by the tools, then the content
14259 of the source directory and object directory lines are added as if they
14260 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14261 @samp{^-aO^/OBJECT_SEARCH^}.
14263 @item ^-r^/REFERENCES^
14264 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14265 By default, @code{gnatfind} will output only the information about the
14266 declaration, body or type completion of the entities. If this switch is
14267 set, the @code{gnatfind} will locate every reference to the entities in
14268 the files specified on the command line (or in every file in the search
14269 path if no file is given on the command line).
14271 @item ^-s^/PRINT_LINES^
14272 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14273 If this switch is set, then @code{gnatfind} will output the content
14274 of the Ada source file lines were the entity was found.
14276 @item ^-t^/TYPE_HIERARCHY^
14277 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14278 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14279 the specified type. It act like -d option but recursively from parent
14280 type to parent type. When this switch is set it is not possible to
14281 specify more than one file.
14283 @end table
14285 @noindent
14286 All these switches may be in any order on the command line, and may even
14287 appear after the file names. They need not be separated by spaces, thus
14288 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14289 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14291 As stated previously, gnatfind will search in every directory in the
14292 search path. You can force it to look only in the current directory if
14293 you specify @code{*} at the end of the command line.
14295 @node Project Files for gnatxref and gnatfind
14296 @section Project Files for @command{gnatxref} and @command{gnatfind}
14298 @noindent
14299 Project files allow a programmer to specify how to compile its
14300 application, where to find sources, etc.  These files are used
14301 @ifclear vms
14302 primarily by the Glide Ada mode, but they can also be used
14303 @end ifclear
14304 by the two tools
14305 @code{gnatxref} and @code{gnatfind}.
14307 A project file name must end with @file{.gpr}. If a single one is
14308 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14309 extract the information from it. If multiple project files are found, none of
14310 them is read, and you have to use the @samp{-p} switch to specify the one
14311 you want to use.
14313 The following lines can be included, even though most of them have default
14314 values which can be used in most cases.
14315 The lines can be entered in any order in the file.
14316 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14317 each line. If you have multiple instances, only the last one is taken into
14318 account.
14320 @table @code
14321 @item src_dir=DIR
14322 [default: @code{"^./^[]^"}]
14323 specifies a directory where to look for source files. Multiple @code{src_dir}
14324 lines can be specified and they will be searched in the order they
14325 are specified.
14327 @item obj_dir=DIR
14328 [default: @code{"^./^[]^"}]
14329 specifies a directory where to look for object and library files. Multiple
14330 @code{obj_dir} lines can be specified, and they will be searched in the order
14331 they are specified
14333 @item comp_opt=SWITCHES
14334 [default: @code{""}]
14335 creates a variable which can be referred to subsequently by using
14336 the @code{$@{comp_opt@}} notation. This is intended to store the default
14337 switches given to @command{gnatmake} and @command{gcc}.
14339 @item bind_opt=SWITCHES
14340 [default: @code{""}]
14341 creates a variable which can be referred to subsequently by using
14342 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14343 switches given to @command{gnatbind}.
14345 @item link_opt=SWITCHES
14346 [default: @code{""}]
14347 creates a variable which can be referred to subsequently by using
14348 the @samp{$@{link_opt@}} notation. This is intended to store the default
14349 switches given to @command{gnatlink}.
14351 @item main=EXECUTABLE
14352 [default: @code{""}]
14353 specifies the name of the executable for the application. This variable can
14354 be referred to in the following lines by using the @samp{$@{main@}} notation.
14356 @ifset vms
14357 @item comp_cmd=COMMAND
14358 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14359 @end ifset
14360 @ifclear vms
14361 @item comp_cmd=COMMAND
14362 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14363 @end ifclear
14364 specifies the command used to compile a single file in the application.
14366 @ifset vms
14367 @item make_cmd=COMMAND
14368 [default: @code{"GNAT MAKE $@{main@}
14369 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14370 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14371 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14372 @end ifset
14373 @ifclear vms
14374 @item make_cmd=COMMAND
14375 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14376  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14377  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14378 @end ifclear
14379 specifies the command used to recompile the whole application.
14381 @item run_cmd=COMMAND
14382 [default: @code{"$@{main@}"}]
14383 specifies the command used to run the application.
14385 @item debug_cmd=COMMAND
14386 [default: @code{"gdb $@{main@}"}]
14387 specifies the command used to debug the application
14389 @end table
14391 @noindent
14392 @command{gnatxref} and @command{gnatfind} only take into account the
14393 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14395 @node Regular Expressions in gnatfind and gnatxref
14396 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14398 @noindent
14399 As specified in the section about @command{gnatfind}, the pattern can be a
14400 regular expression. Actually, there are to set of regular expressions
14401 which are recognized by the program :
14403 @table @code
14404 @item globbing patterns
14405 These are the most usual regular expression. They are the same that you
14406 generally used in a Unix shell command line, or in a DOS session.
14408 Here is a more formal grammar :
14409 @smallexample
14410 @group
14411 @iftex
14412 @leftskip=.5cm
14413 @end iftex
14414 regexp ::= term
14415 term   ::= elmt            -- matches elmt
14416 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14417 term   ::= *               -- any string of 0 or more characters
14418 term   ::= ?               -- matches any character
14419 term   ::= [char @{char@}] -- matches any character listed
14420 term   ::= [char - char]   -- matches any character in range
14421 @end group
14422 @end smallexample
14424 @item full regular expression
14425 The second set of regular expressions is much more powerful. This is the
14426 type of regular expressions recognized by utilities such a @file{grep}.
14428 The following is the form of a regular expression, expressed in Ada
14429 reference manual style BNF is as follows
14431 @smallexample
14432 @iftex
14433 @leftskip=.5cm
14434 @end iftex
14435 @group
14436 regexp ::= term @{| term@} -- alternation (term or term ...)
14438 term ::= item @{item@}     -- concatenation (item then item)
14440 item ::= elmt              -- match elmt
14441 item ::= elmt *            -- zero or more elmt's
14442 item ::= elmt +            -- one or more elmt's
14443 item ::= elmt ?            -- matches elmt or nothing
14444 @end group
14445 @group
14446 elmt ::= nschar            -- matches given character
14447 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14448 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14449 elmt ::= [char - char]     -- matches chars in given range
14450 elmt ::= \ char            -- matches given character
14451 elmt ::= .                 -- matches any single character
14452 elmt ::= ( regexp )        -- parens used for grouping
14454 char ::= any character, including special characters
14455 nschar ::= any character except ()[].*+?^^^
14456 @end group
14457 @end smallexample
14459 Following are a few examples :
14461 @table @samp
14462 @item abcde|fghi
14463 will match any of the two strings 'abcde' and 'fghi'.
14465 @item abc*d
14466 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14468 @item [a-z]+
14469 will match any string which has only lowercase characters in it (and at
14470 least one character
14472 @end table
14473 @end table
14475 @node Examples of gnatxref Usage
14476 @section Examples of @code{gnatxref} Usage
14478 @subsection General Usage
14480 @noindent
14481 For the following examples, we will consider the following units :
14483 @smallexample @c ada
14484 @group
14485 @cartouche
14486 main.ads:
14487 1: with Bar;
14488 2: package Main is
14489 3:     procedure Foo (B : in Integer);
14490 4:     C : Integer;
14491 5: private
14492 6:     D : Integer;
14493 7: end Main;
14495 main.adb:
14496 1: package body Main is
14497 2:     procedure Foo (B : in Integer) is
14498 3:     begin
14499 4:        C := B;
14500 5:        D := B;
14501 6:        Bar.Print (B);
14502 7:        Bar.Print (C);
14503 8:     end Foo;
14504 9: end Main;
14506 bar.ads:
14507 1: package Bar is
14508 2:     procedure Print (B : Integer);
14509 3: end bar;
14510 @end cartouche
14511 @end group
14512 @end smallexample
14514 @table @code
14516 @noindent
14517 The first thing to do is to recompile your application (for instance, in
14518 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14519 the cross-referencing information.
14520 You can then issue any of the following commands:
14522 @item gnatxref main.adb
14523 @code{gnatxref} generates cross-reference information for main.adb
14524 and every unit 'with'ed by main.adb.
14526 The output would be:
14527 @smallexample
14528 @iftex
14529 @leftskip=0cm
14530 @end iftex
14531 B                                                      Type: Integer
14532   Decl: bar.ads           2:22
14533 B                                                      Type: Integer
14534   Decl: main.ads          3:20
14535   Body: main.adb          2:20
14536   Ref:  main.adb          4:13     5:13     6:19
14537 Bar                                                    Type: Unit
14538   Decl: bar.ads           1:9
14539   Ref:  main.adb          6:8      7:8
14540        main.ads           1:6
14541 C                                                      Type: Integer
14542   Decl: main.ads          4:5
14543   Modi: main.adb          4:8
14544   Ref:  main.adb          7:19
14545 D                                                      Type: Integer
14546   Decl: main.ads          6:5
14547   Modi: main.adb          5:8
14548 Foo                                                    Type: Unit
14549   Decl: main.ads          3:15
14550   Body: main.adb          2:15
14551 Main                                                    Type: Unit
14552   Decl: main.ads          2:9
14553   Body: main.adb          1:14
14554 Print                                                   Type: Unit
14555   Decl: bar.ads           2:15
14556   Ref:  main.adb          6:12     7:12
14557 @end smallexample
14559 @noindent
14560 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14561 its body is in main.adb, line 1, column 14 and is not referenced any where.
14563 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14564 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14566 @item gnatxref package1.adb package2.ads
14567 @code{gnatxref} will generates cross-reference information for
14568 package1.adb, package2.ads and any other package 'with'ed by any
14569 of these.
14571 @end table
14573 @ifclear vms
14574 @subsection Using gnatxref with vi
14576 @code{gnatxref} can generate a tags file output, which can be used
14577 directly from @file{vi}. Note that the standard version of @file{vi}
14578 will not work properly with overloaded symbols. Consider using another
14579 free implementation of @file{vi}, such as @file{vim}.
14581 @smallexample
14582 $ gnatxref -v gnatfind.adb > tags
14583 @end smallexample
14585 @noindent
14586 will generate the tags file for @code{gnatfind} itself (if the sources
14587 are in the search path!).
14589 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14590 (replacing @i{entity} by whatever you are looking for), and vi will
14591 display a new file with the corresponding declaration of entity.
14592 @end ifclear
14594 @node Examples of gnatfind Usage
14595 @section Examples of @code{gnatfind} Usage
14597 @table @code
14599 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14600 Find declarations for all entities xyz referenced at least once in
14601 main.adb. The references are search in every library file in the search
14602 path.
14604 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14605 switch is set)
14607 The output will look like:
14608 @smallexample
14609 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14610 ^directory/^[directory]^main.adb:24:10: xyz <= body
14611 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14612 @end smallexample
14614 @noindent
14615 that is to say, one of the entities xyz found in main.adb is declared at
14616 line 12 of main.ads (and its body is in main.adb), and another one is
14617 declared at line 45 of foo.ads
14619 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14620 This is the same command as the previous one, instead @code{gnatfind} will
14621 display the content of the Ada source file lines.
14623 The output will look like:
14625 @smallexample
14626 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14627    procedure xyz;
14628 ^directory/^[directory]^main.adb:24:10: xyz <= body
14629    procedure xyz is
14630 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14631    xyz : Integer;
14632 @end smallexample
14634 @noindent
14635 This can make it easier to find exactly the location your are looking
14636 for.
14638 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14639 Find references to all entities containing an x that are
14640 referenced on line 123 of main.ads.
14641 The references will be searched only in main.ads and foo.adb.
14643 @item gnatfind main.ads:123
14644 Find declarations and bodies for all entities that are referenced on
14645 line 123 of main.ads.
14647 This is the same as @code{gnatfind "*":main.adb:123}.
14649 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14650 Find the declaration for the entity referenced at column 45 in
14651 line 123 of file main.adb in directory mydir. Note that it
14652 is usual to omit the identifier name when the column is given,
14653 since the column position identifies a unique reference.
14655 The column has to be the beginning of the identifier, and should not
14656 point to any character in the middle of the identifier.
14658 @end table
14660 @c *********************************
14661 @node The GNAT Pretty-Printer gnatpp
14662 @chapter The GNAT Pretty-Printer @command{gnatpp}
14663 @findex gnatpp
14664 @cindex Pretty-Printer
14666 @noindent
14667 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14668 for source reformatting / pretty-printing.
14669 It takes an Ada source file as input and generates a reformatted
14670 version as output.
14671 You can specify various style directives via switches; e.g.,
14672 identifier case conventions, rules of indentation, and comment layout.
14674 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14675 tree for the input source and thus requires the input to be syntactically and
14676 semantically legal.
14677 If this condition is not met, @command{gnatpp} will terminate with an
14678 error message; no output file will be generated.
14680 If the compilation unit
14681 contained in the input source depends semantically upon units located
14682 outside the current directory, you have to provide the source search path
14683 when invoking @command{gnatpp}, if these units are contained in files with
14684 names that do not follow the GNAT file naming rules, you have to provide
14685 the configuration file describing the corresponding naming scheme;
14686 see the description of the @command{gnatpp}
14687 switches below. Another possibility is to use a project file and to
14688 call @command{gnatpp} through the @command{gnat} driver
14690 The @command{gnatpp} command has the form
14692 @smallexample
14693 $ gnatpp [@var{switches}] @var{filename}
14694 @end smallexample
14696 @noindent
14697 where
14698 @itemize @bullet
14699 @item
14700 @var{switches} is an optional sequence of switches defining such properties as
14701 the formatting rules, the source search path, and the destination for the
14702 output source file
14704 @item
14705 @var{filename} is the name (including the extension) of the source file to
14706 reformat; ``wildcards'' or several file names on the same gnatpp command are
14707 allowed.  The file name may contain path information; it does not have to
14708 follow the GNAT file naming rules
14709 @end itemize
14711 @menu
14712 * Switches for gnatpp::
14713 * Formatting Rules::
14714 @end menu
14716 @node Switches for gnatpp
14717 @section Switches for @command{gnatpp}
14719 @noindent
14720 The following subsections describe the various switches accepted by
14721 @command{gnatpp}, organized by category.
14723 @ifclear vms
14724 You specify a switch by supplying a name and generally also a value.
14725 In many cases the values for a switch with a given name are incompatible with
14726 each other
14727 (for example the switch that controls the casing of a reserved word may have
14728 exactly one value: upper case, lower case, or
14729 mixed case) and thus exactly one such switch can be in effect for an
14730 invocation of @command{gnatpp}.
14731 If more than one is supplied, the last one is used.
14732 However, some values for the same switch are mutually compatible.
14733 You may supply several such switches to @command{gnatpp}, but then
14734 each must be specified in full, with both the name and the value.
14735 Abbreviated forms (the name appearing once, followed by each value) are
14736 not permitted.
14737 For example, to set
14738 the alignment of the assignment delimiter both in declarations and in
14739 assignment statements, you must write @option{-A2A3}
14740 (or @option{-A2 -A3}), but not @option{-A23}.
14741 @end ifclear
14743 @ifset vms
14744 In many cases the set of options for a given qualifier are incompatible with
14745 each other (for example the qualifier that controls the casing of a reserved
14746 word may have exactly one option, which specifies either upper case, lower
14747 case, or mixed case), and thus exactly one such option can be in effect for
14748 an invocation of @command{gnatpp}.
14749 If more than one is supplied, the last one is used.
14750 However, some qualifiers have options that are mutually compatible,
14751 and then you may then supply several such options when invoking
14752 @command{gnatpp}.
14753 @end ifset
14755 In most cases, it is obvious whether or not the
14756 ^values for a switch with a given name^options for a given qualifier^
14757 are compatible with each other.
14758 When the semantics might not be evident, the summaries below explicitly
14759 indicate the effect.
14761 @menu
14762 * Alignment Control::
14763 * Casing Control::
14764 * Construct Layout Control::
14765 * General Text Layout Control::
14766 * Other Formatting Options::
14767 * Setting the Source Search Path::
14768 * Output File Control::
14769 * Other gnatpp Switches::
14770 @end menu
14772 @node Alignment Control
14773 @subsection Alignment Control
14774 @cindex Alignment control in @command{gnatpp}
14776 @noindent
14777 Programs can be easier to read if certain constructs are vertically aligned.
14778 By default all alignments are set ON.
14779 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14780 OFF, and then use one or more of the other
14781 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14782 to activate alignment for specific constructs.
14784 @table @option
14785 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14787 @ifset vms
14788 @item /ALIGN=ON
14789 Set all alignments to ON
14790 @end ifset
14792 @item ^-A0^/ALIGN=OFF^
14793 Set all alignments to OFF
14795 @item ^-A1^/ALIGN=COLONS^
14796 Align @code{:} in declarations
14798 @item ^-A2^/ALIGN=DECLARATIONS^
14799 Align @code{:=} in initializations in declarations
14801 @item ^-A3^/ALIGN=STATEMENTS^
14802 Align @code{:=} in assignment statements
14804 @item ^-A4^/ALIGN=ARROWS^
14805 Align @code{=>} in associations
14807 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14808 Align @code{at} keywords in the component clauses in record
14809 representation clauses
14810 @end table
14812 @noindent
14813 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14814 is allowed.
14816 @node Casing Control
14817 @subsection Casing Control
14818 @cindex Casing control in @command{gnatpp}
14820 @noindent
14821 @command{gnatpp} allows you to specify the casing for reserved words,
14822 pragma names, attribute designators and identifiers.
14823 For identifiers you may define a
14824 general rule for name casing but also override this rule
14825 via a set of dictionary files.
14827 Three types of casing are supported: lower case, upper case, and mixed case.
14828 Lower and upper case are self-explanatory (but since some letters in
14829 Latin1 and other GNAT-supported character sets
14830 exist only in lower-case form, an upper case conversion will have no
14831 effect on them.)
14832 ``Mixed case'' means that the first letter, and also each letter immediately
14833 following an underscore, are converted to their uppercase forms;
14834 all the other letters are converted to their lowercase forms.
14836 @table @option
14837 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14838 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14839 Attribute designators are lower case
14841 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14842 Attribute designators are upper case
14844 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14845 Attribute designators are mixed case (this is the default)
14847 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14848 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14849 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14850 lower case (this is the default)
14852 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14853 Keywords are upper case
14855 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14856 @item ^-nD^/NAME_CASING=AS_DECLARED^
14857 Name casing for defining occurrences are as they appear in the source file
14858 (this is the default)
14860 @item ^-nU^/NAME_CASING=UPPER_CASE^
14861 Names are in upper case
14863 @item ^-nL^/NAME_CASING=LOWER_CASE^
14864 Names are in lower case
14866 @item ^-nM^/NAME_CASING=MIXED_CASE^
14867 Names are in mixed case
14869 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14870 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14871 Pragma names are lower case
14873 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14874 Pragma names are upper case
14876 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14877 Pragma names are mixed case (this is the default)
14879 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14880 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14881 Use @var{file} as a @emph{dictionary file} that defines
14882 the casing for a set of specified names,
14883 thereby overriding the effect on these names by
14884 any explicit or implicit
14885 ^-n^/NAME_CASING^ switch.
14886 To supply more than one dictionary file,
14887 use ^several @option{-D} switches^a list of files as options^.
14889 @noindent
14890 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14891 to define the casing for the Ada predefined names and
14892 the names declared in the GNAT libraries.
14894 @item ^-D-^/SPECIFIC_CASING^
14895 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14896 Do not use the default dictionary file;
14897 instead, use the casing
14898 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14899 dictionary file(s)
14900 @end table
14902 @noindent
14903 The structure of a dictionary file, and details on the conventions
14904 used in the default dictionary file, are defined in @ref{Name Casing}.
14906 The @option{^-D-^/SPECIFIC_CASING^} and
14907 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14908 compatible.
14910 @node Construct Layout Control
14911 @subsection Construct Layout Control
14912 @cindex Layout control in @command{gnatpp}
14914 @noindent
14915 This group of @command{gnatpp} switches controls the layout of comments and
14916 complex syntactic constructs.  See @ref{Formatting Comments} for details
14917 on their effect.
14919 @table @option
14920 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14921 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14922 All the comments remain unchanged
14924 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14925 GNAT-style comment line indentation (this is the default).
14927 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14928 Reference-manual comment line indentation.
14930 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14931 GNAT-style comment beginning
14933 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14934 Reformat comment blocks
14936 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14937 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14938 GNAT-style layout (this is the default)
14940 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14941 Compact layout
14943 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14944 Uncompact layout
14946 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14947 @item ^-N^/NOTABS^
14948 All the VT characters are removed from the comment text. All the HT characters
14949 are expanded with the sequences of space characters to get to the next tab
14950 stops.
14952 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14953 @item ^--no-separate-is^/NO_SEPARATE_IS^
14954 Do not place the keyword @code{is} on a separate line in a subprogram body in
14955 case if the specification occupies more then one line.
14957 @end table
14959 @ifclear vms
14960 @noindent
14961 The @option{-c1} and @option{-c2} switches are incompatible.
14962 The @option{-c3} and @option{-c4} switches are compatible with each other and
14963 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14964 the other comment formatting switches.
14966 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14967 @end ifclear
14969 @ifset vms
14970 @noindent
14971 For the @option{/COMMENTS_LAYOUT} qualifier:
14972 @itemize @bullet
14973 @item
14974 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14975 @item
14976 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14977 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14978 @end itemize
14980 @noindent
14981 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14982 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14983 @end ifset
14985 @node General Text Layout Control
14986 @subsection General Text Layout Control
14988 @noindent
14989 These switches allow control over line length and indentation.
14991 @table @option
14992 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14993 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14994 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14996 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14997 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14998 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
15000 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15001 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15002 Indentation level for continuation lines (relative to the line being
15003 continued), @i{nnn} from 1 .. 9.
15004 The default
15005 value is one less then the (normal) indentation level, unless the
15006 indentation is set to 1 (in which case the default value for continuation
15007 line indentation is also 1)
15008 @end table
15010 @node Other Formatting Options
15011 @subsection Other Formatting Options
15013 @noindent
15014 These switches control the inclusion of missing end/exit labels, and
15015 the indentation level in @b{case} statements.
15017 @table @option
15018 @item ^-e^/NO_MISSED_LABELS^
15019 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15020 Do not insert missing end/exit labels. An end label is the name of
15021 a construct that may optionally be repeated at the end of the
15022 construct's declaration;
15023 e.g., the names of packages, subprograms, and tasks.
15024 An exit label is the name of a loop that may appear as target
15025 of an exit statement within the loop.
15026 By default, @command{gnatpp} inserts these end/exit labels when
15027 they are absent from the original source. This option suppresses such
15028 insertion, so that the formatted source reflects the original.
15030 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15031 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15032 Insert a Form Feed character after a pragma Page.
15034 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15035 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15036 Do not use an additional indentation level for @b{case} alternatives
15037 and variants if there are @i{nnn} or more (the default
15038 value is 10).
15039 If @i{nnn} is 0, an additional indentation level is
15040 used for @b{case} alternatives and variants regardless of their number.
15041 @end table
15043 @node Setting the Source Search Path
15044 @subsection Setting the Source Search Path
15046 @noindent
15047 To define the search path for the input source file, @command{gnatpp}
15048 uses the same switches as the GNAT compiler, with the same effects.
15050 @table @option
15051 @item ^-I^/SEARCH=^@var{dir}
15052 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15053 The same as the corresponding gcc switch
15055 @item ^-I-^/NOCURRENT_DIRECTORY^
15056 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15057 The same as the corresponding gcc switch
15059 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15060 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15061 The same as the corresponding gcc switch
15063 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15064 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15065 The same as the corresponding gcc switch
15067 @end table
15069 @node Output File Control
15070 @subsection Output File Control
15072 @noindent
15073 By default the output is sent to the file whose name is obtained by appending
15074 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15075 (if the file with this name already exists, it is unconditionally overwritten).
15076 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15077 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15078 as output file.
15079 The output may be redirected by the following switches:
15081 @table @option
15082 @item ^-pipe^/STANDARD_OUTPUT^
15083 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15084 Send the output to @code{Standard_Output}
15086 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15087 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15088 Write the output into @var{output_file}.
15089 If @var{output_file} already exists, @command{gnatpp} terminates without
15090 reading or processing the input file.
15092 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15093 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15094 Write the output into @var{output_file}, overwriting the existing file
15095 (if one is present).
15097 @item ^-r^/REPLACE^
15098 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15099 Replace the input source file with the reformatted output, and copy the
15100 original input source into the file whose name is obtained by appending the
15101 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15102 If a file with this name already exists, @command{gnatpp} terminates without
15103 reading or processing the input file.
15105 @item ^-rf^/OVERRIDING_REPLACE^
15106 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15107 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15108 already exists, it is overwritten.
15110 @item ^-rnb^/NO_BACKUP^
15111 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15112 Replace the input source file with the reformatted output without
15113 creating any backup copy of the input source.
15115 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15116 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15117 Specifies the format of the reformatted output file. The @var{xxx}
15118 ^string specified with the switch^option^ may be either
15119 @itemize @bullet
15120 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15121 @item ``@option{^crlf^CRLF^}''
15122 the same as @option{^crlf^CRLF^}
15123 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15124 @item ``@option{^lf^LF^}''
15125 the same as @option{^unix^UNIX^}
15126 @end itemize
15128 @end table
15130 @noindent
15131 Options @option{^-pipe^/STANDARD_OUTPUT^},
15132 @option{^-o^/OUTPUT^} and
15133 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15134 contains only one file to reformat.
15135 Option
15136 @option{^--eol^/END_OF_LINE^}
15137 cannot be used together
15138 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15140 @node Other gnatpp Switches
15141 @subsection Other @code{gnatpp} Switches
15143 @noindent
15144 The additional @command{gnatpp} switches are defined in this subsection.
15146 @table @option
15147 @item ^-files @var{filename}^/FILES=@var{output_file}^
15148 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15149 Take the argument source files from the specified file. This file should be an
15150 ordinary textual file containing file names separated by spaces or
15151 line breaks. You can use this switch more then once in the same call to
15152 @command{gnatpp}. You also can combine this switch with explicit list of
15153 files.
15155 @item ^-v^/VERBOSE^
15156 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15157 Verbose mode;
15158 @command{gnatpp} generates version information and then
15159 a trace of the actions it takes to produce or obtain the ASIS tree.
15161 @item ^-w^/WARNINGS^
15162 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15163 Warning mode;
15164 @command{gnatpp} generates a warning whenever it cannot provide
15165 a required layout in the result source.
15166 @end table
15168 @node Formatting Rules
15169 @section Formatting Rules
15171 @noindent
15172 The following subsections show how @command{gnatpp} treats ``white space'',
15173 comments, program layout, and name casing.
15174 They provide the detailed descriptions of the switches shown above.
15176 @menu
15177 * White Space and Empty Lines::
15178 * Formatting Comments::
15179 * Construct Layout::
15180 * Name Casing::
15181 @end menu
15183 @node White Space and Empty Lines
15184 @subsection White Space and Empty Lines
15186 @noindent
15187 @command{gnatpp} does not have an option to control space characters.
15188 It will add or remove spaces according to the style illustrated by the
15189 examples in the @cite{Ada Reference Manual}.
15191 The only format effectors
15192 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15193 that will appear in the output file are platform-specific line breaks,
15194 and also format effectors within (but not at the end of) comments.
15195 In particular, each horizontal tab character that is not inside
15196 a comment will be treated as a space and thus will appear in the
15197 output file as zero or more spaces depending on
15198 the reformatting of the line in which it appears.
15199 The only exception is a Form Feed character, which is inserted after a
15200 pragma @code{Page} when @option{-ff} is set.
15202 The output file will contain no lines with trailing ``white space'' (spaces,
15203 format effectors).
15205 Empty lines in the original source are preserved
15206 only if they separate declarations or statements.
15207 In such contexts, a
15208 sequence of two or more empty lines is replaced by exactly one empty line.
15209 Note that a blank line will be removed if it separates two ``comment blocks''
15210 (a comment block is a sequence of whole-line comments).
15211 In order to preserve a visual separation between comment blocks, use an
15212 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15213 Likewise, if for some reason you wish to have a sequence of empty lines,
15214 use a sequence of empty comments instead.
15216 @node Formatting Comments
15217 @subsection Formatting Comments
15219 @noindent
15220 Comments in Ada code are of two kinds:
15221 @itemize @bullet
15222 @item
15223 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15224 ``white space'') on a line
15226 @item
15227 an @emph{end-of-line comment}, which follows some other Ada lexical element
15228 on the same line.
15229 @end itemize
15231 @noindent
15232 The indentation of a whole-line comment is that of either
15233 the preceding or following line in
15234 the formatted source, depending on switch settings as will be described below.
15236 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15237 between the end of the preceding Ada lexical element and the beginning
15238 of the comment as appear in the original source,
15239 unless either the comment has to be split to
15240 satisfy the line length limitation, or else the next line contains a
15241 whole line comment that is considered a continuation of this end-of-line
15242 comment (because it starts at the same position).
15243 In the latter two
15244 cases, the start of the end-of-line comment is moved right to the nearest
15245 multiple of the indentation level.
15246 This may result in a ``line overflow'' (the right-shifted comment extending
15247 beyond the maximum line length), in which case the comment is split as
15248 described below.
15250 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15251 (GNAT-style comment line indentation)
15252 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15253 (reference-manual comment line indentation).
15254 With reference-manual style, a whole-line comment is indented as if it
15255 were a declaration or statement at the same place
15256 (i.e., according to the indentation of the preceding line(s)).
15257 With GNAT style, a whole-line comment that is immediately followed by an
15258 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15259 word @b{begin}, is indented based on the construct that follows it.
15261 For example:
15262 @smallexample @c ada
15263 @cartouche
15264 if A then
15265     null;
15266        -- some comment
15267 else
15268    null;
15269 end if;
15270 @end cartouche
15271 @end smallexample
15273 @noindent
15274 Reference-manual indentation produces:
15276 @smallexample @c ada
15277 @cartouche
15278 if A then
15279    null;
15280    --  some comment
15281 else
15282    null;
15283 end if;
15284 @end cartouche
15285 @end smallexample
15287 @noindent
15288 while GNAT-style indentation produces:
15290 @smallexample @c ada
15291 @cartouche
15292 if A then
15293    null;
15294 --  some comment
15295 else
15296    null;
15297 end if;
15298 @end cartouche
15299 @end smallexample
15301 @noindent
15302 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15303 (GNAT style comment beginning) has the following
15304 effect:
15306 @itemize @bullet
15307 @item
15308 For each whole-line comment that does not end with two hyphens,
15309 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15310 to ensure that there are at least two spaces between these hyphens and the
15311 first non-blank character of the comment.
15312 @end itemize
15314 @noindent
15315 For an end-of-line comment, if in the original source the next line is a
15316 whole-line comment that starts at the same position
15317 as the end-of-line comment,
15318 then the whole-line comment (and all whole-line comments
15319 that follow it and that start at the same position)
15320 will start at this position in the output file.
15322 @noindent
15323 That is, if in the original source we have:
15325 @smallexample @c ada
15326 @cartouche
15327 begin
15328 A := B + C;            --  B must be in the range Low1..High1
15329                        --  C must be in the range Low2..High2
15330              --B+C will be in the range Low1+Low2..High1+High2
15331 X := X + 1;
15332 @end cartouche
15333 @end smallexample
15335 @noindent
15336 Then in the formatted source we get
15338 @smallexample @c ada
15339 @cartouche
15340 begin
15341    A := B + C;            --  B must be in the range Low1..High1
15342                           --  C must be in the range Low2..High2
15343    --  B+C will be in the range Low1+Low2..High1+High2
15344    X := X + 1;
15345 @end cartouche
15346 @end smallexample
15348 @noindent
15349 A comment that exceeds the line length limit will be split.
15350 Unless switch
15351 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15352 the line belongs to a reformattable block, splitting the line generates a
15353 @command{gnatpp} warning.
15354 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15355 comments may be reformatted in typical
15356 word processor style (that is, moving words between lines and putting as
15357 many words in a line as possible).
15359 @node Construct Layout
15360 @subsection Construct Layout
15362 @noindent
15363 In several cases the suggested layout in the Ada Reference Manual includes
15364 an extra level of indentation that many programmers prefer to avoid. The
15365 affected cases include:
15367 @itemize @bullet
15369 @item Record type declaration (RM 3.8)
15371 @item Record representation clause (RM 13.5.1)
15373 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15375 @item Block statement in case if a block has a statement identifier (RM 5.6)
15376 @end itemize
15378 @noindent
15379 In compact mode (when GNAT style layout or compact layout is set),
15380 the pretty printer uses one level of indentation instead
15381 of two. This is achieved in the record definition and record representation
15382 clause cases by putting the @code{record} keyword on the same line as the
15383 start of the declaration or representation clause, and in the block and loop
15384 case by putting the block or loop header on the same line as the statement
15385 identifier.
15387 @noindent
15388 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15389 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15390 layout on the one hand, and uncompact layout
15391 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15392 can be illustrated by the following examples:
15394 @iftex
15395 @cartouche
15396 @multitable @columnfractions .5 .5
15397 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15399 @item
15400 @smallexample @c ada
15401 type q is record
15402    a : integer;
15403    b : integer;
15404 end record;
15405 @end smallexample
15406 @tab
15407 @smallexample @c ada
15408 type q is
15409    record
15410       a : integer;
15411       b : integer;
15412    end record;
15413 @end smallexample
15415 @item
15416 @smallexample @c ada
15417 for q use record
15418    a at 0 range  0 .. 31;
15419    b at 4 range  0 .. 31;
15420 end record;
15421 @end smallexample
15422 @tab
15423 @smallexample @c ada
15424 for q use
15425    record
15426       a at 0 range  0 .. 31;
15427       b at 4 range  0 .. 31;
15428    end record;
15429 @end smallexample
15431 @item
15432 @smallexample @c ada
15433 Block : declare
15434    A : Integer := 3;
15435 begin
15436    Proc (A, A);
15437 end Block;
15438 @end smallexample
15439 @tab
15440 @smallexample @c ada
15441 Block :
15442    declare
15443       A : Integer := 3;
15444    begin
15445       Proc (A, A);
15446    end Block;
15447 @end smallexample
15449 @item
15450 @smallexample @c ada
15451 Clear : for J in 1 .. 10 loop
15452    A (J) := 0;
15453 end loop Clear;
15454 @end smallexample
15455 @tab
15456 @smallexample @c ada
15457 Clear :
15458    for J in 1 .. 10 loop
15459       A (J) := 0;
15460    end loop Clear;
15461 @end smallexample
15462 @end multitable
15463 @end cartouche
15464 @end iftex
15466 @ifnottex
15467 @smallexample
15468 @cartouche
15469 GNAT style, compact layout              Uncompact layout
15471 type q is record                        type q is
15472    a : integer;                            record
15473    b : integer;                               a : integer;
15474 end record;                                   b : integer;
15475                                            end record;
15477 for q use record                        for q use
15478    a at 0 range  0 .. 31;                  record
15479    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
15480 end record;                                   b at 4 range  0 .. 31;
15481                                            end record;
15483 Block : declare                         Block :
15484    A : Integer := 3;                       declare
15485 begin                                         A : Integer := 3;
15486    Proc (A, A);                            begin
15487 end Block;                                    Proc (A, A);
15488                                            end Block;
15490 Clear : for J in 1 .. 10 loop           Clear :
15491    A (J) := 0;                             for J in 1 .. 10 loop
15492 end loop Clear;                               A (J) := 0;
15493                                            end loop Clear;
15494 @end cartouche
15495 @end smallexample
15496 @end ifnottex
15498 @noindent
15499 A further difference between GNAT style layout and compact layout is that
15500 GNAT style layout inserts empty lines as separation for
15501 compound statements, return statements and bodies.
15503 @node Name Casing
15504 @subsection Name Casing
15506 @noindent
15507 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15508 the same casing as the corresponding defining identifier.
15510 You control the casing for defining occurrences via the
15511 @option{^-n^/NAME_CASING^} switch.
15512 @ifclear vms
15513 With @option{-nD} (``as declared'', which is the default),
15514 @end ifclear
15515 @ifset vms
15516 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15517 @end ifset
15518 defining occurrences appear exactly as in the source file
15519 where they are declared.
15520 The other ^values for this switch^options for this qualifier^ ---
15521 @option{^-nU^UPPER_CASE^},
15522 @option{^-nL^LOWER_CASE^},
15523 @option{^-nM^MIXED_CASE^} ---
15524 result in
15525 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15526 If @command{gnatpp} changes the casing of a defining
15527 occurrence, it analogously changes the casing of all the
15528 usage occurrences of this name.
15530 If the defining occurrence of a name is not in the source compilation unit
15531 currently being processed by @command{gnatpp}, the casing of each reference to
15532 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15533 switch (subject to the dictionary file mechanism described below).
15534 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15535 had affected the
15536 casing for the defining occurrence of the name.
15538 Some names may need to be spelled with casing conventions that are not
15539 covered by the upper-, lower-, and mixed-case transformations.
15540 You can arrange correct casing by placing such names in a
15541 @emph{dictionary file},
15542 and then supplying a @option{^-D^/DICTIONARY^} switch.
15543 The casing of names from dictionary files overrides
15544 any @option{^-n^/NAME_CASING^} switch.
15546 To handle the casing of Ada predefined names and the names from GNAT libraries,
15547 @command{gnatpp} assumes a default dictionary file.
15548 The name of each predefined entity is spelled with the same casing as is used
15549 for the entity in the @cite{Ada Reference Manual}.
15550 The name of each entity in the GNAT libraries is spelled with the same casing
15551 as is used in the declaration of that entity.
15553 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15554 default dictionary file.
15555 Instead, the casing for predefined and GNAT-defined names will be established
15556 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15557 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15558 will appear as just shown,
15559 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15560 To ensure that even such names are rendered in uppercase,
15561 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15562 (or else, less conveniently, place these names in upper case in a dictionary
15563 file).
15565 A dictionary file is
15566 a plain text file; each line in this file can be either a blank line
15567 (containing only space characters and ASCII.HT characters), an Ada comment
15568 line, or the specification of exactly one @emph{casing schema}.
15570 A casing schema is a string that has the following syntax:
15572 @smallexample
15573 @cartouche
15574   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15576   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15577 @end cartouche
15578 @end smallexample
15580 @noindent
15581 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15582 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15584 The casing schema string can be followed by white space and/or an Ada-style
15585 comment; any amount of white space is allowed before the string.
15587 If a dictionary file is passed as
15588 @ifclear vms
15589 the value of a @option{-D@var{file}} switch
15590 @end ifclear
15591 @ifset vms
15592 an option to the @option{/DICTIONARY} qualifier
15593 @end ifset
15594 then for every
15595 simple name and every identifier, @command{gnatpp} checks if the dictionary
15596 defines the casing for the name or for some of its parts (the term ``subword''
15597 is used below to denote the part of a name which is delimited by ``_'' or by
15598 the beginning or end of the word and which does not contain any ``_'' inside):
15600 @itemize @bullet
15601 @item
15602 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15603 the casing defined by the dictionary; no subwords are checked for this word
15605 @item
15606 for every subword @command{gnatpp} checks if the dictionary contains the
15607 corresponding string of the form @code{*@var{simple_identifier}*},
15608 and if it does, the casing of this @var{simple_identifier} is used
15609 for this subword
15611 @item
15612 if the whole name does not contain any ``_'' inside, and if for this name
15613 the dictionary contains two entries - one of the form @var{identifier},
15614 and another - of the form *@var{simple_identifier}*, then the first one
15615 is applied to define the casing of this name
15617 @item
15618 if more than one dictionary file is passed as @command{gnatpp} switches, each
15619 dictionary adds new casing exceptions and overrides all the existing casing
15620 exceptions set by the previous dictionaries
15622 @item
15623 when @command{gnatpp} checks if the word or subword is in the dictionary,
15624 this check is not case sensitive
15625 @end itemize
15627 @noindent
15628 For example, suppose we have the following source to reformat:
15630 @smallexample @c ada
15631 @cartouche
15632 procedure test is
15633    name1 : integer := 1;
15634    name4_name3_name2 : integer := 2;
15635    name2_name3_name4 : Boolean;
15636    name1_var : Float;
15637 begin
15638    name2_name3_name4 := name4_name3_name2 > name1;
15639 end;
15640 @end cartouche
15641 @end smallexample
15643 @noindent
15644 And suppose we have two dictionaries:
15646 @smallexample
15647 @cartouche
15648 @i{dict1:}
15649    NAME1
15650    *NaMe3*
15651    *Name1*
15652 @end cartouche
15654 @cartouche
15655 @i{dict2:}
15656   *NAME3*
15657 @end cartouche
15658 @end smallexample
15660 @noindent
15661 If @command{gnatpp} is called with the following switches:
15663 @smallexample
15664 @ifclear vms
15665 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15666 @end ifclear
15667 @ifset vms
15668 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15669 @end ifset
15670 @end smallexample
15672 @noindent
15673 then we will get the following name casing in the @command{gnatpp} output:
15675 @smallexample @c ada
15676 @cartouche
15677 procedure Test is
15678    NAME1             : Integer := 1;
15679    Name4_NAME3_Name2 : Integer := 2;
15680    Name2_NAME3_Name4 : Boolean;
15681    Name1_Var         : Float;
15682 begin
15683    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15684 end Test;
15685 @end cartouche
15686 @end smallexample
15688 @c *********************************
15689 @node The GNAT Metric Tool gnatmetric
15690 @chapter The GNAT Metric Tool @command{gnatmetric}
15691 @findex gnatmetric
15692 @cindex Metric tool
15694 @noindent
15695 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15696 for computing various program metrics.
15697 It takes an Ada source file as input and generates a file containing the
15698 metrics data as output. Various switches control which
15699 metrics are computed and output.
15701 @command{gnatmetric} generates and uses the ASIS
15702 tree for the input source and thus requires the input to be syntactically and
15703 semantically legal.
15704 If this condition is not met, @command{gnatmetric} will generate
15705 an error message; no metric information for this file will be
15706 computed and reported.
15708 If the compilation unit contained in the input source depends semantically
15709 upon units in files located outside the current directory, you have to provide
15710 the source search path when invoking @command{gnatmetric}.
15711 If it depends semantically upon units that are contained
15712 in files with names that do not follow the GNAT file naming rules, you have to
15713 provide the configuration file describing the corresponding naming scheme (see
15714 the description of the @command{gnatmetric} switches below.)
15715 Alternatively, you may use a project file and invoke @command{gnatmetric}
15716 through the @command{gnat} driver.
15719 The @command{gnatmetric} command has the form
15721 @smallexample
15722 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
15723 @end smallexample
15725 @noindent
15726 where
15727 @itemize @bullet
15728 @item
15729 @i{switches} specify the metrics to compute and define the destination for
15730 the output
15732 @item
15733 Each @i{filename} is the name (including the extension) of a source
15734 file to process. ``Wildcards'' are allowed, and
15735 the file name may contain path information.
15736 If no @i{filename} is supplied, then the @i{switches} list must contain
15737 at least one
15738 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15739 Including both a @option{-files} switch and one or more
15740 @i{filename} arguments is permitted.
15742 @item
15743 @i{-cargs gcc_switches} is a list of switches for
15744 @command{gcc}. They will be passed on to all compiler invocations made by
15745 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15746 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15747 and use the @option{-gnatec} switch to set the configuration file.
15748 @end itemize
15750 @menu
15751 * Switches for gnatmetric::
15752 @end menu
15754 @node Switches for gnatmetric
15755 @section Switches for @command{gnatmetric}
15757 @noindent
15758 The following subsections describe the various switches accepted by
15759 @command{gnatmetric}, organized by category.
15761 @menu
15762 * Output Files Control::
15763 * Disable Metrics For Local Units::
15764 * Line Metrics Control::
15765 * Syntax Metrics Control::
15766 * Complexity Metrics Control::
15767 * Other gnatmetric Switches::
15768 @end menu
15770 @node Output Files Control
15771 @subsection Output File Control
15772 @cindex Output file control in @command{gnatmetric}
15774 @noindent
15775 @command{gnatmetric} has two output formats. It can generate a
15776 textual (human-readable) form, and also XML. By default only textual
15777 output is generated.
15779 When generating the output in textual form, @command{gnatmetric} creates
15780 for each Ada source file a corresponding text file
15781 containing the computed metrics. By default, this file
15782 is placed in the same directory as where the source file is located, and
15783 its name is obtained
15784 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15785 input file.
15787 All the output information generated in XML format is placed in a single
15788 file. By default this file is placed in the current directory and has the
15789 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15791 Some of the computed metrics are summed over the units passed to
15792 @command{gnatmetric}; for example, the total number of lines of code.
15793 By default this information is sent to @file{stdout}, but a file
15794 can be specified with the @option{-og} switch.
15796 The following switches control the @command{gnatmetric} output:
15798 @table @option
15799 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15800 @item ^-x^/XML^
15801 Generate the XML output
15803 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15804 @item ^-nt^/NO_TEXT^
15805 Do not generate the output in text form (implies @option{^-x^/XML^})
15807 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15808 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15809 Put textual files with detailed metrics into @var{output_dir}
15811 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15812 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15813 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15814 in the name of the output file.
15816 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15817 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15818 Put global metrics into @var{file_name}
15820 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15821 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15822 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15824 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15825 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15826 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15827 output includes the name(s) of the Ada source file(s) from which the metrics
15828 are computed.  By default each name includes the absolute path. The
15829 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15830 to exclude all directory information from the file names that are output.)
15832 @end table
15834 @node Disable Metrics For Local Units
15835 @subsection Disable Metrics For Local Units
15836 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15838 @noindent
15839 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15840 one compilation
15841 unit per one source file. It computes line metrics for the whole source
15842 file, and it also computes syntax
15843 and complexity metrics for the file's outermost unit.
15845 By default, @command{gnatmetric} will also compute all metrics for certain
15846 kinds of locally declared program units:
15848 @itemize @bullet
15849 @item
15850 subprogram (and generic subprogram) bodies;
15852 @item
15853 package (and generic package) specifications and bodies;
15855 @item
15856 task object and type specifications and bodies;
15858 @item
15859 protected object and type specifications and bodies.
15860 @end itemize
15862 @noindent
15863 These kinds of entities will be referred to as
15864 @emph{eligible local program units}, or simply @emph{eligible local units},
15865 @cindex Eligible local unit (for @command{gnatmetric})
15866 in the discussion below.
15868 Note that a subprogram declaration, generic instantiation,
15869 or renaming declaration only receives metrics
15870 computation when it appear as the outermost entity
15871 in a source file.
15873 Suppression of metrics computation for eligible local units can be
15874 obtained via the following switch:
15876 @table @option
15877 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15878 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15879 Do not compute detailed metrics for eligible local program units
15881 @end table
15883 @node Line Metrics Control
15884 @subsection Line Metrics Control
15885 @cindex Line metrics control in @command{gnatmetric}
15887 @noindent
15888 For any (legal) source file, and for each of its
15889 eligible local program units, @command{gnatmetric} computes the following
15890 metrics:
15892 @itemize @bullet
15893 @item
15894 the total number of lines;
15896 @item
15897 the total number of code lines (i.e., non-blank lines that are not comments)
15899 @item
15900 the number of comment lines
15902 @item
15903 the number of code lines containing end-of-line comments;
15905 @item
15906 the number of empty lines and lines containing only space characters and/or
15907 format effectors (blank lines)
15909 @end itemize
15911 If @command{gnatmetric} is invoked on more than one source file, it sums the
15912 values of the line metrics for all the files being processed and then
15913 generates the cumulative results.
15915 By default, all the line metrics are computed and reported. You can use the
15916 following switches to select the specific line metrics to be computed and
15917 reported (if any of these parameters is set, only explicitly specified line
15918 metrics are computed).
15920 @table @option
15921 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15922 @item ^-la^/LINES_ALL^
15923 The number of all lines
15925 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15926 @item ^-lcode^/CODE_LINES^
15927 The number of code lines
15929 @cindex @option{^-lcomm^/COMENT_LINES^} (@command{gnatmetric})
15930 @item ^-lcomm^/COMENT_LINES^
15931 The number of comment lines
15933 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15934 @item ^-leol^/MIXED_CODE_COMMENTS^
15935 The number of code lines containing
15936 end-of-line comments
15938 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
15939 @item ^-lb^/BLANK_LINES^
15940 The number of blank lines
15942 @end table
15945 @node Syntax Metrics Control
15946 @subsection Syntax Metrics Control
15947 @cindex Syntax metrics control in @command{gnatmetric}
15949 @noindent
15950 @command{gnatmetric} computes various syntactic metrics for the
15951 outermost unit and for each eligible local unit:
15953 @table @emph
15954 @item LSLOC (``Logical Source Lines Of Code'')
15955 The total number of declarations and the total number of statements
15957 @item Maximal static nesting level of inner program units
15958 According to
15959 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
15960 package, a task unit, a protected unit, a
15961 protected entry, a generic unit, or an explicitly declared subprogram other
15962 than an enumeration literal.''
15964 @item Maximal nesting level of composite syntactic constructs
15965 This corresponds to the notion of the
15966 maximum nesting level in the GNAT built-in style checks
15967 (@pxref{Style Checking})
15968 @end table
15970 @noindent
15971 For the outermost unit in the file, @command{gnatmetric} additionally computes
15972 the following metrics:
15974 @table @emph
15975 @item Public subprograms
15976 This metric is computed for package specifications. It is the
15977 number of subprograms and generic subprograms declared in the visible
15978 part (including in nested packages, protected objects, and
15979 protected types).
15981 @item All subprograms
15982 This metric is computed for bodies and subunits. The
15983 metric is equal to a total number of subprogram bodies in the compilation
15984 unit.
15985 Neither generic instantiations nor renamings-as-a-body nor body stubs
15986 are counted. Any subprogram body is counted, independently of its nesting
15987 level and enclosing constructs. Generic bodies and bodies of protected
15988 subprograms are counted in the same way as ``usual'' subprogram bodies.
15990 @item Public types
15991 This metric is computed for package specifications and
15992 generic package declarations. It is the total number of types
15993 that can be referenced from outside this compilation unit, plus the
15994 number of types from all the visible parts of all the visible generic packages.
15995 Generic formal types are not counted.  Only types, not subtypes,
15996 are included.
15998 @noindent
15999 Along with the total number of public types, the following
16000 types are counted and reported separately:
16002 @itemize @bullet
16003 @item
16004 Abstract types
16006 @item
16007 Root tagged types (abstract, non-abstract, private, non-private). Type
16008 extensions are @emph{not} counted
16010 @item
16011 Private types (including private extensions)
16013 @item
16014 Task types
16016 @item
16017 Protected types
16019 @end itemize
16021 @item All types
16022 This metric is computed for any compilation unit. It is equal to the total
16023 number of the declarations of different types given in the compilation unit.
16024 The private and the corresponding full type declaration are counted as one
16025 type declaration. Incomplete type declarations and generic formal types
16026 are not counted.
16027 No distinction is made among different kinds of types (abstract,
16028 private etc.); the total number of types is computed and reported.
16030 @end table
16032 @noindent
16033 By default, all the syntax metrics are computed and reported. You can use the
16034 following switches to select specific syntax metrics;
16035 if any of these is set, only the explicitly specified metrics are computed.
16037 @table @option
16038 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
16039 @item ^-ed^/DECLARATION_TOTAL^
16040 The total number of declarations
16042 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
16043 @item ^-es^/STATEMENT_TOTAL^
16044 The total number of statements
16046 @cindex @option{^-eps^/^} (@command{gnatmetric})
16047 @item ^-eps^/INT_SUBPROGRAMS^
16048 The number of public subprograms in a compilation unit
16050 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
16051 @item ^-eas^/SUBPROGRAMS_ALL^
16052 The number of all the subprograms in a compilation unit
16054 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
16055 @item ^-ept^/INT_TYPES^
16056 The number of public types in a compilation unit
16058 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
16059 @item ^-eat^/TYPES_ALL^
16060 The number of all the types in a compilation unit
16062 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
16063 @item ^-enu^/PROGRAM_NESTING_MAX^
16064 The maximal program unit nesting level
16066 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
16067 @item ^-ec^/CONSTRUCT_NESTING_MAX^
16068 The maximal construct nesting level
16070 @end table
16072 @node Complexity Metrics Control
16073 @subsection Complexity Metrics Control
16074 @cindex Complexity metrics control in @command{gnatmetric}
16076 @noindent
16077 For a program unit that is an executable body (a subprogram body (including
16078 generic bodies), task body, entry body or a package body containing
16079 its own statement sequence ) @command{gnatmetric} computes the following
16080 complexity metrics:
16082 @itemize @bullet
16083 @item
16084 McCabe cyclomatic complexity;
16086 @item
16087 McCabe essential complexity;
16089 @item
16090 maximal loop nesting level
16092 @end itemize
16094 @noindent
16095 The McCabe complexity metrics are defined
16096 in @url{www.mccabe.com/pdf/nist235r.pdf}
16098 According to McCabe, both control statements and short-circuit control forms
16099 should be taken into account when computing cyclomatic complexity. For each
16100 body, we compute three metric values:
16102 @itemize @bullet
16103 @item
16104 the complexity introduced by control
16105 statements only, without taking into account short-circuit forms,
16107 @item
16108 the complexity introduced by short-circuit control forms only, and
16110 @item
16111 the total
16112 cyclomatic complexity, which is the sum of these two values.
16113 @end itemize
16115 @noindent
16116 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16117 the code in the exception handlers and in all the nested program units.
16119 By default, all the complexity metrics are computed and reported.
16120 For more finely-grained control you can use
16121 the following switches:
16123 @table @option
16124 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16126 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
16127 Do not compute the McCabe Cyclomatic Complexity
16129 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
16130 Do not compute the Essential Complexity
16132 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
16133 Do not compute maximal loop nesting level
16135 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
16136 Do not consider @code{exit} statements as @code{goto}s when
16137 computing Essential Complexity
16139 @end table
16141 @node Other gnatmetric Switches
16142 @subsection Other @code{gnatmetric} Switches
16144 @noindent
16145 Additional @command{gnatmetric} switches are as follows:
16147 @table @option
16148 @item ^-files @var{filename}^/FILES=@var{filename}^
16149 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16150 Take the argument source files from the specified file. This file should be an
16151 ordinary textual file containing file names separated by spaces or
16152 line breaks. You can use this switch more then once in the same call to
16153 @command{gnatmetric}. You also can combine this switch with
16154 an explicit list of files.
16156 @item ^-v^/VERBOSE^
16157 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16158 Verbose mode;
16159 @command{gnatmetric} generates version information and then
16160 a trace of sources being processed.
16162 @item ^-dv^/DEBUG_OUTPUT^
16163 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16164 Debug mode;
16165 @command{gnatmetric} generates various messages useful to understand what
16166 happens during the metrics computation
16168 @item ^-q^/QUIET^
16169 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16170 Quiet mode.
16171 @end table
16173 @c ***********************************
16174 @node File Name Krunching Using gnatkr
16175 @chapter File Name Krunching Using @code{gnatkr}
16176 @findex gnatkr
16178 @noindent
16179 This chapter discusses the method used by the compiler to shorten
16180 the default file names chosen for Ada units so that they do not
16181 exceed the maximum length permitted. It also describes the
16182 @code{gnatkr} utility that can be used to determine the result of
16183 applying this shortening.
16184 @menu
16185 * About gnatkr::
16186 * Using gnatkr::
16187 * Krunching Method::
16188 * Examples of gnatkr Usage::
16189 @end menu
16191 @node About gnatkr
16192 @section About @code{gnatkr}
16194 @noindent
16195 The default file naming rule in GNAT
16196 is that the file name must be derived from
16197 the unit name. The exact default rule is as follows:
16198 @itemize @bullet
16199 @item
16200 Take the unit name and replace all dots by hyphens.
16201 @item
16202 If such a replacement occurs in the
16203 second character position of a name, and the first character is
16204 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16205 ^~ (tilde)^$ (dollar sign)^
16206 instead of a minus.
16207 @end itemize
16208 The reason for this exception is to avoid clashes
16209 with the standard names for children of System, Ada, Interfaces,
16210 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16211 respectively.
16213 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16214 switch of the compiler activates a ``krunching''
16215 circuit that limits file names to nn characters (where nn is a decimal
16216 integer). For example, using OpenVMS,
16217 where the maximum file name length is
16218 39, the value of nn is usually set to 39, but if you want to generate
16219 a set of files that would be usable if ported to a system with some
16220 different maximum file length, then a different value can be specified.
16221 The default value of 39 for OpenVMS need not be specified.
16223 The @code{gnatkr} utility can be used to determine the krunched name for
16224 a given file, when krunched to a specified maximum length.
16226 @node Using gnatkr
16227 @section Using @code{gnatkr}
16229 @noindent
16230 The @code{gnatkr} command has the form
16232 @ifclear vms
16233 @smallexample
16234 $ gnatkr @var{name} [@var{length}]
16235 @end smallexample
16236 @end ifclear
16238 @ifset vms
16239 @smallexample
16240 $ gnatkr @var{name} /COUNT=nn
16241 @end smallexample
16242 @end ifset
16244 @noindent
16245 @var{name} is the uncrunched file name, derived from the name of the unit
16246 in the standard manner described in the previous section (i.e. in particular
16247 all dots are replaced by hyphens). The file name may or may not have an
16248 extension (defined as a suffix of the form period followed by arbitrary
16249 characters other than period). If an extension is present then it will
16250 be preserved in the output. For example, when krunching @file{hellofile.ads}
16251 to eight characters, the result will be hellofil.ads.
16253 Note: for compatibility with previous versions of @code{gnatkr} dots may
16254 appear in the name instead of hyphens, but the last dot will always be
16255 taken as the start of an extension. So if @code{gnatkr} is given an argument
16256 such as @file{Hello.World.adb} it will be treated exactly as if the first
16257 period had been a hyphen, and for example krunching to eight characters
16258 gives the result @file{hellworl.adb}.
16260 Note that the result is always all lower case (except on OpenVMS where it is
16261 all upper case). Characters of the other case are folded as required.
16263 @var{length} represents the length of the krunched name. The default
16264 when no argument is given is ^8^39^ characters. A length of zero stands for
16265 unlimited, in other words do not chop except for system files where the
16266 implied crunching length is always eight characters.
16268 @noindent
16269 The output is the krunched name. The output has an extension only if the
16270 original argument was a file name with an extension.
16272 @node Krunching Method
16273 @section Krunching Method
16275 @noindent
16276 The initial file name is determined by the name of the unit that the file
16277 contains. The name is formed by taking the full expanded name of the
16278 unit and replacing the separating dots with hyphens and
16279 using ^lowercase^uppercase^
16280 for all letters, except that a hyphen in the second character position is
16281 replaced by a ^tilde^dollar sign^ if the first character is
16282 ^a, i, g, or s^A, I, G, or S^.
16283 The extension is @code{.ads} for a
16284 specification and @code{.adb} for a body.
16285 Krunching does not affect the extension, but the file name is shortened to
16286 the specified length by following these rules:
16288 @itemize @bullet
16289 @item
16290 The name is divided into segments separated by hyphens, tildes or
16291 underscores and all hyphens, tildes, and underscores are
16292 eliminated. If this leaves the name short enough, we are done.
16294 @item
16295 If the name is too long, the longest segment is located (left-most
16296 if there are two of equal length), and shortened by dropping
16297 its last character. This is repeated until the name is short enough.
16299 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16300 to fit the name into 8 characters as required by some operating systems.
16302 @smallexample
16303 our-strings-wide_fixed 22
16304 our strings wide fixed 19
16305 our string  wide fixed 18
16306 our strin   wide fixed 17
16307 our stri    wide fixed 16
16308 our stri    wide fixe  15
16309 our str     wide fixe  14
16310 our str     wid  fixe  13
16311 our str     wid  fix   12
16312 ou  str     wid  fix   11
16313 ou  st      wid  fix   10
16314 ou  st      wi   fix   9
16315 ou  st      wi   fi    8
16316 Final file name: oustwifi.adb
16317 @end smallexample
16319 @item
16320 The file names for all predefined units are always krunched to eight
16321 characters. The krunching of these predefined units uses the following
16322 special prefix replacements:
16324 @table @file
16325 @item ada-
16326 replaced by @file{^a^A^-}
16328 @item gnat-
16329 replaced by @file{^g^G^-}
16331 @item interfaces-
16332 replaced by @file{^i^I^-}
16334 @item system-
16335 replaced by @file{^s^S^-}
16336 @end table
16338 These system files have a hyphen in the second character position. That
16339 is why normal user files replace such a character with a
16340 ^tilde^dollar sign^, to
16341 avoid confusion with system file names.
16343 As an example of this special rule, consider
16344 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16346 @smallexample
16347 ada-strings-wide_fixed 22
16348 a-  strings wide fixed 18
16349 a-  string  wide fixed 17
16350 a-  strin   wide fixed 16
16351 a-  stri    wide fixed 15
16352 a-  stri    wide fixe  14
16353 a-  str     wide fixe  13
16354 a-  str     wid  fixe  12
16355 a-  str     wid  fix   11
16356 a-  st      wid  fix   10
16357 a-  st      wi   fix   9
16358 a-  st      wi   fi    8
16359 Final file name: a-stwifi.adb
16360 @end smallexample
16361 @end itemize
16363 Of course no file shortening algorithm can guarantee uniqueness over all
16364 possible unit names, and if file name krunching is used then it is your
16365 responsibility to ensure that no name clashes occur. The utility
16366 program @code{gnatkr} is supplied for conveniently determining the
16367 krunched name of a file.
16369 @node Examples of gnatkr Usage
16370 @section Examples of @code{gnatkr} Usage
16372 @smallexample
16373 @iftex
16374 @leftskip=0cm
16375 @end iftex
16376 @ifclear vms
16377 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16378 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16379 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16380 $ gnatkr grandparent-parent-child     --> grparchi
16381 @end ifclear
16382 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16383 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16384 @end smallexample
16386 @node Preprocessing Using gnatprep
16387 @chapter Preprocessing Using @code{gnatprep}
16388 @findex gnatprep
16390 @noindent
16391 The @code{gnatprep} utility provides
16392 a simple preprocessing capability for Ada programs.
16393 It is designed for use with GNAT, but is not dependent on any special
16394 features of GNAT.
16396 @menu
16397 * Using gnatprep::
16398 * Switches for gnatprep::
16399 * Form of Definitions File::
16400 * Form of Input Text for gnatprep::
16401 @end menu
16403 @node Using gnatprep
16404 @section Using @code{gnatprep}
16406 @noindent
16407 To call @code{gnatprep} use
16409 @smallexample
16410 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
16411 @end smallexample
16413 @noindent
16414 where
16415 @table @code
16416 @item infile
16417 is the full name of the input file, which is an Ada source
16418 file containing preprocessor directives.
16420 @item outfile
16421 is the full name of the output file, which is an Ada source
16422 in standard Ada form. When used with GNAT, this file name will
16423 normally have an ads or adb suffix.
16425 @item deffile
16426 is the full name of a text file containing definitions of
16427 symbols to be referenced by the preprocessor. This argument is
16428 optional, and can be replaced by the use of the @option{-D} switch.
16430 @item switches
16431 is an optional sequence of switches as described in the next section.
16432 @end table
16434 @node Switches for gnatprep
16435 @section Switches for @code{gnatprep}
16437 @table @option
16438 @c !sort!
16440 @item ^-b^/BLANK_LINES^
16441 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16442 Causes both preprocessor lines and the lines deleted by
16443 preprocessing to be replaced by blank lines in the output source file,
16444 preserving line numbers in the output file.
16446 @item ^-c^/COMMENTS^
16447 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16448 Causes both preprocessor lines and the lines deleted
16449 by preprocessing to be retained in the output source as comments marked
16450 with the special string @code{"--! "}. This option will result in line numbers
16451 being preserved in the output file.
16453 @item ^-C^/REPLACE_IN_COMMENTS^
16454 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16455 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16456 If this option is specified, then comments are scanned and any $symbol
16457 substitutions performed as in program text. This is particularly useful
16458 when structured comments are used (e.g. when writing programs in the
16459 SPARK dialect of Ada). Note that this switch is not available when
16460 doing integrated preprocessing (it would be useless in this context
16461 since comments are ignored by the compiler in any case).
16463 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16464 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16465 Defines a new symbol, associated with value. If no value is given on the
16466 command line, then symbol is considered to be @code{True}. This switch
16467 can be used in place of a definition file.
16469 @ifset vms
16470 @item /REMOVE
16471 @cindex @option{/REMOVE} (@command{gnatprep})
16472 This is the default setting which causes lines deleted by preprocessing
16473 to be entirely removed from the output file.
16474 @end ifset
16476 @item ^-r^/REFERENCE^
16477 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16478 Causes a @code{Source_Reference} pragma to be generated that
16479 references the original input file, so that error messages will use
16480 the file name of this original file. The use of this switch implies
16481 that preprocessor lines are not to be removed from the file, so its
16482 use will force @option{^-b^/BLANK_LINES^} mode if
16483 @option{^-c^/COMMENTS^}
16484 has not been specified explicitly.
16486 Note that if the file to be preprocessed contains multiple units, then
16487 it will be necessary to @code{gnatchop} the output file from
16488 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16489 in the preprocessed file, it will be respected by
16490 @code{gnatchop ^-r^/REFERENCE^}
16491 so that the final chopped files will correctly refer to the original
16492 input source file for @code{gnatprep}.
16494 @item ^-s^/SYMBOLS^
16495 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16496 Causes a sorted list of symbol names and values to be
16497 listed on the standard output file.
16499 @item ^-u^/UNDEFINED^
16500 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16501 Causes undefined symbols to be treated as having the value FALSE in the context
16502 of a preprocessor test. In the absence of this option, an undefined symbol in
16503 a @code{#if} or @code{#elsif} test will be treated as an error.
16505 @end table
16507 @ifclear vms
16508 @noindent
16509 Note: if neither @option{-b} nor @option{-c} is present,
16510 then preprocessor lines and
16511 deleted lines are completely removed from the output, unless -r is
16512 specified, in which case -b is assumed.
16513 @end ifclear
16515 @node Form of Definitions File
16516 @section Form of Definitions File
16518 @noindent
16519 The definitions file contains lines of the form
16521 @smallexample
16522 symbol := value
16523 @end smallexample
16525 @noindent
16526 where symbol is an identifier, following normal Ada (case-insensitive)
16527 rules for its syntax, and value is one of the following:
16529 @itemize @bullet
16530 @item
16531 Empty, corresponding to a null substitution
16532 @item
16533 A string literal using normal Ada syntax
16534 @item
16535 Any sequence of characters from the set
16536 (letters, digits, period, underline).
16537 @end itemize
16539 @noindent
16540 Comment lines may also appear in the definitions file, starting with
16541 the usual @code{--},
16542 and comments may be added to the definitions lines.
16544 @node Form of Input Text for gnatprep
16545 @section Form of Input Text for @code{gnatprep}
16547 @noindent
16548 The input text may contain preprocessor conditional inclusion lines,
16549 as well as general symbol substitution sequences.
16551 The preprocessor conditional inclusion commands have the form
16553 @smallexample
16554 @group
16555 @cartouche
16556 #if @i{expression} [then]
16557    lines
16558 #elsif @i{expression} [then]
16559    lines
16560 #elsif @i{expression} [then]
16561    lines
16563 #else
16564    lines
16565 #end if;
16566 @end cartouche
16567 @end group
16568 @end smallexample
16570 @noindent
16571 In this example, @i{expression} is defined by the following grammar:
16572 @smallexample
16573 @i{expression} ::=  <symbol>
16574 @i{expression} ::=  <symbol> = "<value>"
16575 @i{expression} ::=  <symbol> = <symbol>
16576 @i{expression} ::=  <symbol> 'Defined
16577 @i{expression} ::=  not @i{expression}
16578 @i{expression} ::=  @i{expression} and @i{expression}
16579 @i{expression} ::=  @i{expression} or @i{expression}
16580 @i{expression} ::=  @i{expression} and then @i{expression}
16581 @i{expression} ::=  @i{expression} or else @i{expression}
16582 @i{expression} ::=  ( @i{expression} )
16583 @end smallexample
16585 @noindent
16586 For the first test (@i{expression} ::= <symbol>) the symbol must have
16587 either the value true or false, that is to say the right-hand of the
16588 symbol definition must be one of the (case-insensitive) literals
16589 @code{True} or @code{False}. If the value is true, then the
16590 corresponding lines are included, and if the value is false, they are
16591 excluded.
16593 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16594 the symbol has been defined in the definition file or by a @option{-D}
16595 switch on the command line. Otherwise, the test is false.
16597 The equality tests are case insensitive, as are all the preprocessor lines.
16599 If the symbol referenced is not defined in the symbol definitions file,
16600 then the effect depends on whether or not switch @option{-u}
16601 is specified. If so, then the symbol is treated as if it had the value
16602 false and the test fails. If this switch is not specified, then
16603 it is an error to reference an undefined symbol. It is also an error to
16604 reference a symbol that is defined with a value other than @code{True}
16605 or @code{False}.
16607 The use of the @code{not} operator inverts the sense of this logical test, so
16608 that the lines are included only if the symbol is not defined.
16609 The @code{then} keyword is optional as shown
16611 The @code{#} must be the first non-blank character on a line, but
16612 otherwise the format is free form. Spaces or tabs may appear between
16613 the @code{#} and the keyword. The keywords and the symbols are case
16614 insensitive as in normal Ada code. Comments may be used on a
16615 preprocessor line, but other than that, no other tokens may appear on a
16616 preprocessor line. Any number of @code{elsif} clauses can be present,
16617 including none at all. The @code{else} is optional, as in Ada.
16619 The @code{#} marking the start of a preprocessor line must be the first
16620 non-blank character on the line, i.e. it must be preceded only by
16621 spaces or horizontal tabs.
16623 Symbol substitution outside of preprocessor lines is obtained by using
16624 the sequence
16626 @smallexample
16627 $symbol
16628 @end smallexample
16630 @noindent
16631 anywhere within a source line, except in a comment or within a
16632 string literal. The identifier
16633 following the @code{$} must match one of the symbols defined in the symbol
16634 definition file, and the result is to substitute the value of the
16635 symbol in place of @code{$symbol} in the output file.
16637 Note that although the substitution of strings within a string literal
16638 is not possible, it is possible to have a symbol whose defined value is
16639 a string literal. So instead of setting XYZ to @code{hello} and writing:
16641 @smallexample
16642 Header : String := "$XYZ";
16643 @end smallexample
16645 @noindent
16646 you should set XYZ to @code{"hello"} and write:
16648 @smallexample
16649 Header : String := $XYZ;
16650 @end smallexample
16652 @noindent
16653 and then the substitution will occur as desired.
16655 @ifset vms
16656 @node The GNAT Run-Time Library Builder gnatlbr
16657 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16658 @findex gnatlbr
16659 @cindex Library builder
16661 @noindent
16662 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16663 supplied configuration pragmas.
16665 @menu
16666 * Running gnatlbr::
16667 * Switches for gnatlbr::
16668 * Examples of gnatlbr Usage::
16669 @end menu
16671 @node Running gnatlbr
16672 @section Running @code{gnatlbr}
16674 @noindent
16675 The @code{gnatlbr} command has the form
16677 @smallexample
16678 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16679 @end smallexample
16681 @node Switches for gnatlbr
16682 @section Switches for @code{gnatlbr}
16684 @noindent
16685 @code{gnatlbr} recognizes the following switches:
16687 @table @option
16688 @c !sort!
16689 @item /CREATE=directory
16690 @cindex @code{/CREATE} (@code{gnatlbr})
16691      Create the new run-time library in the specified directory.
16693 @item /SET=directory
16694 @cindex @code{/SET} (@code{gnatlbr})
16695      Make the library in the specified directory the current run-time
16696      library.
16698 @item /DELETE=directory
16699 @cindex @code{/DELETE} (@code{gnatlbr})
16700      Delete the run-time library in the specified directory.
16702 @item /CONFIG=file
16703 @cindex @code{/CONFIG} (@code{gnatlbr})
16704      With /CREATE:
16705      Use the configuration pragmas in the specified file when building
16706      the library.
16708      With /SET:
16709      Use the configuration pragmas in the specified file when compiling.
16711 @end table
16713 @node Examples of gnatlbr Usage
16714 @section Example of @code{gnatlbr} Usage
16716 @smallexample
16717 Contents of VAXFLOAT.ADC:
16718 pragma Float_Representation (VAX_Float);
16720 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16722 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16724 @end smallexample
16725 @end ifset
16727 @node The GNAT Library Browser gnatls
16728 @chapter The GNAT Library Browser @code{gnatls}
16729 @findex gnatls
16730 @cindex Library browser
16732 @noindent
16733 @code{gnatls} is a tool that outputs information about compiled
16734 units. It gives the relationship between objects, unit names and source
16735 files. It can also be used to check the source dependencies of a unit
16736 as well as various characteristics.
16738 @menu
16739 * Running gnatls::
16740 * Switches for gnatls::
16741 * Examples of gnatls Usage::
16742 @end menu
16744 @node Running gnatls
16745 @section Running @code{gnatls}
16747 @noindent
16748 The @code{gnatls} command has the form
16750 @smallexample
16751 $ gnatls switches @var{object_or_ali_file}
16752 @end smallexample
16754 @noindent
16755 The main argument is the list of object or @file{ali} files
16756 (@pxref{The Ada Library Information Files})
16757 for which information is requested.
16759 In normal mode, without additional option, @code{gnatls} produces a
16760 four-column listing. Each line represents information for a specific
16761 object. The first column gives the full path of the object, the second
16762 column gives the name of the principal unit in this object, the third
16763 column gives the status of the source and the fourth column gives the
16764 full path of the source representing this unit.
16765 Here is a simple example of use:
16767 @smallexample
16768 $ gnatls *.o
16769 ^./^[]^demo1.o            demo1            DIF demo1.adb
16770 ^./^[]^demo2.o            demo2             OK demo2.adb
16771 ^./^[]^hello.o            h1                OK hello.adb
16772 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16773 ^./^[]^instr.o            instr             OK instr.adb
16774 ^./^[]^tef.o              tef              DIF tef.adb
16775 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16776 ^./^[]^tgef.o             tgef             DIF tgef.adb
16777 @end smallexample
16779 @noindent
16780 The first line can be interpreted as follows: the main unit which is
16781 contained in
16782 object file @file{demo1.o} is demo1, whose main source is in
16783 @file{demo1.adb}. Furthermore, the version of the source used for the
16784 compilation of demo1 has been modified (DIF). Each source file has a status
16785 qualifier which can be:
16787 @table @code
16788 @item OK (unchanged)
16789 The version of the source file used for the compilation of the
16790 specified unit corresponds exactly to the actual source file.
16792 @item MOK (slightly modified)
16793 The version of the source file used for the compilation of the
16794 specified unit differs from the actual source file but not enough to
16795 require recompilation. If you use gnatmake with the qualifier
16796 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16797 MOK will not be recompiled.
16799 @item DIF (modified)
16800 No version of the source found on the path corresponds to the source
16801 used to build this object.
16803 @item ??? (file not found)
16804 No source file was found for this unit.
16806 @item HID (hidden,  unchanged version not first on PATH)
16807 The version of the source that corresponds exactly to the source used
16808 for compilation has been found on the path but it is hidden by another
16809 version of the same source that has been modified.
16811 @end table
16813 @node Switches for gnatls
16814 @section Switches for @code{gnatls}
16816 @noindent
16817 @code{gnatls} recognizes the following switches:
16819 @table @option
16820 @c !sort!
16821 @item ^-a^/ALL_UNITS^
16822 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16823 Consider all units, including those of the predefined Ada library.
16824 Especially useful with @option{^-d^/DEPENDENCIES^}.
16826 @item ^-d^/DEPENDENCIES^
16827 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16828 List sources from which specified units depend on.
16830 @item ^-h^/OUTPUT=OPTIONS^
16831 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16832 Output the list of options.
16834 @item ^-o^/OUTPUT=OBJECTS^
16835 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16836 Only output information about object files.
16838 @item ^-s^/OUTPUT=SOURCES^
16839 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16840 Only output information about source files.
16842 @item ^-u^/OUTPUT=UNITS^
16843 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16844 Only output information about compilation units.
16846 @item ^-files^/FILES^=@var{file}
16847 @cindex @option{^-files^/FILES^} (@code{gnatls})
16848 Take as arguments the files listed in text file @var{file}.
16849 Text file @var{file} may contain empty lines that are ignored.
16850 Each non empty line should contain the name of an existing file.
16851 Several such switches may be specified simultaneously.
16853 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16854 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16855 @itemx ^-I^/SEARCH=^@var{dir}
16856 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16857 @itemx -nostdinc
16858 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16859 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16860 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16861 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16862 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16863 flags (@pxref{Switches for gnatmake}).
16865 @item --RTS=@var{rts-path}
16866 @cindex @option{--RTS} (@code{gnatls})
16867 Specifies the default location of the runtime library. Same meaning as the
16868 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16870 @item ^-v^/OUTPUT=VERBOSE^
16871 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16872 Verbose mode. Output the complete source, object and project paths. Do not use
16873 the default column layout but instead use long format giving as much as
16874 information possible on each requested units, including special
16875 characteristics such as:
16877 @table @code
16878 @item  Preelaborable
16879 The unit is preelaborable in the Ada 95 sense.
16881 @item No_Elab_Code
16882 No elaboration code has been produced by the compiler for this unit.
16884 @item Pure
16885 The unit is pure in the Ada 95 sense.
16887 @item Elaborate_Body
16888 The unit contains a pragma Elaborate_Body.
16890 @item Remote_Types
16891 The unit contains a pragma Remote_Types.
16893 @item Shared_Passive
16894 The unit contains a pragma Shared_Passive.
16896 @item Predefined
16897 This unit is part of the predefined environment and cannot be modified
16898 by the user.
16900 @item Remote_Call_Interface
16901 The unit contains a pragma Remote_Call_Interface.
16903 @end table
16905 @end table
16907 @node Examples of gnatls Usage
16908 @section Example of @code{gnatls} Usage
16909 @ifclear vms
16911 @noindent
16912 Example of using the verbose switch. Note how the source and
16913 object paths are affected by the -I switch.
16915 @smallexample
16916 $ gnatls -v -I.. demo1.o
16918 GNATLS 5.03w (20041123-34)
16919 Copyright 1997-2004 Free Software Foundation, Inc.
16921 Source Search Path:
16922    <Current_Directory>
16923    ../
16924    /home/comar/local/adainclude/
16926 Object Search Path:
16927    <Current_Directory>
16928    ../
16929    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16931 Project Search Path:
16932    <Current_Directory>
16933    /home/comar/local/lib/gnat/
16935 ./demo1.o
16936    Unit =>
16937      Name   => demo1
16938      Kind   => subprogram body
16939      Flags  => No_Elab_Code
16940      Source => demo1.adb    modified
16941 @end smallexample
16943 @noindent
16944 The following is an example of use of the dependency list.
16945 Note the use of the -s switch
16946 which gives a straight list of source files. This can be useful for
16947 building specialized scripts.
16949 @smallexample
16950 $ gnatls -d demo2.o
16951 ./demo2.o   demo2        OK demo2.adb
16952                          OK gen_list.ads
16953                          OK gen_list.adb
16954                          OK instr.ads
16955                          OK instr-child.ads
16957 $ gnatls -d -s -a demo1.o
16958 demo1.adb
16959 /home/comar/local/adainclude/ada.ads
16960 /home/comar/local/adainclude/a-finali.ads
16961 /home/comar/local/adainclude/a-filico.ads
16962 /home/comar/local/adainclude/a-stream.ads
16963 /home/comar/local/adainclude/a-tags.ads
16964 gen_list.ads
16965 gen_list.adb
16966 /home/comar/local/adainclude/gnat.ads
16967 /home/comar/local/adainclude/g-io.ads
16968 instr.ads
16969 /home/comar/local/adainclude/system.ads
16970 /home/comar/local/adainclude/s-exctab.ads
16971 /home/comar/local/adainclude/s-finimp.ads
16972 /home/comar/local/adainclude/s-finroo.ads
16973 /home/comar/local/adainclude/s-secsta.ads
16974 /home/comar/local/adainclude/s-stalib.ads
16975 /home/comar/local/adainclude/s-stoele.ads
16976 /home/comar/local/adainclude/s-stratt.ads
16977 /home/comar/local/adainclude/s-tasoli.ads
16978 /home/comar/local/adainclude/s-unstyp.ads
16979 /home/comar/local/adainclude/unchconv.ads
16980 @end smallexample
16981 @end ifclear
16983 @ifset vms
16984 @smallexample
16985 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16987 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16988 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16989 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16990 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16991 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16992 demo1.adb
16993 gen_list.ads
16994 gen_list.adb
16995 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16996 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16997 instr.ads
16998 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16999 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17000 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17001 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17002 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17003 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17004 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17005 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17006 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17007 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17008 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17009 @end smallexample
17010 @end ifset
17012 @node Cleaning Up Using gnatclean
17013 @chapter Cleaning Up Using @code{gnatclean}
17014 @findex gnatclean
17015 @cindex Cleaning tool
17017 @noindent
17018 @code{gnatclean} is a tool that allows the deletion of files produced by the
17019 compiler, binder and linker, including ALI files, object files, tree files,
17020 expanded source files, library files, interface copy source files, binder
17021 generated files and executable files.
17023 @menu
17024 * Running gnatclean::
17025 * Switches for gnatclean::
17026 @c * Examples of gnatclean Usage::
17027 @end menu
17029 @node Running gnatclean
17030 @section Running @code{gnatclean}
17032 @noindent
17033 The @code{gnatclean} command has the form:
17035 @smallexample
17036 $ gnatclean switches @var{names}
17037 @end smallexample
17039 @noindent
17040 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17041 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17042 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17044 @noindent
17045 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17046 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17047 the linker. In informative-only mode, specified by switch
17048 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17049 normal mode is listed, but no file is actually deleted.
17051 @node Switches for gnatclean
17052 @section Switches for @code{gnatclean}
17054 @noindent
17055 @code{gnatclean} recognizes the following switches:
17057 @table @option
17058 @c !sort!
17059 @item ^-c^/COMPILER_FILES_ONLY^
17060 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17061 Only attempt to delete the files produced by the compiler, not those produced
17062 by the binder or the linker. The files that are not to be deleted are library
17063 files, interface copy files, binder generated files and executable files.
17065 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17066 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17067 Indicate that ALI and object files should normally be found in directory
17068 @var{dir}.
17070 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17071 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17072 When using project files, if some errors or warnings are detected during
17073 parsing and verbose mode is not in effect (no use of switch
17074 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17075 file, rather than its simple file name.
17077 @item ^-h^/HELP^
17078 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17079 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17081 @item ^-n^/NODELETE^
17082 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17083 Informative-only mode. Do not delete any files. Output the list of the files
17084 that would have been deleted if this switch was not specified.
17086 @item ^-P^/PROJECT_FILE=^@var{project}
17087 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17088 Use project file @var{project}. Only one such switch can be used.
17089 When cleaning a project file, the files produced by the compilation of the
17090 immediate sources or inherited sources of the project files are to be
17091 deleted. This is not depending on the presence or not of executable names
17092 on the command line.
17094 @item ^-q^/QUIET^
17095 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17096 Quiet output. If there are no error, do not ouuput anything, except in
17097 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17098 (switch ^-n^/NODELETE^).
17100 @item ^-r^/RECURSIVE^
17101 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17102 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17103 clean all imported and extended project files, recursively. If this switch
17104 is not specified, only the files related to the main project file are to be
17105 deleted. This switch has no effect if no project file is specified.
17107 @item ^-v^/VERBOSE^
17108 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17109 Verbose mode.
17111 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17112 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17113 Indicates the verbosity of the parsing of GNAT project files.
17114 @xref{Switches Related to Project Files}.
17116 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17117 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17118 Indicates that external variable @var{name} has the value @var{value}.
17119 The Project Manager will use this value for occurrences of
17120 @code{external(name)} when parsing the project file.
17121 @xref{Switches Related to Project Files}.
17123 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17124 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17125 When searching for ALI and object files, look in directory
17126 @var{dir}.
17128 @item ^-I^/SEARCH=^@var{dir}
17129 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17130 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17132 @item ^-I-^/NOCURRENT_DIRECTORY^
17133 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17134 @cindex Source files, suppressing search
17135 Do not look for ALI or object files in the directory
17136 where @code{gnatclean} was invoked.
17138 @end table
17140 @c @node Examples of gnatclean Usage
17141 @c @section Examples of @code{gnatclean} Usage
17143 @ifclear vms
17144 @node GNAT and Libraries
17145 @chapter GNAT and Libraries
17146 @cindex Library, building, installing, using
17148 @noindent
17149 This chapter describes how to build and use libraries with GNAT, and also shows
17150 how to recompile the GNAT run-time library. You should be familiar with the
17151 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17152 chapter.
17154 @menu
17155 * Introduction to Libraries in GNAT::
17156 * General Ada Libraries::
17157 * Stand-alone Ada Libraries::
17158 * Rebuilding the GNAT Run-Time Library::
17159 @end menu
17161 @node Introduction to Libraries in GNAT
17162 @section Introduction to Libraries in GNAT
17164 @noindent
17165 A library is, conceptually, a collection of objects which does not have its
17166 own main thread of execution, but rather provides certain services to the
17167 applications that use it. A library can be either statically linked with the
17168 application, in which case its code is directly included in the application,
17169 or, on platforms that support it, be dynamically linked, in which case
17170 its code is shared by all applications making use of this library.
17172 GNAT supports both types of libraries.
17173 In the static case, the compiled code can be provided in different ways. The
17174 simplest approach is to provide directly the set of objects resulting from
17175 compilation of the library source files. Alternatively, you can group the
17176 objects into an archive using whatever commands are provided by the operating
17177 system. For the latter case, the objects are grouped into a shared library.
17179 In the GNAT environment, a library has three types of components:
17180 @itemize @bullet
17181 @item
17182 Source files.
17183 @item
17184 @file{ALI} files.
17185 @xref{The Ada Library Information Files}.
17186 @item
17187 Object files, an archive or a shared library.
17188 @end itemize
17190 @noindent
17191 A GNAT library may expose all its source files, which is useful for
17192 documentation purposes. Alternatively, it may expose only the units needed by
17193 an external user to make use of the library. That is to say, the specs
17194 reflecting the library services along with all the units needed to compile
17195 those specs, which can include generic bodies or any body implementing an
17196 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17197 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17199 All compilation units comprising an application, including those in a library,
17200 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17201 computes the elaboration order from the @file{ALI} files and this is why they
17202 constitute a mandatory part of GNAT libraries. Except in the case of
17203 @emph{stand-alone libraries}, where a specific library elaboration routine is
17204 produced independently of the application(s) using the library.
17206 @node General Ada Libraries
17207 @section General Ada Libraries
17209 @menu
17210 * Building a library::
17211 * Installing a library::
17212 * Using a library::
17213 @end menu
17215 @node Building a library
17216 @subsection Building a library
17218 @noindent
17219 The easiest way to build a library is to use the Project Manager,
17220 which supports a special type of project called a @emph{Library Project}
17221 (@pxref{Library Projects}).
17223 A project is considered a library project, when two project-level attributes
17224 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17225 control different aspects of library configuration, additional optional
17226 project-level attributes can be specified:
17227 @table @code
17228 @item Library_Kind
17229 This attribute controls whether the library is to be static or dynamic
17231 @item Library_Version
17232 This attribute specifies the library version; this value is used
17233 during dynamic linking of shared libraries to determine if the currently
17234 installed versions of the binaries are compatible.
17236 @item Library_Options
17237 @item Library_GCC
17238 These attributes specify additional low-level options to be used during
17239 library generation, and redefine the actual application used to generate
17240 library.
17241 @end table
17243 @noindent
17244 The GNAT Project Manager takes full care of the library maintenance task,
17245 including recompilation of the source files for which objects do not exist
17246 or are not up to date, assembly of the library archive, and installation of
17247 the library (i.e., copying associated source, object and @file{ALI} files
17248 to the specified location).
17250 Here is a simple library project file:
17251 @smallexample @c ada
17252 project My_Lib is
17253    for Source_Dirs use ("src1", "src2");
17254    for Object_Dir use "obj";
17255    for Library_Name use "mylib";
17256    for Library_Dir use "lib";
17257    for Library_Kind use "dynamic";
17258 end My_lib;
17259 @end smallexample
17261 @noindent
17262 and the compilation command to build and install the library:
17264 @smallexample @c ada
17265   $ gnatmake -Pmy_lib
17266 @end smallexample
17268 @noindent
17269 It is not entirely trivial to perform manually all the steps required to
17270 produce a library. We recommend that you use the GNAT Project Manager
17271 for this task. In special cases where this is not desired, the necessary
17272 steps are discussed below.
17274 There are various possibilities for compiling the units that make up the
17275 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17276 with a conventional script. For simple libraries, it is also possible to create
17277 a dummy main program which depends upon all the packages that comprise the
17278 interface of the library. This dummy main program can then be given to
17279 @command{gnatmake}, which will ensure that all necessary objects are built.
17281 After this task is accomplished, you should follow the standard procedure
17282 of the underlying operating system to produce the static or shared library.
17284 Here is an example of such a dummy program:
17285 @smallexample @c ada
17286 @group
17287 with My_Lib.Service1;
17288 with My_Lib.Service2;
17289 with My_Lib.Service3;
17290 procedure My_Lib_Dummy is
17291 begin
17292    null;
17293 end;
17294 @end group
17295 @end smallexample
17297 @noindent
17298 Here are the generic commands that will build an archive or a shared library.
17300 @smallexample
17301 # compiling the library
17302 $ gnatmake -c my_lib_dummy.adb
17304 # we don't need the dummy object itself
17305 $ rm my_lib_dummy.o my_lib_dummy.ali
17307 # create an archive with the remaining objects
17308 $ ar rc libmy_lib.a *.o
17309 # some systems may require "ranlib" to be run as well
17311 # or create a shared library
17312 $ gcc -shared -o libmy_lib.so *.o
17313 # some systems may require the code to have been compiled with -fPIC
17315 # remove the object files that are now in the library
17316 $ rm *.o
17318 # Make the ALI files read-only so that gnatmake will not try to
17319 # regenerate the objects that are in the library
17320 $ chmod -w *.ali
17321 @end smallexample
17323 @noindent
17324 Please note that the library must have a name of the form @file{libxxx.a} or
17325 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17326 the directive @option{-lxxx} at link time.
17328 @node Installing a library
17329 @subsection Installing a library
17330 @cindex @code{ADA_PROJECT_PATH}
17332 @noindent
17333 If you use project files, library installation is part of the library build
17334 process. Thus no further action is needed in order to make use of the
17335 libraries that are built as part of the general application build. A usable
17336 version of the library is installed in the directory specified by the
17337 @code{Library_Dir} attribute of the library project file.
17339 You may want to install a library in a context different from where the library
17340 is built. This situation arises with third party suppliers, who may want
17341 to distribute a library in binary form where the user is not expected to be
17342 able to recompile the library. The simplest option in this case is to provide
17343 a project file slightly different from the one used to build the library, by
17344 using the @code{externally_built} attribute. For instance, the project
17345 file used to build the library in the previous section can be changed into the
17346 following one when the library is installed:
17348 @smallexample @c projectfile
17349 project My_Lib is
17350    for Source_Dirs use ("src1", "src2");
17351    for Library_Name use "mylib";
17352    for Library_Dir use "lib";
17353    for Library_Kind use "dynamic";
17354    for Externally_Built use "true";
17355 end My_lib;
17356 @end smallexample
17358 @noindent
17359 This project file assumes that the directories @file{src1},
17360 @file{src2}, and @file{lib} exist in
17361 the directory containing the project file. The @code{externally_built}
17362 attribute makes it clear to the GNAT builder that it should not attempt to
17363 recompile any of the units from this library. It allows the library provider to
17364 restrict the source set to the minimum necessary for clients to make use of the
17365 library as described in the first section of this chapter. It is the
17366 responsibility of the library provider to install the necessary sources, ALI
17367 files and libraries in the directories mentioned in the project file. For
17368 convenience, the user's library project file should be installed in a location
17369 that will be searched automatically by the GNAT
17370 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
17371 environment variable (@pxref{Importing Projects}), and also the default GNAT
17372 library location that can be queried with @command{gnatls -v} and is usually of
17373 the form $gnat_install_root/lib/gnat.
17375 When project files are not an option, it is also possible, but not recommended,
17376 to install the library so that the sources needed to use the library are on the
17377 Ada source path and the ALI files & libraries be on the Ada Object path (see
17378 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17379 administrator can place general-purpose libraries in the default compiler
17380 paths, by specifying the libraries' location in the configuration files
17381 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17382 must be located in the GNAT installation tree at the same place as the gcc spec
17383 file. The location of the gcc spec file can be determined as follows:
17384 @smallexample
17385 $ gcc -v
17386 @end smallexample
17388 @noindent
17389 The configuration files mentioned above have a simple format: each line
17390 must contain one unique directory name.
17391 Those names are added to the corresponding path
17392 in their order of appearance in the file. The names can be either absolute
17393 or relative; in the latter case, they are relative to where theses files
17394 are located.
17396 The files @file{ada_source_path} and @file{ada_object_path} might not be
17397 present in a
17398 GNAT installation, in which case, GNAT will look for its run-time library in
17399 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17400 objects and @file{ALI} files). When the files exist, the compiler does not
17401 look in @file{adainclude} and @file{adalib}, and thus the
17402 @file{ada_source_path} file
17403 must contain the location for the GNAT run-time sources (which can simply
17404 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17405 contain the location for the GNAT run-time objects (which can simply
17406 be @file{adalib}).
17408 You can also specify a new default path to the run-time library at compilation
17409 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17410 the run-time library you want your program to be compiled with. This switch is
17411 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17412 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17414 It is possible to install a library before or after the standard GNAT
17415 library, by reordering the lines in the configuration files. In general, a
17416 library must be installed before the GNAT library if it redefines
17417 any part of it.
17419 @node Using a library
17420 @subsection Using a library
17422 @noindent Once again, the project facility greatly simplifies the use of
17423 libraries. In this context, using a library is just a matter of adding a
17424 @code{with} clause in the user project. For instance, to make use of the
17425 library @code{My_Lib} shown in examples in earlier sections, you can
17426 write:
17428 @smallexample @c projectfile
17429 with "my_lib";
17430 project My_Proj is
17431   ...
17432 end My_Proj;
17433 @end smallexample
17435 Even if you have a third-party, non-Ada library, you can still use GNAT's
17436 Project Manager facility to provide a wrapper for it. For example, the
17437 following project, when @code{with}ed by your main project, will link with the
17438 third-party library @file{liba.a}:
17440 @smallexample @c projectfile
17441 @group
17442 project Liba is
17443    for Externally_Built use "true";
17444    for Library_Dir use "lib";
17445    for Library_Name use "a";
17446    for Library_Kind use "static";
17447 end Liba;
17448 @end group
17449 @end smallexample
17450 This is an alternative to the use of @code{pragma Linker_Options}. It is
17451 especially interesting in the context of systems with several interdependant
17452 static libraries where finding a proper linker order is not easy and best be
17453 left to the tools having visibility over project dependancy information.
17455 @noindent
17456 In order to use an Ada library manually, you need to make sure that this
17457 library is on both your source and object path
17458 (see @ref{Search Paths and the Run-Time Library (RTL)}
17459 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17460 in an archive or a shared library, you need to specify the desired
17461 library at link time.
17463 For example, you can use the library @file{mylib} installed in
17464 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17466 @smallexample
17467 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17468   -largs -lmy_lib
17469 @end smallexample
17471 @noindent
17472 This can be expressed more simply:
17473 @smallexample
17474 $ gnatmake my_appl
17475 @end smallexample
17476 @noindent
17477 when the following conditions are met:
17478 @itemize @bullet
17479 @item
17480 @file{/dir/my_lib_src} has been added by the user to the environment
17481 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17482 @file{ada_source_path}
17483 @item
17484 @file{/dir/my_lib_obj} has been added by the user to the environment
17485 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17486 @file{ada_object_path}
17487 @item
17488 a pragma @code{Linker_Options} has been added to one of the sources.
17489 For example:
17491 @smallexample @c ada
17492 pragma Linker_Options ("-lmy_lib");
17493 @end smallexample
17494 @end itemize
17496 @node Stand-alone Ada Libraries
17497 @section Stand-alone Ada Libraries
17498 @cindex Stand-alone library, building, using
17500 @menu
17501 * Introduction to Stand-alone Libraries::
17502 * Building a Stand-alone Library::
17503 * Creating a Stand-alone Library to be used in a non-Ada context::
17504 * Restrictions in Stand-alone Libraries::
17505 @end menu
17507 @node Introduction to Stand-alone Libraries
17508 @subsection Introduction to Stand-alone Libraries
17510 @noindent
17511 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17512 necessary code to
17513 elaborate the Ada units that are included in the library. In contrast with
17514 an ordinary library, which consists of all sources, objects and @file{ALI}
17515 files of the
17516 library, a SAL may specify a restricted subset of compilation units
17517 to serve as a library interface. In this case, the fully
17518 self-sufficient set of files will normally consist of an objects
17519 archive, the sources of interface units' specs, and the @file{ALI}
17520 files of interface units.
17521 If an interface spec contains a generic unit or an inlined subprogram,
17522 the body's
17523 source must also be provided; if the units that must be provided in the source
17524 form depend on other units, the source and @file{ALI} files of those must
17525 also be provided.
17527 The main purpose of a SAL is to minimize the recompilation overhead of client
17528 applications when a new version of the library is installed. Specifically,
17529 if the interface sources have not changed, client applications do not need to
17530 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17531 version, controlled by @code{Library_Version} attribute, is not changed,
17532 then the clients do not need to be relinked.
17534 SALs also allow the library providers to minimize the amount of library source
17535 text exposed to the clients.  Such ``information hiding'' might be useful or
17536 necessary for various reasons.
17538 Stand-alone libraries are also well suited to be used in an executable whose
17539 main routine is not written in Ada.
17541 @node Building a Stand-alone Library
17542 @subsection Building a Stand-alone Library
17544 @noindent
17545 GNAT's Project facility provides a simple way of building and installing
17546 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17547 To be a Stand-alone Library Project, in addition to the two attributes
17548 that make a project a Library Project (@code{Library_Name} and
17549 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17550 @code{Library_Interface} must be defined.  For example:
17552 @smallexample @c projectfile
17553 @group
17554    for Library_Dir use "lib_dir";
17555    for Library_Name use "dummy";
17556    for Library_Interface use ("int1", "int1.child");
17557 @end group
17558 @end smallexample
17560 @noindent
17561 Attribute @code{Library_Interface} has a non-empty string list value,
17562 each string in the list designating a unit contained in an immediate source
17563 of the project file.
17565 When a Stand-alone Library is built, first the binder is invoked to build
17566 a package whose name depends on the library name
17567 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17568 This binder-generated package includes initialization and
17569 finalization procedures whose
17570 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17571 in the example
17572 above). The object corresponding to this package is included in the library.
17574 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17575 calling of these procedures if a static SAL is built, or if a shared SAL
17576 is built
17577 with the project-level attribute @code{Library_Auto_Init} set to
17578 @code{"false"}.
17580 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17581 (those that are listed in attribute @code{Library_Interface}) are copied to
17582 the Library Directory. As a consequence, only the Interface Units may be
17583 imported from Ada units outside of the library. If other units are imported,
17584 the binding phase will fail.
17586 The attribute @code{Library_Src_Dir} may be specified for a
17587 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17588 single string value. Its value must be the path (absolute or relative to the
17589 project directory) of an existing directory. This directory cannot be the
17590 object directory or one of the source directories, but it can be the same as
17591 the library directory. The sources of the Interface
17592 Units of the library that are needed by an Ada client of the library will be
17593 copied to the designated directory, called the Interface Copy directory.
17594 These sources include the specs of the Interface Units, but they may also
17595 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17596 are used, or when there is a generic unit in the spec. Before the sources
17597 are copied to the Interface Copy directory, an attempt is made to delete all
17598 files in the Interface Copy directory.
17600 Building stand-alone libraries by hand is somewhat tedious, but for those
17601 occasions when it is necessary here are the steps that you need to perform:
17602 @itemize @bullet
17603 @item
17604 Compile all library sources.
17606 @item
17607 Invoke the binder with the switch @option{-n} (No Ada main program),
17608 with all the @file{ALI} files of the interfaces, and
17609 with the switch @option{-L} to give specific names to the @code{init}
17610 and @code{final} procedures.  For example:
17611 @smallexample
17612   gnatbind -n int1.ali int2.ali -Lsal1
17613 @end smallexample
17615 @item
17616 Compile the binder generated file:
17617 @smallexample
17618   gcc -c b~int2.adb
17619 @end smallexample
17621 @item
17622 Link the dynamic library with all the necessary object files,
17623 indicating to the linker the names of the @code{init} (and possibly
17624 @code{final}) procedures for automatic initialization (and finalization).
17625 The built library should be placed in a directory different from
17626 the object directory.
17628 @item
17629 Copy the @code{ALI} files of the interface to the library directory,
17630 add in this copy an indication that it is an interface to a SAL
17631 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17632 with letter ``P'') and make the modified copy of the @file{ALI} file
17633 read-only.
17634 @end itemize
17636 @noindent
17637 Using SALs is not different from using other libraries
17638 (see @ref{Using a library}).
17640 @node Creating a Stand-alone Library to be used in a non-Ada context
17641 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17643 @noindent
17644 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17645 a non-Ada context.
17647 The only extra step required is to ensure that library interface subprograms
17648 are compatible with the main program, by means of @code{pragma Export}
17649 or @code{pragma Convention}.
17651 Here is an example of simple library interface for use with C main program:
17653 @smallexample @c ada
17654 package Interface is
17656    procedure Do_Something;
17657    pragma Export (C, Do_Something, "do_something");
17659    procedure Do_Something_Else;
17660    pragma Export (C, Do_Something_Else, "do_something_else");
17662 end Interface;
17663 @end smallexample
17665 @noindent
17666 On the foreign language side, you must provide a ``foreign'' view of the
17667 library interface; remember that it should contain elaboration routines in
17668 addition to interface subprograms.
17670 The example below shows the content of @code{mylib_interface.h} (note
17671 that there is no rule for the naming of this file, any name can be used)
17672 @smallexample
17673 /* the library elaboration procedure */
17674 extern void mylibinit (void);
17676 /* the library finalization procedure */
17677 extern void mylibfinal (void);
17679 /* the interface exported by the library */
17680 extern void do_something (void);
17681 extern void do_something_else (void);
17682 @end smallexample
17684 @noindent
17685 Libraries built as explained above can be used from any program, provided
17686 that the elaboration procedures (named @code{mylibinit} in the previous
17687 example) are called before the library services are used. Any number of
17688 libraries can be used simultaneously, as long as the elaboration
17689 procedure of each library is called.
17691 Below is an example of a C program that uses the @code{mylib} library.
17693 @smallexample
17694 #include "mylib_interface.h"
17697 main (void)
17699    /* First, elaborate the library before using it */
17700    mylibinit ();
17702    /* Main program, using the library exported entities */
17703    do_something ();
17704    do_something_else ();
17706    /* Library finalization at the end of the program */
17707    mylibfinal ();
17708    return 0;
17710 @end smallexample
17712 @noindent
17713 Note that invoking any library finalization procedure generated by
17714 @code{gnatbind} shuts down the Ada run-time environment.
17715 Consequently, the
17716 finalization of all Ada libraries must be performed at the end of the program.
17717 No call to these libraries or to the Ada run-time library should be made
17718 after the finalization phase.
17720 @node Restrictions in Stand-alone Libraries
17721 @subsection Restrictions in Stand-alone Libraries
17723 @noindent
17724 The pragmas listed below should be used with caution inside libraries,
17725 as they can create incompatibilities with other Ada libraries:
17726 @itemize @bullet
17727 @item pragma @code{Locking_Policy}
17728 @item pragma @code{Queuing_Policy}
17729 @item pragma @code{Task_Dispatching_Policy}
17730 @item pragma @code{Unreserve_All_Interrupts}
17731 @end itemize
17733 @noindent
17734 When using a library that contains such pragmas, the user must make sure
17735 that all libraries use the same pragmas with the same values. Otherwise,
17736 @code{Program_Error} will
17737 be raised during the elaboration of the conflicting
17738 libraries. The usage of these pragmas and its consequences for the user
17739 should therefore be well documented.
17741 Similarly, the traceback in the exception occurrence mechanism should be
17742 enabled or disabled in a consistent manner across all libraries.
17743 Otherwise, Program_Error will be raised during the elaboration of the
17744 conflicting libraries.
17746 If the @code{Version} or @code{Body_Version}
17747 attributes are used inside a library, then you need to
17748 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17749 libraries, so that version identifiers can be properly computed.
17750 In practice these attributes are rarely used, so this is unlikely
17751 to be a consideration.
17753 @node  Rebuilding the GNAT Run-Time Library
17754 @section Rebuilding the GNAT Run-Time Library
17755 @cindex GNAT Run-Time Library, rebuilding
17757 @noindent
17758 It may be useful to recompile the GNAT library in various contexts, the
17759 most important one being the use of partition-wide configuration pragmas
17760 such as @code{Normalize_Scalars}. A special Makefile called
17761 @code{Makefile.adalib} is provided to that effect and can be found in
17762 the directory containing the GNAT library. The location of this
17763 directory depends on the way the GNAT environment has been installed and can
17764 be determined by means of the command:
17766 @smallexample
17767 $ gnatls -v
17768 @end smallexample
17770 @noindent
17771 The last entry in the object search path usually contains the
17772 gnat library. This Makefile contains its own documentation and in
17773 particular the set of instructions needed to rebuild a new library and
17774 to use it.
17776 @node Using the GNU make Utility
17777 @chapter Using the GNU @code{make} Utility
17778 @findex make
17780 @noindent
17781 This chapter offers some examples of makefiles that solve specific
17782 problems. It does not explain how to write a makefile (see the GNU make
17783 documentation), nor does it try to replace the @command{gnatmake} utility
17784 (@pxref{The GNAT Make Program gnatmake}).
17786 All the examples in this section are specific to the GNU version of
17787 make. Although @code{make} is a standard utility, and the basic language
17788 is the same, these examples use some advanced features found only in
17789 @code{GNU make}.
17791 @menu
17792 * Using gnatmake in a Makefile::
17793 * Automatically Creating a List of Directories::
17794 * Generating the Command Line Switches::
17795 * Overcoming Command Line Length Limits::
17796 @end menu
17798 @node Using gnatmake in a Makefile
17799 @section Using gnatmake in a Makefile
17800 @findex makefile
17801 @cindex GNU make
17803 @noindent
17804 Complex project organizations can be handled in a very powerful way by
17805 using GNU make combined with gnatmake. For instance, here is a Makefile
17806 which allows you to build each subsystem of a big project into a separate
17807 shared library. Such a makefile allows you to significantly reduce the link
17808 time of very big applications while maintaining full coherence at
17809 each step of the build process.
17811 The list of dependencies are handled automatically by
17812 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17813 the appropriate directories.
17815 Note that you should also read the example on how to automatically
17816 create the list of directories
17817 (@pxref{Automatically Creating a List of Directories})
17818 which might help you in case your project has a lot of subdirectories.
17820 @smallexample
17821 @iftex
17822 @leftskip=0cm
17823 @font@heightrm=cmr8
17824 @heightrm
17825 @end iftex
17826 ## This Makefile is intended to be used with the following directory
17827 ## configuration:
17828 ##  - The sources are split into a series of csc (computer software components)
17829 ##    Each of these csc is put in its own directory.
17830 ##    Their name are referenced by the directory names.
17831 ##    They will be compiled into shared library (although this would also work
17832 ##    with static libraries
17833 ##  - The main program (and possibly other packages that do not belong to any
17834 ##    csc is put in the top level directory (where the Makefile is).
17835 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17836 ##                    \_ second_csc (sources) __ lib (will contain the library)
17837 ##                    \_ ...
17838 ## Although this Makefile is build for shared library, it is easy to modify
17839 ## to build partial link objects instead (modify the lines with -shared and
17840 ## gnatlink below)
17842 ## With this makefile, you can change any file in the system or add any new
17843 ## file, and everything will be recompiled correctly (only the relevant shared
17844 ## objects will be recompiled, and the main program will be re-linked).
17846 # The list of computer software component for your project. This might be
17847 # generated automatically.
17848 CSC_LIST=aa bb cc
17850 # Name of the main program (no extension)
17851 MAIN=main
17853 # If we need to build objects with -fPIC, uncomment the following line
17854 #NEED_FPIC=-fPIC
17856 # The following variable should give the directory containing libgnat.so
17857 # You can get this directory through 'gnatls -v'. This is usually the last
17858 # directory in the Object_Path.
17859 GLIB=...
17861 # The directories for the libraries
17862 # (This macro expands the list of CSC to the list of shared libraries, you
17863 # could simply use the expanded form :
17864 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17865 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17867 $@{MAIN@}: objects $@{LIB_DIR@}
17868     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17869     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17871 objects::
17872     # recompile the sources
17873     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17875 # Note: In a future version of GNAT, the following commands will be simplified
17876 # by a new tool, gnatmlib
17877 $@{LIB_DIR@}:
17878     mkdir -p $@{dir $@@ @}
17879     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17880     cd $@{dir $@@ @}; cp -f ../*.ali .
17882 # The dependencies for the modules
17883 # Note that we have to force the expansion of *.o, since in some cases
17884 # make won't be able to do it itself.
17885 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17886 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17887 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17889 # Make sure all of the shared libraries are in the path before starting the
17890 # program
17891 run::
17892     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17894 clean::
17895     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17896     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17897     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17898     $@{RM@} *.o *.ali $@{MAIN@}
17899 @end smallexample
17901 @node Automatically Creating a List of Directories
17902 @section Automatically Creating a List of Directories
17904 @noindent
17905 In most makefiles, you will have to specify a list of directories, and
17906 store it in a variable. For small projects, it is often easier to
17907 specify each of them by hand, since you then have full control over what
17908 is the proper order for these directories, which ones should be
17909 included...
17911 However, in larger projects, which might involve hundreds of
17912 subdirectories, it might be more convenient to generate this list
17913 automatically.
17915 The example below presents two methods. The first one, although less
17916 general, gives you more control over the list. It involves wildcard
17917 characters, that are automatically expanded by @code{make}. Its
17918 shortcoming is that you need to explicitly specify some of the
17919 organization of your project, such as for instance the directory tree
17920 depth, whether some directories are found in a separate tree,...
17922 The second method is the most general one. It requires an external
17923 program, called @code{find}, which is standard on all Unix systems. All
17924 the directories found under a given root directory will be added to the
17925 list.
17927 @smallexample
17928 @iftex
17929 @leftskip=0cm
17930 @font@heightrm=cmr8
17931 @heightrm
17932 @end iftex
17933 # The examples below are based on the following directory hierarchy:
17934 # All the directories can contain any number of files
17935 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17936 #                       ->  ab
17937 #                       ->  ac
17938 #                ->  b  ->  ba  ->  baa
17939 #                       ->  bb
17940 #                       ->  bc
17941 # This Makefile creates a variable called DIRS, that can be reused any time
17942 # you need this list (see the other examples in this section)
17944 # The root of your project's directory hierarchy
17945 ROOT_DIRECTORY=.
17947 ####
17948 # First method: specify explicitly the list of directories
17949 # This allows you to specify any subset of all the directories you need.
17950 ####
17952 DIRS := a/aa/ a/ab/ b/ba/
17954 ####
17955 # Second method: use wildcards
17956 # Note that the argument(s) to wildcard below should end with a '/'.
17957 # Since wildcards also return file names, we have to filter them out
17958 # to avoid duplicate directory names.
17959 # We thus use make's @code{dir} and @code{sort} functions.
17960 # It sets DIRs to the following value (note that the directories aaa and baa
17961 # are not given, unless you change the arguments to wildcard).
17962 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17963 ####
17965 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17966                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17968 ####
17969 # Third method: use an external program
17970 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17971 # This is the most complete command: it sets DIRs to the following value:
17972 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17973 ####
17975 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17977 @end smallexample
17979 @node Generating the Command Line Switches
17980 @section Generating the Command Line Switches
17982 @noindent
17983 Once you have created the list of directories as explained in the
17984 previous section (@pxref{Automatically Creating a List of Directories}),
17985 you can easily generate the command line arguments to pass to gnatmake.
17987 For the sake of completeness, this example assumes that the source path
17988 is not the same as the object path, and that you have two separate lists
17989 of directories.
17991 @smallexample
17992 # see "Automatically creating a list of directories" to create
17993 # these variables
17994 SOURCE_DIRS=
17995 OBJECT_DIRS=
17997 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17998 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18000 all:
18001         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18002 @end smallexample
18004 @node Overcoming Command Line Length Limits
18005 @section Overcoming Command Line Length Limits
18007 @noindent
18008 One problem that might be encountered on big projects is that many
18009 operating systems limit the length of the command line. It is thus hard to give
18010 gnatmake the list of source and object directories.
18012 This example shows how you can set up environment variables, which will
18013 make @command{gnatmake} behave exactly as if the directories had been
18014 specified on the command line, but have a much higher length limit (or
18015 even none on most systems).
18017 It assumes that you have created a list of directories in your Makefile,
18018 using one of the methods presented in
18019 @ref{Automatically Creating a List of Directories}.
18020 For the sake of completeness, we assume that the object
18021 path (where the ALI files are found) is different from the sources patch.
18023 Note a small trick in the Makefile below: for efficiency reasons, we
18024 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18025 expanded immediately by @code{make}. This way we overcome the standard
18026 make behavior which is to expand the variables only when they are
18027 actually used.
18029 On Windows, if you are using the standard Windows command shell, you must
18030 replace colons with semicolons in the assignments to these variables.
18032 @smallexample
18033 @iftex
18034 @leftskip=0cm
18035 @font@heightrm=cmr8
18036 @heightrm
18037 @end iftex
18038 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18039 # This is the same thing as putting the -I arguments on the command line.
18040 # (the equivalent of using -aI on the command line would be to define
18041 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18042 # You can of course have different values for these variables.
18044 # Note also that we need to keep the previous values of these variables, since
18045 # they might have been set before running 'make' to specify where the GNAT
18046 # library is installed.
18048 # see "Automatically creating a list of directories" to create these
18049 # variables
18050 SOURCE_DIRS=
18051 OBJECT_DIRS=
18053 empty:=
18054 space:=$@{empty@} $@{empty@}
18055 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18056 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18057 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18058 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18059 export ADA_INCLUDE_PATH
18060 export ADA_OBJECT_PATH
18062 all:
18063         gnatmake main_unit
18064 @end smallexample
18065 @end ifclear
18067 @node Memory Management Issues
18068 @chapter Memory Management Issues
18070 @noindent
18071 This chapter describes some useful memory pools provided in the GNAT library
18072 and in particular the GNAT Debug Pool facility, which can be used to detect
18073 incorrect uses of access values (including ``dangling references'').
18074 @ifclear vms
18075 It also describes the @command{gnatmem} tool, which can be used to track down
18076 ``memory leaks''.
18077 @end ifclear
18079 @menu
18080 * Some Useful Memory Pools::
18081 * The GNAT Debug Pool Facility::
18082 @ifclear vms
18083 * The gnatmem Tool::
18084 @end ifclear
18085 @end menu
18087 @node Some Useful Memory Pools
18088 @section Some Useful Memory Pools
18089 @findex Memory Pool
18090 @cindex storage, pool
18092 @noindent
18093 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18094 storage pool. Allocations use the standard system call @code{malloc} while
18095 deallocations use the standard system call @code{free}. No reclamation is
18096 performed when the pool goes out of scope. For performance reasons, the
18097 standard default Ada allocators/deallocators do not use any explicit storage
18098 pools but if they did, they could use this storage pool without any change in
18099 behavior. That is why this storage pool is used  when the user
18100 manages to make the default implicit allocator explicit as in this example:
18101 @smallexample @c ada
18102    type T1 is access Something;
18103     -- no Storage pool is defined for T2
18104    type T2 is access Something_Else;
18105    for T2'Storage_Pool use T1'Storage_Pool;
18106    -- the above is equivalent to
18107    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18108 @end smallexample
18110 @noindent
18111 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18112 pool. The allocation strategy is similar to @code{Pool_Local}'s
18113 except that the all
18114 storage allocated with this pool is reclaimed when the pool object goes out of
18115 scope. This pool provides a explicit mechanism similar to the implicit one
18116 provided by several Ada 83 compilers for allocations performed through a local
18117 access type and whose purpose was to reclaim memory when exiting the
18118 scope of a given local access. As an example, the following program does not
18119 leak memory even though it does not perform explicit deallocation:
18121 @smallexample @c ada
18122 with System.Pool_Local;
18123 procedure Pooloc1 is
18124    procedure Internal is
18125       type A is access Integer;
18126       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18127       for A'Storage_Pool use X;
18128       v : A;
18129    begin
18130       for I in  1 .. 50 loop
18131          v := new Integer;
18132       end loop;
18133    end Internal;
18134 begin
18135    for I in  1 .. 100 loop
18136       Internal;
18137    end loop;
18138 end Pooloc1;
18139 @end smallexample
18141 @noindent
18142 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18143 @code{Storage_Size} is specified for an access type.
18144 The whole storage for the pool is
18145 allocated at once, usually on the stack at the point where the access type is
18146 elaborated. It is automatically reclaimed when exiting the scope where the
18147 access type is defined. This package is not intended to be used directly by the
18148 user and it is implicitly used for each such declaration:
18150 @smallexample @c ada
18151    type T1 is access Something;
18152    for T1'Storage_Size use 10_000;
18153 @end smallexample
18156 @node The GNAT Debug Pool Facility
18157 @section The GNAT Debug Pool Facility
18158 @findex Debug Pool
18159 @cindex storage, pool, memory corruption
18161 @noindent
18162 The use of unchecked deallocation and unchecked conversion can easily
18163 lead to incorrect memory references. The problems generated by such
18164 references are usually difficult to tackle because the symptoms can be
18165 very remote from the origin of the problem. In such cases, it is
18166 very helpful to detect the problem as early as possible. This is the
18167 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18169 In order to use the GNAT specific debugging pool, the user must
18170 associate a debug pool object with each of the access types that may be
18171 related to suspected memory problems. See Ada Reference Manual 13.11.
18172 @smallexample @c ada
18173 type Ptr is access Some_Type;
18174 Pool : GNAT.Debug_Pools.Debug_Pool;
18175 for Ptr'Storage_Pool use Pool;
18176 @end smallexample
18178 @noindent
18179 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18180 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18181 allow the user to redefine allocation and deallocation strategies. They
18182 also provide a checkpoint for each dereference, through the use of
18183 the primitive operation @code{Dereference} which is implicitly called at
18184 each dereference of an access value.
18186 Once an access type has been associated with a debug pool, operations on
18187 values of the type may raise four distinct exceptions,
18188 which correspond to four potential kinds of memory corruption:
18189 @itemize @bullet
18190 @item
18191 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18192 @item
18193 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18194 @item
18195 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18196 @item
18197 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18198 @end itemize
18200 @noindent
18201 For types associated with a Debug_Pool, dynamic allocation is performed using
18202 the standard GNAT allocation routine. References to all allocated chunks of
18203 memory are kept in an internal dictionary. Several deallocation strategies are
18204 provided, whereupon the user can choose to release the memory to the system,
18205 keep it allocated for further invalid access checks, or fill it with an easily
18206 recognizable pattern for debug sessions. The memory pattern is the old IBM
18207 hexadecimal convention: @code{16#DEADBEEF#}.
18209 See the documentation in the file g-debpoo.ads for more information on the
18210 various strategies.
18212 Upon each dereference, a check is made that the access value denotes a
18213 properly allocated memory location. Here is a complete example of use of
18214 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18215 @smallexample @c ada
18216 @iftex
18217 @leftskip=0cm
18218 @end iftex
18219 with Gnat.Io; use Gnat.Io;
18220 with Unchecked_Deallocation;
18221 with Unchecked_Conversion;
18222 with GNAT.Debug_Pools;
18223 with System.Storage_Elements;
18224 with Ada.Exceptions; use Ada.Exceptions;
18225 procedure Debug_Pool_Test is
18227    type T is access Integer;
18228    type U is access all T;
18230    P : GNAT.Debug_Pools.Debug_Pool;
18231    for T'Storage_Pool use P;
18233    procedure Free is new Unchecked_Deallocation (Integer, T);
18234    function UC is new Unchecked_Conversion (U, T);
18235    A, B : aliased T;
18237    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18239 begin
18240    Info (P);
18241    A := new Integer;
18242    B := new Integer;
18243    B := A;
18244    Info (P);
18245    Free (A);
18246    begin
18247       Put_Line (Integer'Image(B.all));
18248    exception
18249       when E : others => Put_Line ("raised: " & Exception_Name (E));
18250    end;
18251    begin
18252       Free (B);
18253    exception
18254       when E : others => Put_Line ("raised: " & Exception_Name (E));
18255    end;
18256    B := UC(A'Access);
18257    begin
18258       Put_Line (Integer'Image(B.all));
18259    exception
18260       when E : others => Put_Line ("raised: " & Exception_Name (E));
18261    end;
18262    begin
18263       Free (B);
18264    exception
18265       when E : others => Put_Line ("raised: " & Exception_Name (E));
18266    end;
18267    Info (P);
18268 end Debug_Pool_Test;
18269 @end smallexample
18271 @noindent
18272 The debug pool mechanism provides the following precise diagnostics on the
18273 execution of this erroneous program:
18274 @smallexample
18275 Debug Pool info:
18276   Total allocated bytes :  0
18277   Total deallocated bytes :  0
18278   Current Water Mark:  0
18279   High Water Mark:  0
18281 Debug Pool info:
18282   Total allocated bytes :  8
18283   Total deallocated bytes :  0
18284   Current Water Mark:  8
18285   High Water Mark:  8
18287 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18288 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18289 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18290 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18291 Debug Pool info:
18292   Total allocated bytes :  8
18293   Total deallocated bytes :  4
18294   Current Water Mark:  4
18295   High Water Mark:  8
18296 @end smallexample
18298 @ifclear vms
18299 @node The gnatmem Tool
18300 @section The @command{gnatmem} Tool
18301 @findex gnatmem
18303 @noindent
18304 The @code{gnatmem} utility monitors dynamic allocation and
18305 deallocation activity in a program, and displays information about
18306 incorrect deallocations and possible sources of memory leaks.
18307 It provides three type of information:
18308 @itemize @bullet
18309 @item
18310 General information concerning memory management, such as the total
18311 number of allocations and deallocations, the amount of allocated
18312 memory and the high water mark, i.e. the largest amount of allocated
18313 memory in the course of program execution.
18315 @item
18316 Backtraces for all incorrect deallocations, that is to say deallocations
18317 which do not correspond to a valid allocation.
18319 @item
18320 Information on each allocation that is potentially the origin of a memory
18321 leak.
18322 @end itemize
18324 @menu
18325 * Running gnatmem::
18326 * Switches for gnatmem::
18327 * Example of gnatmem Usage::
18328 @end menu
18330 @node Running gnatmem
18331 @subsection Running @code{gnatmem}
18333 @noindent
18334 @code{gnatmem} makes use of the output created by the special version of
18335 allocation and deallocation routines that record call information. This
18336 allows to obtain accurate dynamic memory usage history at a minimal cost to
18337 the execution speed. Note however, that @code{gnatmem} is not supported on
18338 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18339 32-bit Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18341 @noindent
18342 The @code{gnatmem} command has the form
18344 @smallexample
18345    $ gnatmem [switches] user_program
18346 @end smallexample
18348 @noindent
18349 The program must have been linked with the instrumented version of the
18350 allocation and deallocation routines. This is done by linking with the
18351 @file{libgmem.a} library. For correct symbolic backtrace information,
18352 the user program should be compiled with debugging options
18353 @ref{Switches for gcc}. For example to build @file{my_program}:
18355 @smallexample
18356 $ gnatmake -g my_program -largs -lgmem
18357 @end smallexample
18359 @noindent
18360 When running @file{my_program} the file @file{gmem.out} is produced. This file
18361 contains information about all allocations and deallocations done by the
18362 program. It is produced by the instrumented allocations and
18363 deallocations routines and will be used by @code{gnatmem}.
18365 @noindent
18366 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18367 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18368 @code{-i} switch, gnatmem will assume that this file can be found in the
18369 current directory. For example, after you have executed @file{my_program},
18370 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18372 @smallexample
18373 $ gnatmem my_program
18374 @end smallexample
18376 @noindent
18377 This will produce the output with the following format:
18379 *************** debut cc
18380 @smallexample
18381 $ gnatmem my_program
18383 Global information
18384 ------------------
18385    Total number of allocations        :  45
18386    Total number of deallocations      :   6
18387    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18388    High Water Mark                    :  11.40 Kilobytes
18393 Allocation Root # 2
18394 -------------------
18395  Number of non freed allocations    :  11
18396  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18397  High Water Mark                    :   1.27 Kilobytes
18398  Backtrace                          :
18399    my_program.adb:23 my_program.alloc
18403 @end smallexample
18405 The first block of output gives general information. In this case, the
18406 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18407 Unchecked_Deallocation routine occurred.
18409 @noindent
18410 Subsequent paragraphs display  information on all allocation roots.
18411 An allocation root is a specific point in the execution of the program
18412 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18413 construct. This root is represented by an execution backtrace (or subprogram
18414 call stack). By default the backtrace depth for allocations roots is 1, so
18415 that a root corresponds exactly to a source location. The backtrace can
18416 be made deeper, to make the root more specific.
18418 @node Switches for gnatmem
18419 @subsection Switches for @code{gnatmem}
18421 @noindent
18422 @code{gnatmem} recognizes the following switches:
18424 @table @option
18426 @item -q
18427 @cindex @option{-q} (@code{gnatmem})
18428 Quiet. Gives the minimum output needed to identify the origin of the
18429 memory leaks. Omits statistical information.
18431 @item @var{N}
18432 @cindex @var{N} (@code{gnatmem})
18433 N is an integer literal (usually between 1 and 10) which controls the
18434 depth of the backtraces defining allocation root. The default value for
18435 N is 1. The deeper the backtrace, the more precise the localization of
18436 the root. Note that the total number of roots can depend on this
18437 parameter. This parameter must be specified @emph{before} the name of the
18438 executable to be analyzed, to avoid ambiguity.
18440 @item -b n
18441 @cindex @option{-b} (@code{gnatmem})
18442 This switch has the same effect as just depth parameter.
18444 @item -i @var{file}
18445 @cindex @option{-i} (@code{gnatmem})
18446 Do the @code{gnatmem} processing starting from @file{file}, rather than
18447 @file{gmem.out} in the current directory.
18449 @item -m n
18450 @cindex @option{-m} (@code{gnatmem})
18451 This switch causes @code{gnatmem} to mask the allocation roots that have less
18452 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18453 examine even the roots that didn't result in leaks.
18455 @item -s order
18456 @cindex @option{-s} (@code{gnatmem})
18457 This switch causes @code{gnatmem} to sort the allocation roots according to the
18458 specified order of sort criteria, each identified by a single letter. The
18459 currently supported criteria are @code{n, h, w} standing respectively for
18460 number of unfreed allocations, high watermark, and final watermark
18461 corresponding to a specific root. The default order is @code{nwh}.
18463 @end table
18465 @node Example of gnatmem Usage
18466 @subsection Example of @code{gnatmem} Usage
18468 @noindent
18469 The following example shows the use of @code{gnatmem}
18470 on a simple memory-leaking program.
18471 Suppose that we have the following Ada program:
18473 @smallexample @c ada
18474 @group
18475 @cartouche
18476 with Unchecked_Deallocation;
18477 procedure Test_Gm is
18479    type T is array (1..1000) of Integer;
18480    type Ptr is access T;
18481    procedure Free is new Unchecked_Deallocation (T, Ptr);
18482    A : Ptr;
18484    procedure My_Alloc is
18485    begin
18486       A := new T;
18487    end My_Alloc;
18489    procedure My_DeAlloc is
18490       B : Ptr := A;
18491    begin
18492       Free (B);
18493    end My_DeAlloc;
18495 begin
18496    My_Alloc;
18497    for I in 1 .. 5 loop
18498       for J in I .. 5 loop
18499          My_Alloc;
18500       end loop;
18501       My_Dealloc;
18502    end loop;
18503 end;
18504 @end cartouche
18505 @end group
18506 @end smallexample
18508 @noindent
18509 The program needs to be compiled with debugging option and linked with
18510 @code{gmem} library:
18512 @smallexample
18513 $ gnatmake -g test_gm -largs -lgmem
18514 @end smallexample
18516 @noindent
18517 Then we execute the program as usual:
18519 @smallexample
18520 $ test_gm
18521 @end smallexample
18523 @noindent
18524 Then @code{gnatmem} is invoked simply with
18525 @smallexample
18526 $ gnatmem test_gm
18527 @end smallexample
18529 @noindent
18530 which produces the following output (result may vary on different platforms):
18532 @smallexample
18533 Global information
18534 ------------------
18535    Total number of allocations        :  18
18536    Total number of deallocations      :   5
18537    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18538    High Water Mark                    :  56.90 Kilobytes
18540 Allocation Root # 1
18541 -------------------
18542  Number of non freed allocations    :  11
18543  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18544  High Water Mark                    :  46.88 Kilobytes
18545  Backtrace                          :
18546    test_gm.adb:11 test_gm.my_alloc
18548 Allocation Root # 2
18549 -------------------
18550  Number of non freed allocations    :   1
18551  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18552  High Water Mark                    :  10.02 Kilobytes
18553  Backtrace                          :
18554    s-secsta.adb:81 system.secondary_stack.ss_init
18556 Allocation Root # 3
18557 -------------------
18558  Number of non freed allocations    :   1
18559  Final Water Mark (non freed mem)   :  12 Bytes
18560  High Water Mark                    :  12 Bytes
18561  Backtrace                          :
18562    s-secsta.adb:181 system.secondary_stack.ss_init
18563 @end smallexample
18565 @noindent
18566 Note that the GNAT run time contains itself a certain number of
18567 allocations that have no  corresponding deallocation,
18568 as shown here for root #2 and root
18569 #3. This is a normal behavior when the number of non freed allocations
18570 is one, it allocates dynamic data structures that the run time needs for
18571 the complete lifetime of the program. Note also that there is only one
18572 allocation root in the user program with a single line back trace:
18573 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18574 program shows that 'My_Alloc' is called at 2 different points in the
18575 source (line 21 and line 24). If those two allocation roots need to be
18576 distinguished, the backtrace depth parameter can be used:
18578 @smallexample
18579 $ gnatmem 3 test_gm
18580 @end smallexample
18582 @noindent
18583 which will give the following output:
18585 @smallexample
18586 Global information
18587 ------------------
18588    Total number of allocations        :  18
18589    Total number of deallocations      :   5
18590    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18591    High Water Mark                    :  56.90 Kilobytes
18593 Allocation Root # 1
18594 -------------------
18595  Number of non freed allocations    :  10
18596  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18597  High Water Mark                    :  42.97 Kilobytes
18598  Backtrace                          :
18599    test_gm.adb:11 test_gm.my_alloc
18600    test_gm.adb:24 test_gm
18601    b_test_gm.c:52 main
18603 Allocation Root # 2
18604 -------------------
18605  Number of non freed allocations    :   1
18606  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18607  High Water Mark                    :  10.02 Kilobytes
18608  Backtrace                          :
18609    s-secsta.adb:81  system.secondary_stack.ss_init
18610    s-secsta.adb:283 <system__secondary_stack___elabb>
18611    b_test_gm.c:33   adainit
18613 Allocation Root # 3
18614 -------------------
18615  Number of non freed allocations    :   1
18616  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18617  High Water Mark                    :   3.91 Kilobytes
18618  Backtrace                          :
18619    test_gm.adb:11 test_gm.my_alloc
18620    test_gm.adb:21 test_gm
18621    b_test_gm.c:52 main
18623 Allocation Root # 4
18624 -------------------
18625  Number of non freed allocations    :   1
18626  Final Water Mark (non freed mem)   :  12 Bytes
18627  High Water Mark                    :  12 Bytes
18628  Backtrace                          :
18629    s-secsta.adb:181 system.secondary_stack.ss_init
18630    s-secsta.adb:283 <system__secondary_stack___elabb>
18631    b_test_gm.c:33   adainit
18632 @end smallexample
18634 @noindent
18635 The allocation root #1 of the first example has been split in 2 roots #1
18636 and #3 thanks to the more precise associated backtrace.
18638 @end ifclear
18640 @node Stack Related Tools
18641 @chapter Stack Related Tools
18643 @noindent
18644 This chapter describes some useful tools associated to stack. In
18645 particular, dynamic and static usage measurements.
18647 @menu
18648 * Stack Overflow Checking::
18649 * Static Stack Usage Analysis::
18650 * Dynamic Stack Usage Analysis::
18651 @end menu
18653 @node Stack Overflow Checking
18654 @section Stack Overflow Checking
18655 @cindex Stack Overflow Checking
18656 @cindex -fstack-check
18658 @noindent
18659 For most operating systems, @command{gcc} does not perform stack overflow
18660 checking by default. This means that if the main environment task or
18661 some other task exceeds the available stack space, then unpredictable
18662 behavior will occur.
18664 To activate stack checking, compile all units with the gcc option
18665 @option{-fstack-check}. For example:
18667 @smallexample
18668 gcc -c -fstack-check package1.adb
18669 @end smallexample
18671 @noindent
18672 Units compiled with this option will generate extra instructions to check
18673 that any use of the stack (for procedure calls or for declaring local
18674 variables in declare blocks) do not exceed the available stack space.
18675 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18677 For declared tasks, the stack size is always controlled by the size
18678 given in an applicable @code{Storage_Size} pragma (or is set to
18679 the default size if no pragma is used.
18681 For the environment task, the stack size depends on
18682 system defaults and is unknown to the compiler. The stack
18683 may even dynamically grow on some systems, precluding the
18684 normal Ada semantics for stack overflow. In the worst case,
18685 unbounded stack usage, causes unbounded stack expansion
18686 resulting in the system running out of virtual memory.
18688 The stack checking may still work correctly if a fixed
18689 size stack is allocated, but this cannot be guaranteed.
18690 To ensure that a clean exception is signalled for stack
18691 overflow, set the environment variable
18692 @code{GNAT_STACK_LIMIT} to indicate the maximum
18693 stack area that can be used, as in:
18694 @cindex GNAT_STACK_LIMIT
18696 @smallexample
18697 SET GNAT_STACK_LIMIT 1600
18698 @end smallexample
18700 @noindent
18701 The limit is given in kilobytes, so the above declaration would
18702 set the stack limit of the environment task to 1.6 megabytes.
18703 Note that the only purpose of this usage is to limit the amount
18704 of stack used by the environment task. If it is necessary to
18705 increase the amount of stack for the environment task, then this
18706 is an operating systems issue, and must be addressed with the
18707 appropriate operating systems commands.
18709 @node Static Stack Usage Analysis
18710 @section Static Stack Usage Analysis
18711 @cindex Static Stack Usage Analysis
18712 @cindex -fstack-usage
18714 @noindent
18715 Units compiled with -fstack-usage will generate an extra file containing
18716 the maximum amount of stack used on a per-function basis. The filename for
18717 the dump is made by appending
18718 @file{.su} to the AUXNAME.  AUXNAME is generated from the name of
18719 the output file, if explicitly specified and it is not an executable,
18720 otherwise it is the basename of the source file.  An entry is made up
18721 of three fields:
18723 @itemize
18724 @item
18725 The name of the function.
18726 @item
18727 A number of bytes.
18728 @item
18729 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18730 @end itemize
18732 The qualifier @code{static} means that the function manipulates the stack
18733 statically: a fixed number of bytes are allocated for the frame on function
18734 entry and released on function exit; no stack adjustments are otherwise made
18735 in the function.  The second field is this fixed number of bytes.
18737 The qualifier @code{dynamic} means that the function manipulates the stack
18738 dynamically: in addition to the static allocation described above, stack
18739 adjustments are made in the body of the function, for example to push/pop
18740 arguments around function calls.  If the qualifier @code{bounded} is also
18741 present, the amount of these adjustments is bounded at compile-time and
18742 the second field is an upper bound of the total amount of stack used by
18743 the function.  If it is not present, the amount of these adjustments is
18744 not bounded at compile-time and the second field only represents the
18745 bounded part.
18747 @node Dynamic Stack Usage Analysis
18748 @section Dynamic Stack Usage Analysis
18750 @noindent
18751 It is possible to measure the maximum amount of stack used by a task, by
18752 adding a switch to @command{gnatbind}, as:
18754 @smallexample
18755 $ gnatbind -u0 file
18756 @end smallexample
18758 @noindent
18759 Here, as soon as a task ends, its stack usage will be printed on stderr. It's
18760 also possible to store a certain number of results to display them only at the
18761 end of the execution. The following command will display the 100 first results
18762 at the end of the programm, and others on the fly:
18764 @smallexample
18765 $ gnatbind -u100 file
18766 @end smallexample
18768 @noindent
18769 Results are displayed in the folowing format:
18771 @noindent
18772 INDEX | TASK NAME | STACK SIZE | MAX USAGE
18774 @noindent
18775 where:
18777 @table @emph
18778 @item INDEX
18779 is a number associated with each task. Numbers before n parameter given
18780 with -u flag correspond to stored results.
18782 @item TASK NAME
18783 is the name of the task analyzed.
18785 @item STACK SIZE
18786 is the maximum size for the stack. In order to prevent overflowed,
18787 this value is a little smaller than the real limit.
18789 @item MAX USAGE
18790 is the measure done by the stack analyzer.
18792 @end table
18794 @noindent
18795 The environment task stack, e.g. the stack that contains the main unit, is
18796 only processed when the environment variable GNAT_STACK_LIMIT is set.
18798 @node Creating Sample Bodies Using gnatstub
18799 @chapter Creating Sample Bodies Using @command{gnatstub}
18800 @findex gnatstub
18802 @noindent
18803 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18804 for library unit declarations.
18806 To create a body stub, @command{gnatstub} has to compile the library
18807 unit declaration. Therefore, bodies can be created only for legal
18808 library units. Moreover, if a library unit depends semantically upon
18809 units located outside the current directory, you have to provide
18810 the source search path when calling @command{gnatstub}, see the description
18811 of @command{gnatstub} switches below.
18813 @menu
18814 * Running gnatstub::
18815 * Switches for gnatstub::
18816 @end menu
18818 @node Running gnatstub
18819 @section Running @command{gnatstub}
18821 @noindent
18822 @command{gnatstub} has the command-line interface of the form
18824 @smallexample
18825 $ gnatstub [switches] filename [directory]
18826 @end smallexample
18828 @noindent
18829 where
18830 @table @emph
18831 @item filename
18832 is the name of the source file that contains a library unit declaration
18833 for which a body must be created. The file name may contain the path
18834 information.
18835 The file name does not have to follow the GNAT file name conventions. If the
18836 name
18837 does not follow GNAT file naming conventions, the name of the body file must
18838 be provided
18839 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18840 If the file name follows the GNAT file naming
18841 conventions and the name of the body file is not provided,
18842 @command{gnatstub}
18843 creates the name
18844 of the body file from the argument file name by replacing the @file{.ads}
18845 suffix
18846 with the @file{.adb} suffix.
18848 @item directory
18849 indicates the directory in which the body stub is to be placed (the default
18850 is the
18851 current directory)
18853 @item switches
18854 is an optional sequence of switches as described in the next section
18855 @end table
18857 @node Switches for gnatstub
18858 @section Switches for @command{gnatstub}
18860 @table @option
18861 @c !sort!
18863 @item ^-f^/FULL^
18864 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18865 If the destination directory already contains a file with the name of the
18866 body file
18867 for the argument spec file, replace it with the generated body stub.
18869 @item ^-hs^/HEADER=SPEC^
18870 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18871 Put the comment header (i.e., all the comments preceding the
18872 compilation unit) from the source of the library unit declaration
18873 into the body stub.
18875 @item ^-hg^/HEADER=GENERAL^
18876 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18877 Put a sample comment header into the body stub.
18879 @ifclear vms
18880 @item -IDIR
18881 @cindex @option{-IDIR} (@command{gnatstub})
18882 @itemx -I-
18883 @cindex @option{-I-} (@command{gnatstub})
18884 @end ifclear
18885 @ifset vms
18886 @item /NOCURRENT_DIRECTORY
18887 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18888 @end ifset
18889 ^These switches have ^This switch has^ the same meaning as in calls to
18890 @command{gcc}.
18891 ^They define ^It defines ^ the source search path in the call to
18892 @command{gcc} issued
18893 by @command{gnatstub} to compile an argument source file.
18895 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18896 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18897 This switch has the same meaning as in calls to @command{gcc}.
18898 It defines the additional configuration file to be passed to the call to
18899 @command{gcc} issued
18900 by @command{gnatstub} to compile an argument source file.
18902 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18903 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18904 (@var{n} is a non-negative integer). Set the maximum line length in the
18905 body stub to @var{n}; the default is 79. The maximum value that can be
18906 specified is 32767. Note that in the special case of configuration
18907 pragma files, the maximum is always 32767 regardless of whether or
18908 not this switch appears.
18910 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18911 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18912 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18913 the generated body sample to @var{n}.
18914 The default indentation is 3.
18916 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18917 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18918 Order local bodies alphabetically. (By default local bodies are ordered
18919 in the same way as the corresponding local specs in the argument spec file.)
18921 @item ^-i^/INDENTATION=^@var{n}
18922 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18923 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18925 @item ^-k^/TREE_FILE=SAVE^
18926 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18927 Do not remove the tree file (i.e., the snapshot of the compiler internal
18928 structures used by @command{gnatstub}) after creating the body stub.
18930 @item ^-l^/LINE_LENGTH=^@var{n}
18931 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18932 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18934 @item ^-o^/BODY=^@var{body-name}
18935 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18936 Body file name.  This should be set if the argument file name does not
18937 follow
18938 the GNAT file naming
18939 conventions. If this switch is omitted the default name for the body will be
18940 obtained
18941 from the argument file name according to the GNAT file naming conventions.
18943 @item ^-q^/QUIET^
18944 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18945 Quiet mode: do not generate a confirmation when a body is
18946 successfully created, and do not generate a message when a body is not
18947 required for an
18948 argument unit.
18950 @item ^-r^/TREE_FILE=REUSE^
18951 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18952 Reuse the tree file (if it exists) instead of creating it.  Instead of
18953 creating the tree file for the library unit declaration, @command{gnatstub}
18954 tries to find it in the current directory and use it for creating
18955 a body. If the tree file is not found, no body is created. This option
18956 also implies @option{^-k^/SAVE^}, whether or not
18957 the latter is set explicitly.
18959 @item ^-t^/TREE_FILE=OVERWRITE^
18960 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18961 Overwrite the existing tree file.  If the current directory already
18962 contains the file which, according to the GNAT file naming rules should
18963 be considered as a tree file for the argument source file,
18964 @command{gnatstub}
18965 will refuse to create the tree file needed to create a sample body
18966 unless this option is set.
18968 @item ^-v^/VERBOSE^
18969 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18970 Verbose mode: generate version information.
18972 @end table
18974 @node Other Utility Programs
18975 @chapter Other Utility Programs
18977 @noindent
18978 This chapter discusses some other utility programs available in the Ada
18979 environment.
18981 @menu
18982 * Using Other Utility Programs with GNAT::
18983 * The External Symbol Naming Scheme of GNAT::
18984 @ifclear vms
18985 * Ada Mode for Glide::
18986 @end ifclear
18987 * Converting Ada Files to html with gnathtml::
18988 * Installing gnathtml::
18989 @ifset vms
18990 * LSE::
18991 * Profiling::
18992 @end ifset
18993 @end menu
18995 @node Using Other Utility Programs with GNAT
18996 @section Using Other Utility Programs with GNAT
18998 @noindent
18999 The object files generated by GNAT are in standard system format and in
19000 particular the debugging information uses this format. This means
19001 programs generated by GNAT can be used with existing utilities that
19002 depend on these formats.
19004 @ifclear vms
19005 In general, any utility program that works with C will also often work with
19006 Ada programs generated by GNAT. This includes software utilities such as
19007 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19008 as Purify.
19009 @end ifclear
19011 @node The External Symbol Naming Scheme of GNAT
19012 @section The External Symbol Naming Scheme of GNAT
19014 @noindent
19015 In order to interpret the output from GNAT, when using tools that are
19016 originally intended for use with other languages, it is useful to
19017 understand the conventions used to generate link names from the Ada
19018 entity names.
19020 All link names are in all lowercase letters. With the exception of library
19021 procedure names, the mechanism used is simply to use the full expanded
19022 Ada name with dots replaced by double underscores. For example, suppose
19023 we have the following package spec:
19025 @smallexample @c ada
19026 @group
19027 @cartouche
19028 package QRS is
19029    MN : Integer;
19030 end QRS;
19031 @end cartouche
19032 @end group
19033 @end smallexample
19035 @noindent
19036 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19037 the corresponding link name is @code{qrs__mn}.
19038 @findex Export
19039 Of course if a @code{pragma Export} is used this may be overridden:
19041 @smallexample @c ada
19042 @group
19043 @cartouche
19044 package Exports is
19045    Var1 : Integer;
19046    pragma Export (Var1, C, External_Name => "var1_name");
19047    Var2 : Integer;
19048    pragma Export (Var2, C, Link_Name => "var2_link_name");
19049 end Exports;
19050 @end cartouche
19051 @end group
19052 @end smallexample
19054 @noindent
19055 In this case, the link name for @var{Var1} is whatever link name the
19056 C compiler would assign for the C function @var{var1_name}. This typically
19057 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19058 system conventions, but other possibilities exist. The link name for
19059 @var{Var2} is @var{var2_link_name}, and this is not operating system
19060 dependent.
19062 @findex _main
19063 One exception occurs for library level procedures. A potential ambiguity
19064 arises between the required name @code{_main} for the C main program,
19065 and the name we would otherwise assign to an Ada library level procedure
19066 called @code{Main} (which might well not be the main program).
19068 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19069 names. So if we have a library level procedure such as
19071 @smallexample @c ada
19072 @group
19073 @cartouche
19074 procedure Hello (S : String);
19075 @end cartouche
19076 @end group
19077 @end smallexample
19079 @noindent
19080 the external name of this procedure will be @var{_ada_hello}.
19082 @ifclear vms
19083 @node Ada Mode for Glide
19084 @section Ada Mode for @code{Glide}
19085 @cindex Ada mode (for Glide)
19087 @noindent
19088 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
19089 user to understand and navigate existing code, and facilitates writing
19090 new code. It furthermore provides some utility functions for easier
19091 integration of standard Emacs features when programming in Ada.
19093 Its general features include:
19095 @itemize @bullet
19096 @item
19097 An Integrated Development Environment with functionality such as the
19098 following
19100 @itemize @bullet
19101 @item
19102 ``Project files'' for configuration-specific aspects
19103 (e.g. directories and compilation options)
19105 @item
19106 Compiling and stepping through error messages.
19108 @item
19109 Running and debugging an applications within Glide.
19110 @end itemize
19112 @item
19113 Pull-down menus
19115 @item
19116 User configurability
19117 @end itemize
19119 Some of the specific Ada mode features are:
19121 @itemize @bullet
19122 @item
19123 Functions for easy and quick stepping through Ada code
19125 @item
19126 Getting cross reference information for identifiers (e.g., finding a
19127 defining occurrence)
19129 @item
19130 Displaying an index menu of types and subprograms, allowing
19131 direct selection for browsing
19133 @item
19134 Automatic color highlighting of the various Ada entities
19135 @end itemize
19137 Glide directly supports writing Ada code, via several facilities:
19139 @itemize @bullet
19140 @item
19141 Switching between spec and body files with possible
19142 autogeneration of body files
19144 @item
19145 Automatic formating of subprogram parameter lists
19147 @item
19148 Automatic indentation according to Ada syntax
19150 @item
19151 Automatic completion of identifiers
19153 @item
19154 Automatic (and configurable) casing of identifiers, keywords, and attributes
19156 @item
19157 Insertion of syntactic templates
19159 @item
19160 Block commenting / uncommenting
19161 @end itemize
19163 @noindent
19164 For more information, please refer to the online documentation
19165 available in the @code{Glide} @result{} @code{Help} menu.
19166 @end ifclear
19168 @node Converting Ada Files to html with gnathtml
19169 @section Converting Ada Files to HTML with @code{gnathtml}
19171 @noindent
19172 This @code{Perl} script allows Ada source files to be browsed using
19173 standard Web browsers. For installation procedure, see the section
19174 @xref{Installing gnathtml}.
19176 Ada reserved keywords are highlighted in a bold font and Ada comments in
19177 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19178 switch to suppress the generation of cross-referencing information, user
19179 defined variables and types will appear in a different color; you will
19180 be able to click on any identifier and go to its declaration.
19182 The command line is as follow:
19183 @smallexample
19184 $ perl gnathtml.pl [switches] ada-files
19185 @end smallexample
19187 @noindent
19188 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19189 an html file for every ada file, and a global file called @file{index.htm}.
19190 This file is an index of every identifier defined in the files.
19192 The available switches are the following ones :
19194 @table @option
19195 @item -83
19196 @cindex @option{-83} (@code{gnathtml})
19197 Only the subset on the Ada 83 keywords will be highlighted, not the full
19198 Ada 95 keywords set.
19200 @item -cc @var{color}
19201 @cindex @option{-cc} (@code{gnathtml})
19202 This option allows you to change the color used for comments. The default
19203 value is green. The color argument can be any name accepted by html.
19205 @item -d
19206 @cindex @option{-d} (@code{gnathtml})
19207 If the ada files depend on some other files (using for instance the
19208 @code{with} command, the latter will also be converted to html.
19209 Only the files in the user project will be converted to html, not the files
19210 in the run-time library itself.
19212 @item -D
19213 @cindex @option{-D} (@code{gnathtml})
19214 This command is the same as @option{-d} above, but @command{gnathtml} will
19215 also look for files in the run-time library, and generate html files for them.
19217 @item -ext @var{extension}
19218 @cindex @option{-ext} (@code{gnathtml})
19219 This option allows you to change the extension of the generated HTML files.
19220 If you do not specify an extension, it will default to @file{htm}.
19222 @item -f
19223 @cindex @option{-f} (@code{gnathtml})
19224 By default, gnathtml will generate html links only for global entities
19225 ('with'ed units, global variables and types,...). If you specify the
19226 @option{-f} on the command line, then links will be generated for local
19227 entities too.
19229 @item -l @var{number}
19230 @cindex @option{-l} (@code{gnathtml})
19231 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
19232 will number the html files every @var{number} line.
19234 @item -I @var{dir}
19235 @cindex @option{-I} (@code{gnathtml})
19236 Specify a directory to search for library files (@file{.ALI} files) and
19237 source files. You can provide several -I switches on the command line,
19238 and the directories will be parsed in the order of the command line.
19240 @item -o @var{dir}
19241 @cindex @option{-o} (@code{gnathtml})
19242 Specify the output directory for html files. By default, gnathtml will
19243 saved the generated html files in a subdirectory named @file{html/}.
19245 @item -p @var{file}
19246 @cindex @option{-p} (@code{gnathtml})
19247 If you are using Emacs and the most recent Emacs Ada mode, which provides
19248 a full Integrated Development Environment for compiling, checking,
19249 running and debugging applications, you may use @file{.gpr} files
19250 to give the directories where Emacs can find sources and object files.
19252 Using this switch, you can tell gnathtml to use these files. This allows
19253 you to get an html version of your application, even if it is spread
19254 over multiple directories.
19256 @item -sc @var{color}
19257 @cindex @option{-sc} (@code{gnathtml})
19258 This option allows you to change the color used for symbol definitions.
19259 The default value is red. The color argument can be any name accepted by html.
19261 @item -t @var{file}
19262 @cindex @option{-t} (@code{gnathtml})
19263 This switch provides the name of a file. This file contains a list of
19264 file names to be converted, and the effect is exactly as though they had
19265 appeared explicitly on the command line. This
19266 is the recommended way to work around the command line length limit on some
19267 systems.
19269 @end table
19271 @node Installing gnathtml
19272 @section Installing @code{gnathtml}
19274 @noindent
19275 @code{Perl} needs to be installed on your machine to run this script.
19276 @code{Perl} is freely available for almost every architecture and
19277 Operating System via the Internet.
19279 On Unix systems, you  may want to modify  the  first line of  the script
19280 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
19281 is. The syntax of this line is :
19282 @smallexample
19283 #!full_path_name_to_perl
19284 @end smallexample
19286 @noindent
19287 Alternatively, you may run the script using the following command line:
19289 @smallexample
19290 $ perl gnathtml.pl [switches] files
19291 @end smallexample
19293 @ifset vms
19294 @node LSE
19295 @section LSE
19296 @findex LSE
19298 @noindent
19299 The GNAT distribution provides an Ada 95 template for the HP Language
19300 Sensitive Editor (LSE), a component of DECset. In order to
19301 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19303 @node Profiling
19304 @section Profiling
19305 @findex PCA
19307 @noindent
19308 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19309 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19310 the collection phase with the /DEBUG qualifier.
19312 @smallexample
19313 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19314 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19315 $ RUN/DEBUG <PROGRAM_NAME>
19316 @end smallexample
19317 @noindent
19318 @end ifset
19320 @node Running and Debugging Ada Programs
19321 @chapter Running and Debugging Ada Programs
19322 @cindex Debugging
19324 @noindent
19325 This chapter discusses how to debug Ada programs.
19326 @ifset vms
19327 It applies to the Alpha OpenVMS platform;
19328 the debugger for Integrity OpenVMS is scheduled for a subsequent release.
19329 @end ifset
19331 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19333 @enumerate
19334 @item
19335 The illegality may be a violation of the static semantics of Ada. In
19336 that case GNAT diagnoses the constructs in the program that are illegal.
19337 It is then a straightforward matter for the user to modify those parts of
19338 the program.
19340 @item
19341 The illegality may be a violation of the dynamic semantics of Ada. In
19342 that case the program compiles and executes, but may generate incorrect
19343 results, or may terminate abnormally with some exception.
19345 @item
19346 When presented with a program that contains convoluted errors, GNAT
19347 itself may terminate abnormally without providing full diagnostics on
19348 the incorrect user program.
19349 @end enumerate
19351 @menu
19352 * The GNAT Debugger GDB::
19353 * Running GDB::
19354 * Introduction to GDB Commands::
19355 * Using Ada Expressions::
19356 * Calling User-Defined Subprograms::
19357 * Using the Next Command in a Function::
19358 * Ada Exceptions::
19359 * Ada Tasks::
19360 * Debugging Generic Units::
19361 * GNAT Abnormal Termination or Failure to Terminate::
19362 * Naming Conventions for GNAT Source Files::
19363 * Getting Internal Debugging Information::
19364 * Stack Traceback::
19365 @end menu
19367 @cindex Debugger
19368 @findex gdb
19370 @node The GNAT Debugger GDB
19371 @section The GNAT Debugger GDB
19373 @noindent
19374 @code{GDB} is a general purpose, platform-independent debugger that
19375 can be used to debug mixed-language programs compiled with @command{gcc},
19376 and in particular is capable of debugging Ada programs compiled with
19377 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19378 complex Ada data structures.
19380 The manual @cite{Debugging with GDB}
19381 @ifset vms
19382 , located in the GNU:[DOCS] directory,
19383 @end ifset
19384 contains full details on the usage of @code{GDB}, including a section on
19385 its usage on programs. This manual should be consulted for full
19386 details. The section that follows is a brief introduction to the
19387 philosophy and use of @code{GDB}.
19389 When GNAT programs are compiled, the compiler optionally writes debugging
19390 information into the generated object file, including information on
19391 line numbers, and on declared types and variables. This information is
19392 separate from the generated code. It makes the object files considerably
19393 larger, but it does not add to the size of the actual executable that
19394 will be loaded into memory, and has no impact on run-time performance. The
19395 generation of debug information is triggered by the use of the
19396 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19397 the compilations. It is important to emphasize that the use of these
19398 options does not change the generated code.
19400 The debugging information is written in standard system formats that
19401 are used by many tools, including debuggers and profilers. The format
19402 of the information is typically designed to describe C types and
19403 semantics, but GNAT implements a translation scheme which allows full
19404 details about Ada types and variables to be encoded into these
19405 standard C formats. Details of this encoding scheme may be found in
19406 the file exp_dbug.ads in the GNAT source distribution. However, the
19407 details of this encoding are, in general, of no interest to a user,
19408 since @code{GDB} automatically performs the necessary decoding.
19410 When a program is bound and linked, the debugging information is
19411 collected from the object files, and stored in the executable image of
19412 the program. Again, this process significantly increases the size of
19413 the generated executable file, but it does not increase the size of
19414 the executable program itself. Furthermore, if this program is run in
19415 the normal manner, it runs exactly as if the debug information were
19416 not present, and takes no more actual memory.
19418 However, if the program is run under control of @code{GDB}, the
19419 debugger is activated.  The image of the program is loaded, at which
19420 point it is ready to run.  If a run command is given, then the program
19421 will run exactly as it would have if @code{GDB} were not present. This
19422 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19423 entirely non-intrusive until a breakpoint is encountered.  If no
19424 breakpoint is ever hit, the program will run exactly as it would if no
19425 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19426 the debugging information and can respond to user commands to inspect
19427 variables, and more generally to report on the state of execution.
19429 @c **************
19430 @node Running GDB
19431 @section Running GDB
19433 @noindent
19434 The debugger can be launched directly and simply from @code{glide} or
19435 through its graphical interface: @code{gvd}. It can also be used
19436 directly in text mode. Here is described the basic use of @code{GDB}
19437 in text mode. All the commands described below can be used in the
19438 @code{gvd} console window even though there is usually other more
19439 graphical ways to achieve the same goals.
19441 @ifclear vms
19442 @noindent
19443 The command to run the graphical interface of the debugger is
19444 @smallexample
19445 $ gvd program
19446 @end smallexample
19447 @end ifclear
19449 @noindent
19450 The command to run @code{GDB} in text mode is
19452 @smallexample
19453 $ ^gdb program^$ GDB PROGRAM^
19454 @end smallexample
19456 @noindent
19457 where @code{^program^PROGRAM^} is the name of the executable file. This
19458 activates the debugger and results in a prompt for debugger commands.
19459 The simplest command is simply @code{run}, which causes the program to run
19460 exactly as if the debugger were not present. The following section
19461 describes some of the additional commands that can be given to @code{GDB}.
19463 @c *******************************
19464 @node Introduction to GDB Commands
19465 @section Introduction to GDB Commands
19467 @noindent
19468 @code{GDB} contains a large repertoire of commands. The manual
19469 @cite{Debugging with GDB}
19470 @ifset vms
19471 , located in the GNU:[DOCS] directory,
19472 @end ifset
19473 includes extensive documentation on the use
19474 of these commands, together with examples of their use. Furthermore,
19475 the command @var{help} invoked from within @code{GDB} activates a simple help
19476 facility which summarizes the available commands and their options.
19477 In this section we summarize a few of the most commonly
19478 used commands to give an idea of what @code{GDB} is about. You should create
19479 a simple program with debugging information and experiment with the use of
19480 these @code{GDB} commands on the program as you read through the
19481 following section.
19483 @table @code
19484 @item set args @var{arguments}
19485 The @var{arguments} list above is a list of arguments to be passed to
19486 the program on a subsequent run command, just as though the arguments
19487 had been entered on a normal invocation of the program. The @code{set args}
19488 command is not needed if the program does not require arguments.
19490 @item run
19491 The @code{run} command causes execution of the program to start from
19492 the beginning. If the program is already running, that is to say if
19493 you are currently positioned at a breakpoint, then a prompt will ask
19494 for confirmation that you want to abandon the current execution and
19495 restart.
19497 @item breakpoint @var{location}
19498 The breakpoint command sets a breakpoint, that is to say a point at which
19499 execution will halt and @code{GDB} will await further
19500 commands. @var{location} is
19501 either a line number within a file, given in the format @code{file:linenumber},
19502 or it is the name of a subprogram. If you request that a breakpoint be set on
19503 a subprogram that is overloaded, a prompt will ask you to specify on which of
19504 those subprograms you want to breakpoint. You can also
19505 specify that all of them should be breakpointed. If the program is run
19506 and execution encounters the breakpoint, then the program
19507 stops and @code{GDB} signals that the breakpoint was encountered by
19508 printing the line of code before which the program is halted.
19510 @item breakpoint exception @var{name}
19511 A special form of the breakpoint command which breakpoints whenever
19512 exception @var{name} is raised.
19513 If @var{name} is omitted,
19514 then a breakpoint will occur when any exception is raised.
19516 @item print @var{expression}
19517 This will print the value of the given expression. Most simple
19518 Ada expression formats are properly handled by @code{GDB}, so the expression
19519 can contain function calls, variables, operators, and attribute references.
19521 @item continue
19522 Continues execution following a breakpoint, until the next breakpoint or the
19523 termination of the program.
19525 @item step
19526 Executes a single line after a breakpoint. If the next statement
19527 is a subprogram call, execution continues into (the first statement of)
19528 the called subprogram.
19530 @item next
19531 Executes a single line. If this line is a subprogram call, executes and
19532 returns from the call.
19534 @item list
19535 Lists a few lines around the current source location. In practice, it
19536 is usually more convenient to have a separate edit window open with the
19537 relevant source file displayed. Successive applications of this command
19538 print subsequent lines. The command can be given an argument which is a
19539 line number, in which case it displays a few lines around the specified one.
19541 @item backtrace
19542 Displays a backtrace of the call chain. This command is typically
19543 used after a breakpoint has occurred, to examine the sequence of calls that
19544 leads to the current breakpoint. The display includes one line for each
19545 activation record (frame) corresponding to an active subprogram.
19547 @item up
19548 At a breakpoint, @code{GDB} can display the values of variables local
19549 to the current frame. The command @code{up} can be used to
19550 examine the contents of other active frames, by moving the focus up
19551 the stack, that is to say from callee to caller, one frame at a time.
19553 @item down
19554 Moves the focus of @code{GDB} down from the frame currently being
19555 examined to the frame of its callee (the reverse of the previous command),
19557 @item frame @var{n}
19558 Inspect the frame with the given number. The value 0 denotes the frame
19559 of the current breakpoint, that is to say the top of the call stack.
19561 @end table
19563 The above list is a very short introduction to the commands that
19564 @code{GDB} provides. Important additional capabilities, including conditional
19565 breakpoints, the ability to execute command sequences on a breakpoint,
19566 the ability to debug at the machine instruction level and many other
19567 features are described in detail in @cite{Debugging with GDB}.
19568 Note that most commands can be abbreviated
19569 (for example, c for continue, bt for backtrace).
19571 @node Using Ada Expressions
19572 @section Using Ada Expressions
19573 @cindex Ada expressions
19575 @noindent
19576 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19577 extensions. The philosophy behind the design of this subset is
19579 @itemize @bullet
19580 @item
19581 That @code{GDB} should provide basic literals and access to operations for
19582 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19583 leaving more sophisticated computations to subprograms written into the
19584 program (which therefore may be called from @code{GDB}).
19586 @item
19587 That type safety and strict adherence to Ada language restrictions
19588 are not particularly important to the @code{GDB} user.
19590 @item
19591 That brevity is important to the @code{GDB} user.
19592 @end itemize
19594 Thus, for brevity, the debugger acts as if there were
19595 implicit @code{with} and @code{use} clauses in effect for all user-written
19596 packages, thus making it unnecessary to fully qualify most names with
19597 their packages, regardless of context. Where this causes ambiguity,
19598 @code{GDB} asks the user's intent.
19600 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19602 @node Calling User-Defined Subprograms
19603 @section Calling User-Defined Subprograms
19605 @noindent
19606 An important capability of @code{GDB} is the ability to call user-defined
19607 subprograms while debugging. This is achieved simply by entering
19608 a subprogram call statement in the form:
19610 @smallexample
19611 call subprogram-name (parameters)
19612 @end smallexample
19614 @noindent
19615 The keyword @code{call} can be omitted in the normal case where the
19616 @code{subprogram-name} does not coincide with any of the predefined
19617 @code{GDB} commands.
19619 The effect is to invoke the given subprogram, passing it the
19620 list of parameters that is supplied. The parameters can be expressions and
19621 can include variables from the program being debugged. The
19622 subprogram must be defined
19623 at the library level within your program, and @code{GDB} will call the
19624 subprogram within the environment of your program execution (which
19625 means that the subprogram is free to access or even modify variables
19626 within your program).
19628 The most important use of this facility is in allowing the inclusion of
19629 debugging routines that are tailored to particular data structures
19630 in your program. Such debugging routines can be written to provide a suitably
19631 high-level description of an abstract type, rather than a low-level dump
19632 of its physical layout. After all, the standard
19633 @code{GDB print} command only knows the physical layout of your
19634 types, not their abstract meaning. Debugging routines can provide information
19635 at the desired semantic level and are thus enormously useful.
19637 For example, when debugging GNAT itself, it is crucial to have access to
19638 the contents of the tree nodes used to represent the program internally.
19639 But tree nodes are represented simply by an integer value (which in turn
19640 is an index into a table of nodes).
19641 Using the @code{print} command on a tree node would simply print this integer
19642 value, which is not very useful. But the PN routine (defined in file
19643 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19644 a useful high level representation of the tree node, which includes the
19645 syntactic category of the node, its position in the source, the integers
19646 that denote descendant nodes and parent node, as well as varied
19647 semantic information. To study this example in more detail, you might want to
19648 look at the body of the PN procedure in the stated file.
19650 @node Using the Next Command in a Function
19651 @section Using the Next Command in a Function
19653 @noindent
19654 When you use the @code{next} command in a function, the current source
19655 location will advance to the next statement as usual. A special case
19656 arises in the case of a @code{return} statement.
19658 Part of the code for a return statement is the ``epilog'' of the function.
19659 This is the code that returns to the caller. There is only one copy of
19660 this epilog code, and it is typically associated with the last return
19661 statement in the function if there is more than one return. In some
19662 implementations, this epilog is associated with the first statement
19663 of the function.
19665 The result is that if you use the @code{next} command from a return
19666 statement that is not the last return statement of the function you
19667 may see a strange apparent jump to the last return statement or to
19668 the start of the function. You should simply ignore this odd jump.
19669 The value returned is always that from the first return statement
19670 that was stepped through.
19672 @node Ada Exceptions
19673 @section Breaking on Ada Exceptions
19674 @cindex Exceptions
19676 @noindent
19677 You can set breakpoints that trip when your program raises
19678 selected exceptions.
19680 @table @code
19681 @item break exception
19682 Set a breakpoint that trips whenever (any task in the) program raises
19683 any exception.
19685 @item break exception @var{name}
19686 Set a breakpoint that trips whenever (any task in the) program raises
19687 the exception @var{name}.
19689 @item break exception unhandled
19690 Set a breakpoint that trips whenever (any task in the) program raises an
19691 exception for which there is no handler.
19693 @item info exceptions
19694 @itemx info exceptions @var{regexp}
19695 The @code{info exceptions} command permits the user to examine all defined
19696 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19697 argument, prints out only those exceptions whose name matches @var{regexp}.
19698 @end table
19700 @node Ada Tasks
19701 @section Ada Tasks
19702 @cindex Tasks
19704 @noindent
19705 @code{GDB} allows the following task-related commands:
19707 @table @code
19708 @item info tasks
19709 This command shows a list of current Ada tasks, as in the following example:
19711 @smallexample
19712 @iftex
19713 @leftskip=0cm
19714 @end iftex
19715 (gdb) info tasks
19716   ID       TID P-ID   Thread Pri State                 Name
19717    1   8088000   0   807e000  15 Child Activation Wait main_task
19718    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19719    3   809a800   1   80a4800  15 Child Activation Wait a
19720 *  4   80ae800   3   80b8000  15 Running               c
19721 @end smallexample
19723 @noindent
19724 In this listing, the asterisk before the first task indicates it to be the
19725 currently running task. The first column lists the task ID that is used
19726 to refer to tasks in the following commands.
19728 @item break @var{linespec} task @var{taskid}
19729 @itemx break @var{linespec} task @var{taskid} if @dots{}
19730 @cindex Breakpoints and tasks
19731 These commands are like the @code{break @dots{} thread @dots{}}.
19732 @var{linespec} specifies source lines.
19734 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19735 to specify that you only want @code{GDB} to stop the program when a
19736 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19737 numeric task identifiers assigned by @code{GDB}, shown in the first
19738 column of the @samp{info tasks} display.
19740 If you do not specify @samp{task @var{taskid}} when you set a
19741 breakpoint, the breakpoint applies to @emph{all} tasks of your
19742 program.
19744 You can use the @code{task} qualifier on conditional breakpoints as
19745 well; in this case, place @samp{task @var{taskid}} before the
19746 breakpoint condition (before the @code{if}).
19748 @item task @var{taskno}
19749 @cindex Task switching
19751 This command allows to switch to the task referred by @var{taskno}. In
19752 particular, This allows to browse the backtrace of the specified
19753 task. It is advised to switch back to the original task before
19754 continuing execution otherwise the scheduling of the program may be
19755 perturbated.
19756 @end table
19758 @noindent
19759 For more detailed information on the tasking support,
19760 see @cite{Debugging with GDB}.
19762 @node Debugging Generic Units
19763 @section Debugging Generic Units
19764 @cindex Debugging Generic Units
19765 @cindex Generics
19767 @noindent
19768 GNAT always uses code expansion for generic instantiation. This means that
19769 each time an instantiation occurs, a complete copy of the original code is
19770 made, with appropriate substitutions of formals by actuals.
19772 It is not possible to refer to the original generic entities in
19773 @code{GDB}, but it is always possible to debug a particular instance of
19774 a generic, by using the appropriate expanded names. For example, if we have
19776 @smallexample @c ada
19777 @group
19778 @cartouche
19779 procedure g is
19781    generic package k is
19782       procedure kp (v1 : in out integer);
19783    end k;
19785    package body k is
19786       procedure kp (v1 : in out integer) is
19787       begin
19788          v1 := v1 + 1;
19789       end kp;
19790    end k;
19792    package k1 is new k;
19793    package k2 is new k;
19795    var : integer := 1;
19797 begin
19798    k1.kp (var);
19799    k2.kp (var);
19800    k1.kp (var);
19801    k2.kp (var);
19802 end;
19803 @end cartouche
19804 @end group
19805 @end smallexample
19807 @noindent
19808 Then to break on a call to procedure kp in the k2 instance, simply
19809 use the command:
19811 @smallexample
19812 (gdb) break g.k2.kp
19813 @end smallexample
19815 @noindent
19816 When the breakpoint occurs, you can step through the code of the
19817 instance in the normal manner and examine the values of local variables, as for
19818 other units.
19820 @node GNAT Abnormal Termination or Failure to Terminate
19821 @section GNAT Abnormal Termination or Failure to Terminate
19822 @cindex GNAT Abnormal Termination or Failure to Terminate
19824 @noindent
19825 When presented with programs that contain serious errors in syntax
19826 or semantics,
19827 GNAT may on rare occasions  experience problems in operation, such
19828 as aborting with a
19829 segmentation fault or illegal memory access, raising an internal
19830 exception, terminating abnormally, or failing to terminate at all.
19831 In such cases, you can activate
19832 various features of GNAT that can help you pinpoint the construct in your
19833 program that is the likely source of the problem.
19835 The following strategies are presented in increasing order of
19836 difficulty, corresponding to your experience in using GNAT and your
19837 familiarity with compiler internals.
19839 @enumerate
19840 @item
19841 Run @command{gcc} with the @option{-gnatf}. This first
19842 switch causes all errors on a given line to be reported. In its absence,
19843 only the first error on a line is displayed.
19845 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19846 are encountered, rather than after compilation is terminated. If GNAT
19847 terminates prematurely or goes into an infinite loop, the last error
19848 message displayed may help to pinpoint the culprit.
19850 @item
19851 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19852 mode, @command{gcc} produces ongoing information about the progress of the
19853 compilation and provides the name of each procedure as code is
19854 generated. This switch allows you to find which Ada procedure was being
19855 compiled when it encountered a code generation problem.
19857 @item
19858 @cindex @option{-gnatdc} switch
19859 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19860 switch that does for the front-end what @option{^-v^VERBOSE^} does
19861 for the back end. The system prints the name of each unit,
19862 either a compilation unit or nested unit, as it is being analyzed.
19863 @item
19864 Finally, you can start
19865 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19866 front-end of GNAT, and can be run independently (normally it is just
19867 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19868 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19869 @code{where} command is the first line of attack; the variable
19870 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19871 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19872 which the execution stopped, and @code{input_file name} indicates the name of
19873 the source file.
19874 @end enumerate
19876 @node Naming Conventions for GNAT Source Files
19877 @section Naming Conventions for GNAT Source Files
19879 @noindent
19880 In order to examine the workings of the GNAT system, the following
19881 brief description of its organization may be helpful:
19883 @itemize @bullet
19884 @item
19885 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19887 @item
19888 All files prefixed with @file{^par^PAR^} are components of the parser. The
19889 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
19890 parsing of select statements can be found in @file{par-ch9.adb}.
19892 @item
19893 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19894 numbers correspond to chapters of the Ada standard. For example, all
19895 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19896 addition, some features of the language require sufficient special processing
19897 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19898 dynamic dispatching, etc.
19900 @item
19901 All files prefixed with @file{^exp^EXP^} perform normalization and
19902 expansion of the intermediate representation (abstract syntax tree, or AST).
19903 these files use the same numbering scheme as the parser and semantics files.
19904 For example, the construction of record initialization procedures is done in
19905 @file{exp_ch3.adb}.
19907 @item
19908 The files prefixed with @file{^bind^BIND^} implement the binder, which
19909 verifies the consistency of the compilation, determines an order of
19910 elaboration, and generates the bind file.
19912 @item
19913 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19914 data structures used by the front-end.
19916 @item
19917 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19918 the abstract syntax tree as produced by the parser.
19920 @item
19921 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19922 all entities, computed during semantic analysis.
19924 @item
19925 Library management issues are dealt with in files with prefix
19926 @file{^lib^LIB^}.
19928 @item
19929 @findex Ada
19930 @cindex Annex A
19931 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19932 defined in Annex A.
19934 @item
19935 @findex Interfaces
19936 @cindex Annex B
19937 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19938 defined in Annex B.
19940 @item
19941 @findex System
19942 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19943 both language-defined children and GNAT run-time routines.
19945 @item
19946 @findex GNAT
19947 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19948 general-purpose packages, fully documented in their specifications. All
19949 the other @file{.c} files are modifications of common @command{gcc} files.
19950 @end itemize
19952 @node Getting Internal Debugging Information
19953 @section Getting Internal Debugging Information
19955 @noindent
19956 Most compilers have internal debugging switches and modes. GNAT
19957 does also, except GNAT internal debugging switches and modes are not
19958 secret. A summary and full description of all the compiler and binder
19959 debug flags are in the file @file{debug.adb}. You must obtain the
19960 sources of the compiler to see the full detailed effects of these flags.
19962 The switches that print the source of the program (reconstructed from
19963 the internal tree) are of general interest for user programs, as are the
19964 options to print
19965 the full internal tree, and the entity table (the symbol table
19966 information). The reconstructed source provides a readable version of the
19967 program after the front-end has completed analysis and  expansion,
19968 and is useful when studying the performance of specific constructs.
19969 For example, constraint checks are indicated, complex aggregates
19970 are replaced with loops and assignments, and tasking primitives
19971 are replaced with run-time calls.
19973 @node Stack Traceback
19974 @section Stack Traceback
19975 @cindex traceback
19976 @cindex stack traceback
19977 @cindex stack unwinding
19979 @noindent
19980 Traceback is a mechanism to display the sequence of subprogram calls that
19981 leads to a specified execution point in a program. Often (but not always)
19982 the execution point is an instruction at which an exception has been raised.
19983 This mechanism is also known as @i{stack unwinding} because it obtains
19984 its information by scanning the run-time stack and recovering the activation
19985 records of all active subprograms. Stack unwinding is one of the most
19986 important tools for program debugging.
19988 The first entry stored in traceback corresponds to the deepest calling level,
19989 that is to say the subprogram currently executing the instruction
19990 from which we want to obtain the traceback.
19992 Note that there is no runtime performance penalty when stack traceback
19993 is enabled, and no exception is raised during program execution.
19995 @menu
19996 * Non-Symbolic Traceback::
19997 * Symbolic Traceback::
19998 @end menu
20000 @node Non-Symbolic Traceback
20001 @subsection Non-Symbolic Traceback
20002 @cindex traceback, non-symbolic
20004 @noindent
20005 Note: this feature is not supported on all platforms. See
20006 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20007 platforms.
20009 @menu
20010 * Tracebacks From an Unhandled Exception::
20011 * Tracebacks From Exception Occurrences (non-symbolic)::
20012 * Tracebacks From Anywhere in a Program (non-symbolic)::
20013 @end menu
20015 @node Tracebacks From an Unhandled Exception
20016 @subsubsection Tracebacks From an Unhandled Exception
20018 @noindent
20019 A runtime non-symbolic traceback is a list of addresses of call instructions.
20020 To enable this feature you must use the @option{-E}
20021 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20022 of exception information. You can retrieve this information using the
20023 @code{addr2line} tool.
20025 Here is a simple example:
20027 @smallexample @c ada
20028 @cartouche
20029 procedure STB is
20031    procedure P1 is
20032    begin
20033       raise Constraint_Error;
20034    end P1;
20036    procedure P2 is
20037    begin
20038       P1;
20039    end P2;
20041 begin
20042    P2;
20043 end STB;
20044 @end cartouche
20045 @end smallexample
20047 @smallexample
20048 $ gnatmake stb -bargs -E
20049 $ stb
20051 Execution terminated by unhandled exception
20052 Exception name: CONSTRAINT_ERROR
20053 Message: stb.adb:5
20054 Call stack traceback locations:
20055 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20056 @end smallexample
20058 @noindent
20059 As we see the traceback lists a sequence of addresses for the unhandled
20060 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20061 guess that this exception come from procedure P1. To translate these
20062 addresses into the source lines where the calls appear, the
20063 @code{addr2line} tool, described below, is invaluable. The use of this tool
20064 requires the program to be compiled with debug information.
20066 @smallexample
20067 $ gnatmake -g stb -bargs -E
20068 $ stb
20070 Execution terminated by unhandled exception
20071 Exception name: CONSTRAINT_ERROR
20072 Message: stb.adb:5
20073 Call stack traceback locations:
20074 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20076 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20077    0x4011f1 0x77e892a4
20079 00401373 at d:/stb/stb.adb:5
20080 0040138B at d:/stb/stb.adb:10
20081 0040139C at d:/stb/stb.adb:14
20082 00401335 at d:/stb/b~stb.adb:104
20083 004011C4 at /build/.../crt1.c:200
20084 004011F1 at /build/.../crt1.c:222
20085 77E892A4 in ?? at ??:0
20086 @end smallexample
20088 @noindent
20089 The @code{addr2line} tool has several other useful options:
20091 @table @code
20092 @item --functions
20093 to get the function name corresponding to any location
20095 @item --demangle=gnat
20096 to use the gnat decoding mode for the function names. Note that
20097 for binutils version 2.9.x the option is simply @option{--demangle}.
20098 @end table
20100 @smallexample
20101 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20102    0x40139c 0x401335 0x4011c4 0x4011f1
20104 00401373 in stb.p1 at d:/stb/stb.adb:5
20105 0040138B in stb.p2 at d:/stb/stb.adb:10
20106 0040139C in stb at d:/stb/stb.adb:14
20107 00401335 in main at d:/stb/b~stb.adb:104
20108 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20109 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20110 @end smallexample
20112 @noindent
20113 From this traceback we can see that the exception was raised in
20114 @file{stb.adb} at line 5, which was reached from a procedure call in
20115 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20116 which contains the call to the main program.
20117 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20118 and the output will vary from platform to platform.
20120 It is also possible to use @code{GDB} with these traceback addresses to debug
20121 the program. For example, we can break at a given code location, as reported
20122 in the stack traceback:
20124 @smallexample
20125 $ gdb -nw stb
20126 @ifclear vms
20127 @noindent
20128 Furthermore, this feature is not implemented inside Windows DLL. Only
20129 the non-symbolic traceback is reported in this case.
20130 @end ifclear
20132 (gdb) break *0x401373
20133 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20134 @end smallexample
20136 @noindent
20137 It is important to note that the stack traceback addresses
20138 do not change when debug information is included. This is particularly useful
20139 because it makes it possible to release software without debug information (to
20140 minimize object size), get a field report that includes a stack traceback
20141 whenever an internal bug occurs, and then be able to retrieve the sequence
20142 of calls with the same program compiled with debug information.
20144 @node Tracebacks From Exception Occurrences (non-symbolic)
20145 @subsubsection Tracebacks From Exception Occurrences
20147 @noindent
20148 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20149 The stack traceback is attached to the exception information string, and can
20150 be retrieved in an exception handler within the Ada program, by means of the
20151 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20153 @smallexample @c ada
20154 with Ada.Text_IO;
20155 with Ada.Exceptions;
20157 procedure STB is
20159    use Ada;
20160    use Ada.Exceptions;
20162    procedure P1 is
20163       K : Positive := 1;
20164    begin
20165       K := K - 1;
20166    exception
20167       when E : others =>
20168          Text_IO.Put_Line (Exception_Information (E));
20169    end P1;
20171    procedure P2 is
20172    begin
20173       P1;
20174    end P2;
20176 begin
20177    P2;
20178 end STB;
20179 @end smallexample
20181 @noindent
20182 This program will output:
20184 @smallexample
20185 $ stb
20187 Exception name: CONSTRAINT_ERROR
20188 Message: stb.adb:12
20189 Call stack traceback locations:
20190 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20191 @end smallexample
20193 @node Tracebacks From Anywhere in a Program (non-symbolic)
20194 @subsubsection Tracebacks From Anywhere in a Program
20196 @noindent
20197 It is also possible to retrieve a stack traceback from anywhere in a
20198 program. For this you need to
20199 use the @code{GNAT.Traceback} API. This package includes a procedure called
20200 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20201 display procedures described below. It is not necessary to use the
20202 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20203 is invoked explicitly.
20205 @noindent
20206 In the following example we compute a traceback at a specific location in
20207 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20208 convert addresses to strings:
20210 @smallexample @c ada
20211 with Ada.Text_IO;
20212 with GNAT.Traceback;
20213 with GNAT.Debug_Utilities;
20215 procedure STB is
20217    use Ada;
20218    use GNAT;
20219    use GNAT.Traceback;
20221    procedure P1 is
20222       TB  : Tracebacks_Array (1 .. 10);
20223       --  We are asking for a maximum of 10 stack frames.
20224       Len : Natural;
20225       --  Len will receive the actual number of stack frames returned.
20226    begin
20227       Call_Chain (TB, Len);
20229       Text_IO.Put ("In STB.P1 : ");
20231       for K in 1 .. Len loop
20232          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20233          Text_IO.Put (' ');
20234       end loop;
20236       Text_IO.New_Line;
20237    end P1;
20239    procedure P2 is
20240    begin
20241       P1;
20242    end P2;
20244 begin
20245    P2;
20246 end STB;
20247 @end smallexample
20249 @smallexample
20250 $ gnatmake -g stb
20251 $ stb
20253 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20254 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20255 @end smallexample
20257 @noindent
20258 You can then get further information by invoking the @code{addr2line}
20259 tool as described earlier (note that the hexadecimal addresses
20260 need to be specified in C format, with a leading ``0x'').
20262 @node Symbolic Traceback
20263 @subsection Symbolic Traceback
20264 @cindex traceback, symbolic
20266 @noindent
20267 A symbolic traceback is a stack traceback in which procedure names are
20268 associated with each code location.
20270 @noindent
20271 Note that this feature is not supported on all platforms. See
20272 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20273 list of currently supported platforms.
20275 @noindent
20276 Note that the symbolic traceback requires that the program be compiled
20277 with debug information. If it is not compiled with debug information
20278 only the non-symbolic information will be valid.
20280 @menu
20281 * Tracebacks From Exception Occurrences (symbolic)::
20282 * Tracebacks From Anywhere in a Program (symbolic)::
20283 @end menu
20285 @node Tracebacks From Exception Occurrences (symbolic)
20286 @subsubsection Tracebacks From Exception Occurrences
20288 @smallexample @c ada
20289 with Ada.Text_IO;
20290 with GNAT.Traceback.Symbolic;
20292 procedure STB is
20294    procedure P1 is
20295    begin
20296       raise Constraint_Error;
20297    end P1;
20299    procedure P2 is
20300    begin
20301       P1;
20302    end P2;
20304    procedure P3 is
20305    begin
20306       P2;
20307    end P3;
20309 begin
20310    P3;
20311 exception
20312    when E : others =>
20313       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20314 end STB;
20315 @end smallexample
20317 @smallexample
20318 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20319 $ stb
20321 0040149F in stb.p1 at stb.adb:8
20322 004014B7 in stb.p2 at stb.adb:13
20323 004014CF in stb.p3 at stb.adb:18
20324 004015DD in ada.stb at stb.adb:22
20325 00401461 in main at b~stb.adb:168
20326 004011C4 in __mingw_CRTStartup at crt1.c:200
20327 004011F1 in mainCRTStartup at crt1.c:222
20328 77E892A4 in ?? at ??:0
20329 @end smallexample
20331 @noindent
20332 In the above example the ``.\'' syntax in the @command{gnatmake} command
20333 is currently required by @command{addr2line} for files that are in
20334 the current working directory.
20335 Moreover, the exact sequence of linker options may vary from platform
20336 to platform.
20337 The above @option{-largs} section is for Windows platforms. By contrast,
20338 under Unix there is no need for the @option{-largs} section.
20339 Differences across platforms are due to details of linker implementation.
20341 @node Tracebacks From Anywhere in a Program (symbolic)
20342 @subsubsection Tracebacks From Anywhere in a Program
20344 @noindent
20345 It is possible to get a symbolic stack traceback
20346 from anywhere in a program, just as for non-symbolic tracebacks.
20347 The first step is to obtain a non-symbolic
20348 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20349 information. Here is an example:
20351 @smallexample @c ada
20352 with Ada.Text_IO;
20353 with GNAT.Traceback;
20354 with GNAT.Traceback.Symbolic;
20356 procedure STB is
20358    use Ada;
20359    use GNAT.Traceback;
20360    use GNAT.Traceback.Symbolic;
20362    procedure P1 is
20363       TB  : Tracebacks_Array (1 .. 10);
20364       --  We are asking for a maximum of 10 stack frames.
20365       Len : Natural;
20366       --  Len will receive the actual number of stack frames returned.
20367    begin
20368       Call_Chain (TB, Len);
20369       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20370    end P1;
20372    procedure P2 is
20373    begin
20374       P1;
20375    end P2;
20377 begin
20378    P2;
20379 end STB;
20380 @end smallexample
20382 @ifset vms
20383 @node Compatibility with HP Ada
20384 @chapter Compatibility with HP Ada
20385 @cindex Compatibility
20387 @noindent
20388 This section of the manual compares HP Ada for OpenVMS Alpha and GNAT
20389 OpenVMS Alpha. GNAT achieves a high level of compatibility
20390 with HP Ada, and it should generally be straightforward to port code
20391 from the HP Ada environment to GNAT. However, there are a few language
20392 and implementation differences of which the user must be aware. These
20393 differences are discussed in this section. In
20394 addition, the operating environment and command structure for the
20395 compiler are different, and these differences are also discussed.
20397 Note that this discussion addresses specifically the implementation
20398 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20399 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20400 GNAT always follows the Alpha implementation.
20402 @menu
20403 * Ada 95 Compatibility::
20404 * Differences in the Definition of Package System::
20405 * Language-Related Features::
20406 * The Package STANDARD::
20407 * The Package SYSTEM::
20408 * Tasking and Task-Related Features::
20409 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20410 * Pragmas and Pragma-Related Features::
20411 * Library of Predefined Units::
20412 * Bindings::
20413 * Main Program Definition::
20414 * Implementation-Defined Attributes::
20415 * Compiler and Run-Time Interfacing::
20416 * Program Compilation and Library Management::
20417 * Input-Output::
20418 * Implementation Limits::
20419 @end menu
20421 @node Ada 95 Compatibility
20422 @section Ada 95 Compatibility
20424 @noindent
20425 GNAT is an Ada 95 compiler, and HP Ada is an Ada 83
20426 compiler. Ada 95 is almost completely upwards compatible
20427 with Ada 83, and therefore Ada 83 programs will compile
20428 and run under GNAT with
20429 no changes or only minor changes. The Ada 95 Reference
20430 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
20431 incompatibilities.
20433 GNAT provides the switch /83 on the GNAT COMPILE command,
20434 as well as the pragma ADA_83, to force the compiler to
20435 operate in Ada 83 mode. This mode does not guarantee complete
20436 conformance to Ada 83, but in practice is sufficient to
20437 eliminate most sources of incompatibilities.
20438 In particular, it eliminates the recognition of the
20439 additional Ada 95 keywords, so that their use as identifiers
20440 in Ada83 program is legal, and handles the cases of packages
20441 with optional bodies, and generics that instantiate unconstrained
20442 types without the use of @code{(<>)}.
20444 @node Differences in the Definition of Package System
20445 @section Differences in the Definition of Package System
20447 @noindent
20448 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
20449 implementation-dependent declarations to package System. In normal mode,
20450 GNAT does not take advantage of this permission, and the version of System
20451 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
20453 However, HP Ada adds an extensive set of declarations to package System,
20454 as fully documented in the HP Ada manuals. To minimize changes required
20455 for programs that make use of these extensions, GNAT provides the pragma
20456 Extend_System for extending the definition of package System. By using:
20458 @smallexample @c ada
20459 @group
20460 @cartouche
20461 pragma Extend_System (Aux_DEC);
20462 @end cartouche
20463 @end group
20464 @end smallexample
20466 @noindent
20467 The set of definitions in System is extended to include those in package
20468 @code{System.Aux_DEC}.
20469 These definitions are incorporated directly into package
20470 System, as though they had been declared there in the first place. For a
20471 list of the declarations added, see the specification of this package,
20472 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
20473 The pragma Extend_System is a configuration pragma, which means that
20474 it can be placed in the file @file{gnat.adc}, so that it will automatically
20475 apply to all subsequent compilations. See the section on Configuration
20476 Pragmas for further details.
20478 An alternative approach that avoids the use of the non-standard
20479 Extend_System pragma is to add a context clause to the unit that
20480 references these facilities:
20482 @smallexample @c ada
20483 @group
20484 @cartouche
20485 with System.Aux_DEC;
20486 use  System.Aux_DEC;
20487 @end cartouche
20488 @end group
20489 @end smallexample
20491 @noindent
20492 The effect is not quite semantically identical to incorporating
20493 the declarations directly into package @code{System},
20494 but most programs will not notice a difference
20495 unless they use prefix notation (e.g. @code{System.Integer_8})
20496 to reference the
20497 entities directly in package @code{System}.
20498 For units containing such references,
20499 the prefixes must either be removed, or the pragma @code{Extend_System}
20500 must be used.
20502 @node Language-Related Features
20503 @section Language-Related Features
20505 @noindent
20506 The following sections highlight differences in types,
20507 representations of types, operations, alignment, and
20508 related topics.
20510 @menu
20511 * Integer Types and Representations::
20512 * Floating-Point Types and Representations::
20513 * Pragmas Float_Representation and Long_Float::
20514 * Fixed-Point Types and Representations::
20515 * Record and Array Component Alignment::
20516 * Address Clauses::
20517 * Other Representation Clauses::
20518 @end menu
20520 @node Integer Types and Representations
20521 @subsection Integer Types and Representations
20523 @noindent
20524 The set of predefined integer types is identical in HP Ada and GNAT.
20525 Furthermore the representation of these integer types is also identical,
20526 including the capability of size clauses forcing biased representation.
20528 In addition,
20529 HP Ada for OpenVMS Alpha systems has defined the
20530 following additional integer types in package System:
20532 @itemize @bullet
20534 @item
20535 INTEGER_8
20537 @item
20538 INTEGER_16
20540 @item
20541 INTEGER_32
20543 @item
20544 INTEGER_64
20546 @item
20547 LARGEST_INTEGER
20548 @end itemize
20550 @noindent
20551 When using GNAT, the first four of these types may be obtained from the
20552 standard Ada 95 package @code{Interfaces}.
20553 Alternatively, by use of the pragma
20554 @code{Extend_System}, identical
20555 declarations can be referenced directly in package @code{System}.
20556 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20558 @node Floating-Point Types and Representations
20559 @subsection Floating-Point Types and Representations
20560 @cindex Floating-Point types
20562 @noindent
20563 The set of predefined floating-point types is identical in HP Ada and GNAT.
20564 Furthermore the representation of these floating-point
20565 types is also identical. One important difference is that the default
20566 representation for HP Ada is VAX_Float, but the default representation
20567 for GNAT is IEEE.
20569 Specific types may be declared to be VAX_Float or IEEE, using the pragma
20570 @code{Float_Representation} as described in the HP Ada documentation.
20571 For example, the declarations:
20573 @smallexample @c ada
20574 @group
20575 @cartouche
20576 type F_Float is digits 6;
20577 pragma Float_Representation (VAX_Float, F_Float);
20578 @end cartouche
20579 @end group
20580 @end smallexample
20582 @noindent
20583 declare a type F_Float that will be represented in VAX_Float format.
20584 This set of declarations actually appears in System.Aux_DEC, which provides
20585 the full set of additional floating-point declarations provided in
20586 the HP Ada version of package
20587 System. This and similar declarations may be accessed in a user program
20588 by using pragma @code{Extend_System}. The use of this
20589 pragma, and the related pragma @code{Long_Float} is described in further
20590 detail in the following section.
20592 @node Pragmas Float_Representation and Long_Float
20593 @subsection Pragmas Float_Representation and Long_Float
20595 @noindent
20596 HP Ada provides the pragma @code{Float_Representation}, which
20597 acts as a program library switch to allow control over
20598 the internal representation chosen for the predefined
20599 floating-point types declared in the package @code{Standard}.
20600 The format of this pragma is as follows:
20602 @smallexample
20603 @group
20604 @cartouche
20605 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
20606 @end cartouche
20607 @end group
20608 @end smallexample
20610 @noindent
20611 This pragma controls the representation of floating-point
20612 types as follows:
20614 @itemize @bullet
20615 @item
20616 @code{VAX_Float} specifies that floating-point
20617 types are represented by default with the VAX system hardware types
20618 F-floating, D-floating, G-floating. Note that the H-floating
20619 type was available only on Vax systems, and is not available
20620 in either HP Ada or GNAT for Alpha systems.
20622 @item
20623 @code{IEEE_Float} specifies that floating-point
20624 types are represented by default with the IEEE single and
20625 double floating-point types.
20626 @end itemize
20628 @noindent
20629 GNAT provides an identical implementation of the pragma
20630 @code{Float_Representation}, except that it functions as a
20631 configuration pragma, as defined by Ada 95. Note that the
20632 notion of configuration pragma corresponds closely to the
20633 HP Ada notion of a program library switch.
20635 When no pragma is used in GNAT, the default is IEEE_Float, which is different
20636 from HP Ada 83, where the default is VAX_Float. In addition, the
20637 predefined libraries in GNAT are built using IEEE_Float, so it is not
20638 advisable to change the format of numbers passed to standard library
20639 routines, and if necessary explicit type conversions may be needed.
20641 The use of IEEE_Float is recommended in GNAT since it is more efficient,
20642 and (given that it conforms to an international standard) potentially more
20643 portable. The situation in which VAX_Float may be useful is in interfacing
20644 to existing code and data that expects the use of VAX_Float. There are
20645 two possibilities here. If the requirement for the use of VAX_Float is
20646 localized, then the best approach is to use the predefined VAX_Float
20647 types in package @code{System}, as extended by
20648 @code{Extend_System}. For example, use @code{System.F_Float}
20649 to specify the 32-bit @code{F-Float} format.
20651 Alternatively, if an entire program depends heavily on the use of
20652 the @code{VAX_Float} and in particular assumes that the types in
20653 package @code{Standard} are in @code{Vax_Float} format, then it
20654 may be desirable to reconfigure GNAT to assume Vax_Float by default.
20655 This is done by using the GNAT LIBRARY command to rebuild the library, and
20656 then using the general form of the @code{Float_Representation}
20657 pragma to ensure that this default format is used throughout.
20658 The form of the GNAT LIBRARY command is:
20660 @smallexample
20661 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
20662 @end smallexample
20664 @noindent
20665 where @i{file} contains the new configuration pragmas
20666 and @i{directory} is the directory to be created to contain
20667 the new library.
20669 @noindent
20670 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20671 to allow control over the internal representation chosen
20672 for the predefined type @code{Long_Float} and for floating-point
20673 type declarations with digits specified in the range 7 .. 15.
20674 The format of this pragma is as follows:
20676 @smallexample @c ada
20677 @cartouche
20678 pragma Long_Float (D_FLOAT | G_FLOAT);
20679 @end cartouche
20680 @end smallexample
20682 @node Fixed-Point Types and Representations
20683 @subsection Fixed-Point Types and Representations
20685 @noindent
20686 On HP Ada for OpenVMS Alpha systems, rounding is
20687 away from zero for both positive and negative numbers.
20688 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
20690 On GNAT for OpenVMS Alpha, the results of operations
20691 on fixed-point types are in accordance with the Ada 95
20692 rules. In particular, results of operations on decimal
20693 fixed-point types are truncated.
20695 @node Record and Array Component Alignment
20696 @subsection Record and Array Component Alignment
20698 @noindent
20699 On HP Ada for OpenVMS Alpha, all non composite components
20700 are aligned on natural boundaries. For example, 1-byte
20701 components are aligned on byte boundaries, 2-byte
20702 components on 2-byte boundaries, 4-byte components on 4-byte
20703 byte boundaries, and so on. The OpenVMS Alpha hardware
20704 runs more efficiently with naturally aligned data.
20706 ON GNAT for OpenVMS Alpha, alignment rules are compatible
20707 with HP Ada for OpenVMS Alpha.
20709 @node Address Clauses
20710 @subsection Address Clauses
20712 @noindent
20713 In HP Ada and GNAT, address clauses are supported for
20714 objects and imported subprograms.
20715 The predefined type @code{System.Address} is a private type
20716 in both compilers, with the same representation (it is simply
20717 a machine pointer). Addition, subtraction, and comparison
20718 operations are available in the standard Ada 95 package
20719 @code{System.Storage_Elements}, or in package @code{System}
20720 if it is extended to include @code{System.Aux_DEC} using a
20721 pragma @code{Extend_System} as previously described.
20723 Note that code that with's both this extended package @code{System}
20724 and the package @code{System.Storage_Elements} should not @code{use}
20725 both packages, or ambiguities will result. In general it is better
20726 not to mix these two sets of facilities. The Ada 95 package was
20727 designed specifically to provide the kind of features that HP Ada
20728 adds directly to package @code{System}.
20730 GNAT is compatible with HP Ada in its handling of address
20731 clauses, except for some limitations in
20732 the form of address clauses for composite objects with
20733 initialization. Such address clauses are easily replaced
20734 by the use of an explicitly-defined constant as described
20735 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
20736 of declarations:
20738 @smallexample @c ada
20739 @cartouche
20740 X, Y : Integer := Init_Func;
20741 Q : String (X .. Y) := "abc";
20743 for Q'Address use Compute_Address;
20744 @end cartouche
20745 @end smallexample
20747 @noindent
20748 will be rejected by GNAT, since the address cannot be computed at the time
20749 that Q is declared. To achieve the intended effect, write instead:
20751 @smallexample @c ada
20752 @group
20753 @cartouche
20754 X, Y : Integer := Init_Func;
20755 Q_Address : constant Address := Compute_Address;
20756 Q : String (X .. Y) := "abc";
20758 for Q'Address use Q_Address;
20759 @end cartouche
20760 @end group
20761 @end smallexample
20763 @noindent
20764 which will be accepted by GNAT (and other Ada 95 compilers), and is also
20765 backwards compatible with Ada 83. A fuller description of the restrictions
20766 on address specifications is found in the GNAT Reference Manual.
20768 @node Other Representation Clauses
20769 @subsection Other Representation Clauses
20771 @noindent
20772 GNAT supports in a compatible manner all the representation
20773 clauses supported by HP Ada. In addition, it
20774 supports representation clause forms that are new in Ada 95
20775 including COMPONENT_SIZE and SIZE clauses for objects.
20777 @node The Package STANDARD
20778 @section The Package STANDARD
20780 @noindent
20781 The package STANDARD, as implemented by HP Ada, is fully
20782 described in the Reference Manual for the Ada Programming
20783 Language (ANSI/MIL-STD-1815A-1983) and in the HP Ada
20784 Language Reference Manual. As implemented by GNAT, the
20785 package STANDARD is described in the Ada 95 Reference
20786 Manual.
20788 In addition, HP Ada supports the Latin-1 character set in
20789 the type CHARACTER. GNAT supports the Latin-1 character set
20790 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
20791 the type WIDE_CHARACTER.
20793 The floating-point types supported by GNAT are those
20794 supported by HP Ada, but defaults are different, and are controlled by
20795 pragmas. See @ref{Floating-Point Types and Representations} for details.
20797 @node The Package SYSTEM
20798 @section The Package SYSTEM
20800 @noindent
20801 HP Ada provides a system-specific version of the package
20802 SYSTEM for each platform on which the language ships.
20803 For the complete specification of the package SYSTEM, see
20804 Appendix F of the HP Ada Language Reference Manual.
20806 On HP Ada, the package SYSTEM includes the following conversion functions:
20807 @itemize @bullet
20808 @item TO_ADDRESS(INTEGER)
20810 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
20812 @item  TO_ADDRESS(universal_integer)
20814 @item  TO_INTEGER(ADDRESS)
20816 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
20818 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
20819                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
20820 @end itemize
20822 @noindent
20823 By default, GNAT supplies a version of SYSTEM that matches
20824 the definition given in the Ada 95 Reference Manual.
20825 This
20826 is a subset of the HP system definitions, which is as
20827 close as possible to the original definitions. The only difference
20828 is that the definition of SYSTEM_NAME is different:
20830 @smallexample @c ada
20831 @group
20832 @cartouche
20833 type Name is (SYSTEM_NAME_GNAT);
20834 System_Name : constant Name := SYSTEM_NAME_GNAT;
20835 @end cartouche
20836 @end group
20837 @end smallexample
20839 @noindent
20840 Also, GNAT adds the new Ada 95 declarations for
20841 BIT_ORDER and DEFAULT_BIT_ORDER.
20843 However, the use of the following pragma causes GNAT
20844 to extend the definition of package SYSTEM so that it
20845 encompasses the full set of HP-specific extensions,
20846 including the functions listed above:
20848 @smallexample @c ada
20849 @cartouche
20850 pragma Extend_System (Aux_DEC);
20851 @end cartouche
20852 @end smallexample
20854 @noindent
20855 The pragma Extend_System is a configuration pragma that
20856 is most conveniently placed in the @file{gnat.adc} file. See the
20857 GNAT Reference Manual for further details.
20859 HP Ada does not allow the recompilation of the package
20860 SYSTEM. Instead HP Ada provides several pragmas (SYSTEM_
20861 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
20862 the package SYSTEM. On OpenVMS Alpha systems, the pragma
20863 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
20864 its single argument.
20866 GNAT does permit the recompilation of package SYSTEM using
20867 a special switch (@option{-gnatg}) and this switch can be used if
20868 it is necessary to modify the definitions in SYSTEM. GNAT does
20869 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
20870 or MEMORY_SIZE by any other means.
20872 On GNAT systems, the pragma SYSTEM_NAME takes the
20873 enumeration literal SYSTEM_NAME_GNAT.
20875 The definitions provided by the use of
20877 @smallexample @c ada
20878 pragma Extend_System (AUX_Dec);
20879 @end smallexample
20881 @noindent
20882 are virtually identical to those provided by the HP Ada 83 package
20883 System. One important difference is that the name of the TO_ADDRESS
20884 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
20885 See the GNAT Reference manual for a discussion of why this change was
20886 necessary.
20888 @noindent
20889 The version of TO_ADDRESS taking a universal integer argument is in fact
20890 an extension to Ada 83 not strictly compatible with the reference manual.
20891 In GNAT, we are constrained to be exactly compatible with the standard,
20892 and this means we cannot provide this capability. In HP Ada 83, the
20893 point of this definition is to deal with a call like:
20895 @smallexample @c ada
20896 TO_ADDRESS (16#12777#);
20897 @end smallexample
20899 @noindent
20900 Normally, according to the Ada 83 standard, one would expect this to be
20901 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
20902 of TO_ADDRESS. However, in HP Ada 83, there is no ambiguity, since the
20903 definition using universal_integer takes precedence.
20905 In GNAT, since the version with universal_integer cannot be supplied, it is
20906 not possible to be 100% compatible. Since there are many programs using
20907 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
20908 to change the name of the function in the UNSIGNED_LONGWORD case, so the
20909 declarations provided in the GNAT version of AUX_Dec are:
20911 @smallexample @c ada
20912 function To_Address (X : Integer) return Address;
20913 pragma Pure_Function (To_Address);
20915 function To_Address_Long (X : Unsigned_Longword) return Address;
20916 pragma Pure_Function (To_Address_Long);
20917 @end smallexample
20919 @noindent
20920 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
20921 change the name to TO_ADDRESS_LONG.
20923 @node Tasking and Task-Related Features
20924 @section Tasking and Task-Related Features
20926 @noindent
20927 The concepts relevant to a comparison of tasking on GNAT
20928 and on HP Ada for OpenVMS Alpha systems are discussed in
20929 the following sections.
20931 For detailed information on concepts related to tasking in
20932 HP Ada, see the HP Ada Language Reference Manual and the
20933 relevant run-time reference manual.
20935 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20936 @section Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20938 @noindent
20939 On OpenVMS Alpha systems, each Ada task (except a passive
20940 task) is implemented as a single stream of execution
20941 that is created and managed by the kernel. On these
20942 systems, HP Ada tasking support is based on DECthreads,
20943 an implementation of the POSIX standard for threads.
20945 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20946 code that calls DECthreads routines can be used together.
20947 The interaction between Ada tasks and DECthreads routines
20948 can have some benefits. For example when on OpenVMS Alpha,
20949 HP Ada can call C code that is already threaded.
20950 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
20951 and Ada tasks are mapped to threads.
20953 @menu
20954 * Assigning Task IDs::
20955 * Task IDs and Delays::
20956 * Task-Related Pragmas::
20957 * Scheduling and Task Priority::
20958 * The Task Stack::
20959 * External Interrupts::
20960 @end menu
20962 @node Assigning Task IDs
20963 @subsection Assigning Task IDs
20965 @noindent
20966 The HP Ada Run-Time Library always assigns %TASK 1 to
20967 the environment task that executes the main program. On
20968 OpenVMS Alpha systems, %TASK 0 is often used for tasks
20969 that have been created but are not yet activated.
20971 On OpenVMS Alpha systems, task IDs are assigned at
20972 activation. On GNAT systems, task IDs are also assigned at
20973 task creation but do not have the same form or values as
20974 task ID values in HP Ada. There is no null task, and the
20975 environment task does not have a specific task ID value.
20977 @node Task IDs and Delays
20978 @subsection Task IDs and Delays
20980 @noindent
20981 On OpenVMS Alpha systems, tasking delays are implemented
20982 using Timer System Services. The Task ID is used for the
20983 identification of the timer request (the REQIDT parameter).
20984 If Timers are used in the application take care not to use
20985 0 for the identification, because cancelling such a timer
20986 will cancel all timers and may lead to unpredictable results.
20988 @node Task-Related Pragmas
20989 @subsection Task-Related Pragmas
20991 @noindent
20992 Ada supplies the pragma TASK_STORAGE, which allows
20993 specification of the size of the guard area for a task
20994 stack. (The guard area forms an area of memory that has no
20995 read or write access and thus helps in the detection of
20996 stack overflow.) On OpenVMS Alpha systems, if the pragma
20997 TASK_STORAGE specifies a value of zero, a minimal guard
20998 area is created. In the absence of a pragma TASK_STORAGE, a default guard
20999 area is created.
21001 GNAT supplies the following task-related pragmas:
21003 @itemize @bullet
21004 @item  TASK_INFO
21006               This pragma appears within a task definition and
21007               applies to the task in which it appears. The argument
21008               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
21010 @item  TASK_STORAGE
21012               GNAT implements pragma TASK_STORAGE in the same way as
21013               HP Ada.
21014               Both HP Ada and GNAT supply the pragmas PASSIVE,
21015               SUPPRESS, and VOLATILE.
21016 @end itemize
21017 @node Scheduling and Task Priority
21018 @subsection Scheduling and Task Priority
21020 @noindent
21021 HP Ada implements the Ada language requirement that
21022 when two tasks are eligible for execution and they have
21023 different priorities, the lower priority task does not
21024 execute while the higher priority task is waiting. The HP
21025 Ada Run-Time Library keeps a task running until either the
21026 task is suspended or a higher priority task becomes ready.
21028 On OpenVMS Alpha systems, the default strategy is round-
21029 robin with preemption. Tasks of equal priority take turns
21030 at the processor. A task is run for a certain period of
21031 time and then placed at the rear of the ready queue for
21032 its priority level.
21034 HP Ada provides the implementation-defined pragma TIME_SLICE,
21035 which can be used to enable or disable round-robin
21036 scheduling of tasks with the same priority.
21037 See the relevant HP Ada run-time reference manual for
21038 information on using the pragmas to control HP Ada task
21039 scheduling.
21041 GNAT follows the scheduling rules of Annex D (real-time
21042 Annex) of the Ada 95 Reference Manual. In general, this
21043 scheduling strategy is fully compatible with HP Ada
21044 although it provides some additional constraints (as
21045 fully documented in Annex D).
21046 GNAT implements time slicing control in a manner compatible with
21047 HP Ada 83, by means of the pragma Time_Slice, whose semantics are identical
21048 to the HP Ada 83 pragma of the same name.
21049 Note that it is not possible to mix GNAT tasking and
21050 HP Ada 83 tasking in the same program, since the two run times are
21051 not compatible.
21053 @node The Task Stack
21054 @subsection The Task Stack
21056 @noindent
21057 In HP Ada, a task stack is allocated each time a
21058 non passive task is activated. As soon as the task is
21059 terminated, the storage for the task stack is deallocated.
21060 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
21061 a default stack size is used. Also, regardless of the size
21062 specified, some additional space is allocated for task
21063 management purposes. On OpenVMS Alpha systems, at least
21064 one page is allocated.
21066 GNAT handles task stacks in a similar manner. According to
21067 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
21068 an alternative method for controlling the task stack size.
21069 The specification of the attribute T'STORAGE_SIZE is also
21070 supported in a manner compatible with HP Ada.
21072 @node External Interrupts
21073 @subsection External Interrupts
21075 @noindent
21076 On HP Ada, external interrupts can be associated with task entries.
21077 GNAT is compatible with HP Ada in its handling of external interrupts.
21079 @node Pragmas and Pragma-Related Features
21080 @section Pragmas and Pragma-Related Features
21082 @noindent
21083 Both HP Ada and GNAT supply all language-defined pragmas
21084 as specified by the Ada 83 standard. GNAT also supplies all
21085 language-defined pragmas specified in the Ada 95 Reference Manual.
21086 In addition, GNAT implements the implementation-defined pragmas
21087 from HP Ada 83.
21089 @itemize @bullet
21090 @item  AST_ENTRY
21092 @item  COMMON_OBJECT
21094 @item  COMPONENT_ALIGNMENT
21096 @item  EXPORT_EXCEPTION
21098 @item  EXPORT_FUNCTION
21100 @item  EXPORT_OBJECT
21102 @item  EXPORT_PROCEDURE
21104 @item  EXPORT_VALUED_PROCEDURE
21106 @item  FLOAT_REPRESENTATION
21108 @item  IDENT
21110 @item  IMPORT_EXCEPTION
21112 @item  IMPORT_FUNCTION
21114 @item  IMPORT_OBJECT
21116 @item  IMPORT_PROCEDURE
21118 @item  IMPORT_VALUED_PROCEDURE
21120 @item  INLINE_GENERIC
21122 @item  INTERFACE_NAME
21124 @item  LONG_FLOAT
21126 @item  MAIN_STORAGE
21128 @item  PASSIVE
21130 @item  PSET_OBJECT
21132 @item  SHARE_GENERIC
21134 @item  SUPPRESS_ALL
21136 @item  TASK_STORAGE
21138 @item  TIME_SLICE
21140 @item  TITLE
21141 @end itemize
21143 @noindent
21144 These pragmas are all fully implemented, with the exception of @code{Title},
21145 @code{Passive}, and @code{Share_Generic}, which are
21146 recognized, but which have no
21147 effect in GNAT. The effect of @code{Passive} may be obtained by the
21148 use of protected objects in Ada 95. In GNAT, all generics are inlined.
21150 Unlike HP Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
21151 a separate subprogram specification which must appear before the
21152 subprogram body.
21154 GNAT also supplies a number of implementation-defined pragmas as follows:
21155 @itemize @bullet
21156 @item  C_PASS_BY_COPY
21158 @item  EXTEND_SYSTEM
21160 @item  SOURCE_FILE_NAME
21162 @item  UNSUPPRESS
21164 @item  WARNINGS
21166 @item  ABORT_DEFER
21168 @item  ADA_83
21170 @item  ADA_95
21172 @item  ADA_05
21174 @item  ANNOTATE
21176 @item  ASSERT
21178 @item  CPP_CLASS
21180 @item  CPP_CONSTRUCTOR
21182 @item  CPP_DESTRUCTOR
21184 @item  CPP_VIRTUAL
21186 @item  CP_VTABLE
21188 @item  DEBUG
21190 @item  LINKER_ALIAS
21192 @item  LINKER_SECTION
21194 @item  MACHINE_ATTRIBUTE
21196 @item  NO_RETURN
21198 @item  PURE_FUNCTION
21200 @item  SOURCE_REFERENCE
21202 @item  TASK_INFO
21204 @item  UNCHECKED_UNION
21206 @item  UNIMPLEMENTED_UNIT
21208 @item  UNIVERSAL_DATA
21210 @item  WEAK_EXTERNAL
21211 @end itemize
21213 @noindent
21214 For full details on these GNAT implementation-defined pragmas, see
21215 the GNAT Reference Manual.
21217 @menu
21218 * Restrictions on the Pragma INLINE::
21219 * Restrictions on the Pragma INTERFACE::
21220 * Restrictions on the Pragma SYSTEM_NAME::
21221 @end menu
21223 @node Restrictions on the Pragma INLINE
21224 @subsection Restrictions on the Pragma INLINE
21226 @noindent
21227 HP Ada applies the following restrictions to the pragma INLINE:
21228 @itemize @bullet
21229 @item  Parameters cannot be a task type.
21231 @item  Function results cannot be task types, unconstrained
21232 array types, or unconstrained types with discriminants.
21234 @item  Bodies cannot declare the following:
21235 @itemize @bullet
21236 @item  Subprogram body or stub (imported subprogram is allowed)
21238 @item  Tasks
21240 @item  Generic declarations
21242 @item  Instantiations
21244 @item  Exceptions
21246 @item  Access types (types derived from access types allowed)
21248 @item  Array or record types
21250 @item  Dependent tasks
21252 @item  Direct recursive calls of subprogram or containing
21253 subprogram, directly or via a renaming
21255 @end itemize
21256 @end itemize
21258 @noindent
21259 In GNAT, the only restriction on pragma INLINE is that the
21260 body must occur before the call if both are in the same
21261 unit, and the size must be appropriately small. There are
21262 no other specific restrictions which cause subprograms to
21263 be incapable of being inlined.
21265 @node  Restrictions on the Pragma INTERFACE
21266 @subsection  Restrictions on the Pragma INTERFACE
21268 @noindent
21269 The following lists and describes the restrictions on the
21270 pragma INTERFACE on HP Ada and GNAT:
21271 @itemize @bullet
21272 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21273 Default is the default on OpenVMS Alpha systems.
21275 @item  Parameter passing: Language specifies default
21276 mechanisms but can be overridden with an EXPORT pragma.
21278 @itemize @bullet
21279 @item  Ada: Use internal Ada rules.
21281 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21282 record or task type. Result cannot be a string, an
21283 array, or a record.
21285 @item  Fortran: Parameters cannot be a task. Result cannot
21286 be a string, an array, or a record.
21287 @end itemize
21288 @end itemize
21290 @noindent
21291 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21292 record parameters for all languages.
21294 @node  Restrictions on the Pragma SYSTEM_NAME
21295 @subsection  Restrictions on the Pragma SYSTEM_NAME
21297 @noindent
21298 For HP Ada for OpenVMS Alpha, the enumeration literal
21299 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
21300 literal for the type NAME is SYSTEM_NAME_GNAT.
21302 @node  Library of Predefined Units
21303 @section  Library of Predefined Units
21305 @noindent
21306 A library of predefined units is provided as part of the
21307 HP Ada and GNAT implementations. HP Ada does not provide
21308 the package MACHINE_CODE but instead recommends importing
21309 assembler code.
21311 The GNAT versions of the HP Ada Run-Time Library (ADA$PREDEFINED:)
21312 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21313 version. During GNAT installation, the HP Ada Predefined
21314 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
21315 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
21316 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
21317 for details.
21319 The GNAT RTL is contained in
21320 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
21321 the default search path is set up to find DECLIB units in preference
21322 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
21323 for example).
21325 However, it is possible to change the default so that the
21326 reverse is true, or even to mix them using child package
21327 notation. The HP Ada 83 units are available as DEC.xxx where xxx
21328 is the package name, and the Ada units are available in the
21329 standard manner defined for Ada 95, that is to say as DEC.xxx. To
21330 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
21331 appropriately. For example, to change the default to use the Ada95
21332 versions do:
21334 @smallexample
21335 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
21336                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
21337 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
21338                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
21339 @end smallexample
21341 @menu
21342 * Changes to DECLIB::
21343 @end menu
21345 @node Changes to DECLIB
21346 @subsection Changes to DECLIB
21348 @noindent
21349 The changes made to the HP Ada predefined library for GNAT and Ada 95
21350 compatibility are minor and include the following:
21352 @itemize @bullet
21353 @item  Adjusting the location of pragmas and record representation
21354 clauses to obey Ada 95 rules
21356 @item  Adding the proper notation to generic formal parameters
21357 that take unconstrained types in instantiation
21359 @item  Adding pragma ELABORATE_BODY to package specifications
21360 that have package bodies not otherwise allowed
21362 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
21363 @code{"PROTECTD"}.
21364 Currently these are found only in the STARLET package spec.
21365 @end itemize
21367 @noindent
21368 None of the above changes is visible to users.
21370 @node Bindings
21371 @section Bindings
21373 @noindent
21374 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21375 @itemize @bullet
21377 @item  Command Language Interpreter (CLI interface)
21379 @item  DECtalk Run-Time Library (DTK interface)
21381 @item  Librarian utility routines (LBR interface)
21383 @item  General Purpose Run-Time Library (LIB interface)
21385 @item  Math Run-Time Library (MTH interface)
21387 @item  National Character Set Run-Time Library (NCS interface)
21389 @item  Compiled Code Support Run-Time Library (OTS interface)
21391 @item  Parallel Processing Run-Time Library (PPL interface)
21393 @item  Screen Management Run-Time Library (SMG interface)
21395 @item  Sort Run-Time Library (SOR interface)
21397 @item  String Run-Time Library (STR interface)
21399 @item STARLET System Library
21400 @findex Starlet
21402 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21404 @item  X Windows Toolkit (XT interface)
21406 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21407 @end itemize
21409 @noindent
21410 GNAT provides implementations of these HP bindings in the DECLIB directory.
21412 The X/Motif bindings used to build DECLIB are whatever versions are in the
21413 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21414 The build script will
21415 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
21416 and @code{X_Lib}
21417 causing the default X/Motif sharable image libraries to be linked in. This
21418 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21419 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21421 It may be necessary to edit these options files to update or correct the
21422 library names if, for example, the newer X/Motif bindings from
21423 @file{ADA$EXAMPLES}
21424 had been (previous to installing GNAT) copied and renamed to supersede the
21425 default @file{ADA$PREDEFINED} versions.
21427 @menu
21428 * Shared Libraries and Options Files::
21429 * Interfaces to C::
21430 @end menu
21432 @node Shared Libraries and Options Files
21433 @subsection Shared Libraries and Options Files
21435 @noindent
21436 When using the HP Ada
21437 predefined X and Motif bindings, the linking with their sharable images is
21438 done automatically by @command{GNAT LINK}.
21439 When using other X and Motif bindings, you need
21440 to add the corresponding sharable images to the command line for
21441 @code{GNAT LINK}. When linking with shared libraries, or with
21442 @file{.OPT} files, you must
21443 also add them to the command line for @command{GNAT LINK}.
21445 A shared library to be used with GNAT is built in the same way as other
21446 libraries under VMS. The VMS Link command can be used in standard fashion.
21448 @node Interfaces to C
21449 @subsection Interfaces to C
21451 @noindent
21452 HP Ada
21453 provides the following Ada types and operations:
21455 @itemize @bullet
21456 @item C types package (C_TYPES)
21458 @item C strings (C_TYPES.NULL_TERMINATED)
21460 @item Other_types (SHORT_INT)
21461 @end itemize
21463 @noindent
21464 Interfacing to C with GNAT, one can use the above approach
21465 described for HP Ada or the facilities of Annex B of
21466 the Ada 95 Reference Manual (packages INTERFACES.C,
21467 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
21468 information, see the section ``Interfacing to C'' in the
21469 @cite{GNAT Reference Manual}.
21471 The @option{-gnatF} qualifier forces default and explicit
21472 @code{External_Name} parameters in pragmas Import and Export
21473 to be uppercased for compatibility with the default behavior
21474 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
21476 @node Main Program Definition
21477 @section Main Program Definition
21479 @noindent
21480 The following section discusses differences in the
21481 definition of main programs on HP Ada and GNAT.
21482 On HP Ada, main programs are defined to meet the
21483 following conditions:
21484 @itemize @bullet
21485 @item  Procedure with no formal parameters (returns 0 upon
21486        normal completion)
21488 @item  Procedure with no formal parameters (returns 42 when
21489        unhandled exceptions are raised)
21491 @item  Function with no formal parameters whose returned value
21492        is of a discrete type
21494 @item  Procedure with one OUT formal of a discrete type for
21495        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
21497 @end itemize
21499 @noindent
21500 When declared with the pragma EXPORT_VALUED_PROCEDURE,
21501 a main function or main procedure returns a discrete
21502 value whose size is less than 64 bits (32 on VAX systems),
21503 the value is zero- or sign-extended as appropriate.
21504 On GNAT, main programs are defined as follows:
21505 @itemize @bullet
21506 @item  Must be a non-generic, parameter-less subprogram that
21507 is either a procedure or function returning an Ada
21508 STANDARD.INTEGER (the predefined type)
21510 @item  Cannot be a generic subprogram or an instantiation of a
21511 generic subprogram
21512 @end itemize
21514 @node Implementation-Defined Attributes
21515 @section Implementation-Defined Attributes
21517 @noindent
21518 GNAT provides all HP Ada implementation-defined
21519 attributes.
21521 @node Compiler and Run-Time Interfacing
21522 @section Compiler and Run-Time Interfacing
21524 @noindent
21525 HP Ada provides the following ways to pass options to the linker
21526 (ACS LINK):
21527 @itemize @bullet
21528 @item  /WAIT and /SUBMIT qualifiers
21530 @item  /COMMAND qualifier
21532 @item  /[NO]MAP qualifier
21534 @item  /OUTPUT=file-spec
21536 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
21537 @end itemize
21539 @noindent
21540 To pass options to the linker, GNAT provides the following
21541 switches:
21543 @itemize @bullet
21544 @item   @option{/EXECUTABLE=exec-name}
21546 @item   @option{/VERBOSE qualifier}
21548 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
21549 @end itemize
21551 @noindent
21552 For more information on these switches, see
21553 @ref{Switches for gnatlink}.
21554 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21555 to control optimization. HP Ada also supplies the
21556 following pragmas:
21557 @itemize @bullet
21558 @item  @code{OPTIMIZE}
21560 @item  @code{INLINE}
21562 @item  @code{INLINE_GENERIC}
21564 @item  @code{SUPPRESS_ALL}
21566 @item  @code{PASSIVE}
21567 @end itemize
21569 @noindent
21570 In GNAT, optimization is controlled strictly by command
21571 line parameters, as described in the corresponding section of this guide.
21572 The HP pragmas for control of optimization are
21573 recognized but ignored.
21575 Note that in GNAT, the default is optimization off, whereas in HP Ada 83,
21576 the default is that optimization is turned on.
21578 @node Program Compilation and Library Management
21579 @section Program Compilation and Library Management
21581 @noindent
21582 HP Ada and GNAT provide a comparable set of commands to
21583 build programs. HP Ada also provides a program library,
21584 which is a concept that does not exist on GNAT. Instead,
21585 GNAT provides directories of sources that are compiled as
21586 needed.
21588 The following table summarizes
21589 the HP Ada commands and provides
21590 equivalent GNAT commands. In this table, some GNAT
21591 equivalents reflect the fact that GNAT does not use the
21592 concept of a program library. Instead, it uses a model
21593 in which collections of source and object files are used
21594 in a manner consistent with other languages like C and
21595 Fortran. Therefore, standard system file commands are used
21596 to manipulate these elements. Those GNAT commands are marked with
21597 an asterisk.
21598 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21600 @need 1500
21601 @multitable @columnfractions .35 .65
21603 @item @emph{HP Ada Command}
21604 @tab @emph{GNAT Equivalent / Description}
21606 @item @command{ADA}
21607 @tab @command{GNAT COMPILE}@*
21608 Invokes the compiler to compile one or more Ada source files.
21610 @item @command{ACS ATTACH}@*
21611 @tab [No equivalent]@*
21612 Switches control of terminal from current process running the program
21613 library manager.
21615 @item @command{ACS CHECK}
21616 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21617 Forms the execution closure of one
21618 or more compiled units and checks completeness and currency.
21620 @item @command{ACS COMPILE}
21621 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21622 Forms the execution closure of one or
21623 more specified units, checks completeness and currency,
21624 identifies units that have revised source files, compiles same,
21625 and recompiles units that are or will become obsolete.
21626 Also completes incomplete generic instantiations.
21628 @item @command{ACS COPY FOREIGN}
21629 @tab Copy (*)@*
21630 Copies a foreign object file into the program library as a
21631 library unit body.
21633 @item @command{ACS COPY UNIT}
21634 @tab Copy (*)@*
21635 Copies a compiled unit from one program library to another.
21637 @item @command{ACS CREATE LIBRARY}
21638 @tab Create /directory (*)@*
21639 Creates a program library.
21641 @item @command{ACS CREATE SUBLIBRARY}
21642 @tab Create /directory (*)@*
21643 Creates a program sublibrary.
21645 @item @command{ACS DELETE LIBRARY}
21646 @tab @*
21647 Deletes a program library and its contents.
21649 @item @command{ACS DELETE SUBLIBRARY}
21650 @tab @*
21651 Deletes a program sublibrary and its contents.
21653 @item @command{ACS DELETE UNIT}
21654 @tab Delete file (*)@*
21655 On OpenVMS systems, deletes one or more compiled units from
21656 the current program library.
21658 @item @command{ACS DIRECTORY}
21659 @tab Directory (*)@*
21660 On OpenVMS systems, lists units contained in the current
21661 program library.
21663 @item @command{ACS ENTER FOREIGN}
21664 @tab Copy (*)@*
21665 Allows the import of a foreign body as an Ada library
21666 specification and enters a reference to a pointer.
21668 @item @command{ACS ENTER UNIT}
21669 @tab Copy (*)@*
21670 Enters a reference (pointer) from the current program library to
21671 a unit compiled into another program library.
21673 @item @command{ACS EXIT}
21674 @tab [No equivalent]@*
21675 Exits from the program library manager.
21677 @item @command{ACS EXPORT}
21678 @tab Copy (*)@*
21679 Creates an object file that contains system-specific object code
21680 for one or more units. With GNAT, object files can simply be copied
21681 into the desired directory.
21683 @item @command{ACS EXTRACT SOURCE}
21684 @tab Copy (*)@*
21685 Allows access to the copied source file for each Ada compilation unit
21687 @item @command{ACS HELP}
21688 @tab @command{HELP GNAT}@*
21689 Provides online help.
21691 @item @command{ACS LINK}
21692 @tab @command{GNAT LINK}@*
21693 Links an object file containing Ada units into an executable file.
21695 @item @command{ACS LOAD}
21696 @tab Copy (*)@*
21697 Loads (partially compiles) Ada units into the program library.
21698 Allows loading a program from a collection of files into a library
21699 without knowing the relationship among units.
21701 @item @command{ACS MERGE}
21702 @tab Copy (*)@*
21703 Merges into the current program library, one or more units from
21704 another library where they were modified.
21706 @item @command{ACS RECOMPILE}
21707 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21708 Recompiles from   external or copied source files any obsolete
21709 unit in the closure. Also, completes any incomplete generic
21710 instantiations.
21712 @item @command{ACS REENTER}
21713 @tab @command{GNAT MAKE}@*
21714 Reenters current references to units compiled after last entered
21715 with the @command{ACS ENTER UNIT} command.
21717 @item @command{ACS SET LIBRARY}
21718 @tab Set default (*)@*
21719 Defines a program library to be the compilation context as well
21720 as the target library for compiler output and commands in general.
21722 @item @command{ACS SET PRAGMA}
21723 @tab Edit @file{gnat.adc} (*)@*
21724 Redefines specified  values of the library characteristics
21725 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21726 and @code{Float_Representation}.
21728 @item @command{ACS SET SOURCE}
21729 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21730 Defines the source file search list for the @command{ACS COMPILE} command.
21732 @item @command{ACS SHOW LIBRARY}
21733 @tab Directory (*)@*
21734 Lists information about one or more program libraries.
21736 @item @command{ACS SHOW PROGRAM}
21737 @tab [No equivalent]@*
21738 Lists information about the execution closure of one or
21739 more units in the program library.
21741 @item @command{ACS SHOW SOURCE}
21742 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21743 Shows the source file search used when compiling units.
21745 @item @command{ACS SHOW VERSION}
21746 @tab Compile with @option{VERBOSE} option
21747 Displays the version number of the compiler and program library
21748 manager used.
21750 @item @command{ACS SPAWN}
21751 @tab [No equivalent]@*
21752 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21753 command).
21755 @item @command{ACS VERIFY}
21756 @tab [No equivalent]@*
21757 Performs a series of consistency checks on a program library to
21758 determine whether the library structure and library files are in
21759 valid form.
21760 @end multitable
21762 @noindent
21764 @node Input-Output
21765 @section Input-Output
21767 @noindent
21768 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21769 Management Services (RMS) to perform operations on
21770 external files.
21772 @noindent
21773 HP Ada and GNAT predefine an identical set of input-
21774 output packages. To make the use of the
21775 generic TEXT_IO operations more convenient, HP Ada
21776 provides predefined library packages that instantiate the
21777 integer and floating-point operations for the predefined
21778 integer and floating-point types as shown in the following table.
21780 @multitable @columnfractions .45 .55
21781 @item @emph{Package Name} @tab Instantiation
21783 @item @code{INTEGER_TEXT_IO}
21784 @tab @code{INTEGER_IO(INTEGER)}
21786 @item @code{SHORT_INTEGER_TEXT_IO}
21787 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21789 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21790 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21792 @item @code{FLOAT_TEXT_IO}
21793 @tab @code{FLOAT_IO(FLOAT)}
21795 @item @code{LONG_FLOAT_TEXT_IO}
21796 @tab @code{FLOAT_IO(LONG_FLOAT)}
21797 @end multitable
21799 @noindent
21800 The HP Ada predefined packages and their operations
21801 are implemented using OpenVMS Alpha files and input-
21802 output facilities. HP Ada supports asynchronous input-
21803 output on OpenVMS Alpha. Familiarity with the following is
21804 recommended:
21805 @itemize @bullet
21806 @item  RMS file organizations and access methods
21808 @item  OpenVMS file specifications and directories
21810 @item  OpenVMS File Definition Language (FDL)
21811 @end itemize
21813 @noindent
21814 GNAT provides I/O facilities that are completely
21815 compatible with HP Ada. The distribution includes the
21816 standard HP Ada versions of all I/O packages, operating
21817 in a manner compatible with HP Ada. In particular, the
21818 following packages are by default the HP Ada (Ada 83)
21819 versions of these packages rather than the renamings
21820 suggested in annex J of the Ada 95 Reference Manual:
21821 @itemize @bullet
21822 @item  @code{TEXT_IO}
21824 @item  @code{SEQUENTIAL_IO}
21826 @item  @code{DIRECT_IO}
21827 @end itemize
21829 @noindent
21830 The use of the standard Ada 95 syntax for child packages (for
21831 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
21832 packages, as defined in the Ada 95 Reference Manual.
21833 GNAT provides HP-compatible predefined instantiations
21834 of the @code{TEXT_IO} packages, and also
21835 provides the standard predefined instantiations required
21836 by the Ada 95 Reference Manual.
21838 For further information on how GNAT interfaces to the file
21839 system or how I/O is implemented in programs written in
21840 mixed languages, see the chapter ``Implementation of the
21841 Standard I/O'' in the @cite{GNAT Reference Manual}.
21842 This chapter covers the following:
21843 @itemize @bullet
21844 @item  Standard I/O packages
21846 @item  @code{FORM} strings
21848 @item  @code{ADA.DIRECT_IO}
21850 @item  @code{ADA.SEQUENTIAL_IO}
21852 @item  @code{ADA.TEXT_IO}
21854 @item  Stream pointer positioning
21856 @item  Reading and writing non-regular files
21858 @item  @code{GET_IMMEDIATE}
21860 @item  Treating @code{TEXT_IO} files as streams
21862 @item  Shared files
21864 @item  Open modes
21865 @end itemize
21867 @node Implementation Limits
21868 @section Implementation Limits
21870 @noindent
21871 The following table lists implementation limits for HP Ada
21872 and GNAT systems.
21873 @multitable @columnfractions .60 .20 .20
21874 @sp 1
21875 @item  @emph{Compilation Parameter}
21876 @tab   @emph{HP Ada}
21877 @tab   @emph{GNAT}
21878 @sp 1
21880 @item  In a subprogram or entry  declaration, maximum number of
21881        formal parameters that are of an unconstrained record type
21882 @tab   32
21883 @tab   No set limit
21884 @sp 1
21886 @item  Maximum identifier length (number of characters)
21887 @tab   255
21888 @tab   255
21889 @sp 1
21891 @item  Maximum number of characters in a source line
21892 @tab   255
21893 @tab   255
21894 @sp 1
21896 @item  Maximum collection size   (number of bytes)
21897 @tab   2**31-1
21898 @tab   2**31-1
21899 @sp 1
21901 @item  Maximum number of discriminants for a record type
21902 @tab   245
21903 @tab   No set limit
21904 @sp 1
21906 @item  Maximum number of formal parameters in an entry or
21907        subprogram declaration
21908 @tab   246
21909 @tab    No set limit
21910 @sp 1
21912 @item  Maximum number of dimensions in an array type
21913 @tab   255
21914 @tab   No set limit
21915 @sp 1
21917 @item  Maximum number of library  units and subunits in a compilation.
21918 @tab   4095
21919 @tab   No set limit
21920 @sp 1
21922 @item  Maximum number of library units and subunits in an execution.
21923 @tab   16383
21924 @tab   No set limit
21925 @sp 1
21927 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21928        or @code{PSECT_OBJECT}
21929 @tab   32757
21930 @tab   No set limit
21931 @sp 1
21933 @item  Maximum number of enumeration literals in an enumeration type
21934        definition
21935 @tab   65535
21936 @tab   No set limit
21937 @sp 1
21939 @item  Maximum number of lines in a source file
21940 @tab   65534
21941 @tab   No set limit
21942 @sp 1
21944 @item  Maximum number of bits in any object
21945 @tab   2**31-1
21946 @tab   2**31-1
21947 @sp 1
21949 @item  Maximum size of the static portion of a stack frame (approximate)
21950 @tab   2**31-1
21951 @tab   2**31-1
21952 @end multitable
21954 @end ifset
21956 @c **************************************
21957 @node Platform-Specific Information for the Run-Time Libraries
21958 @appendix Platform-Specific Information for the Run-Time Libraries
21959 @cindex Tasking and threads libraries
21960 @cindex Threads libraries and tasking
21961 @cindex Run-time libraries (platform-specific information)
21963 @noindent
21964 The GNAT run-time implementation may vary with respect to both the
21965 underlying threads library and the exception handling scheme.
21966 For threads support, one or more of the following are supplied:
21967 @itemize @bullet
21968 @item @b{native threads library}, a binding to the thread package from
21969 the underlying operating system
21971 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21972 POSIX thread package
21973 @end itemize
21975 @noindent
21976 For exception handling, either or both of two models are supplied:
21977 @itemize @bullet
21978 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21979 Most programs should experience a substantial speed improvement by
21980 being compiled with a ZCX run-time.
21981 This is especially true for
21982 tasking applications or applications with many exception handlers.}
21983 @cindex Zero-Cost Exceptions
21984 @cindex ZCX (Zero-Cost Exceptions)
21985 which uses binder-generated tables that
21986 are interrogated at run time to locate a handler
21988 @item @b{setjmp / longjmp} (``SJLJ''),
21989 @cindex setjmp/longjmp Exception Model
21990 @cindex SJLJ (setjmp/longjmp Exception Model)
21991 which uses dynamically-set data to establish
21992 the set of handlers
21993 @end itemize
21995 @noindent
21996 This appendix summarizes which combinations of threads and exception support
21997 are supplied on various GNAT platforms.
21998 It then shows how to select a particular library either
21999 permanently or temporarily,
22000 explains the properties of (and tradeoffs among) the various threads
22001 libraries, and provides some additional
22002 information about several specific platforms.
22004 @menu
22005 * Summary of Run-Time Configurations::
22006 * Specifying a Run-Time Library::
22007 * Choosing the Scheduling Policy::
22008 * Solaris-Specific Considerations::
22009 * IRIX-Specific Considerations::
22010 * Linux-Specific Considerations::
22011 * AIX-Specific Considerations::
22012 @end menu
22014 @node Summary of Run-Time Configurations
22015 @section Summary of Run-Time Configurations
22017 @multitable @columnfractions .30 .70
22018 @item @b{alpha-openvms}
22019 @item @code{@ @ }@i{rts-native (default)}
22020 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22021 @item @code{@ @ @ @ }Exceptions @tab ZCX
22023 @item @b{pa-hpux}
22024 @item @code{@ @ }@i{rts-native (default)}
22025 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
22026 @item @code{@ @ @ @ }Exceptions @tab ZCX
22028 @item @code{@ @ }@i{rts-sjlj}
22029 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
22030 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22032 @item @b{sparc-solaris}  @tab
22033 @item @code{@ @ }@i{rts-native (default)}
22034 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22035 @item @code{@ @ @ @ }Exceptions @tab ZCX
22037 @item @code{@ @ }@i{rts-m64}
22038 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
22039 @item @code{@ @ @ @ }Exceptions  @tab ZCX
22040 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
22041 @item    @tab Use only on Solaris 8 or later.
22042 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
22044 @item @code{@ @ }@i{rts-pthread}
22045 @item @code{@ @ @ @ }Tasking    @tab pthreads library
22046 @item @code{@ @ @ @ }Exceptions @tab ZCX
22048 @item @code{@ @ }@i{rts-sjlj}
22049 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22050 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22052 @item @b{x86-linux}
22053 @item @code{@ @ }@i{rts-native (default)}
22054 @item @code{@ @ @ @ }Tasking    @tab pthread library
22055 @item @code{@ @ @ @ }Exceptions @tab ZCX
22057 @item @code{@ @ }@i{rts-sjlj}
22058 @item @code{@ @ @ @ }Tasking    @tab pthread library
22059 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22061 @item @b{x86-windows}
22062 @item @code{@ @ }@i{rts-native (default)}
22063 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22064 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22066 @end multitable
22068 @node Specifying a Run-Time Library
22069 @section Specifying a Run-Time Library
22071 @noindent
22072 The @file{adainclude} subdirectory containing the sources of the GNAT
22073 run-time library, and the @file{adalib} subdirectory containing the
22074 @file{ALI} files and the static and/or shared GNAT library, are located
22075 in the gcc target-dependent area:
22077 @smallexample
22078 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22079 @end smallexample
22081 @noindent
22082 As indicated above, on some platforms several run-time libraries are supplied.
22083 These libraries are installed in the target dependent area and
22084 contain a complete source and binary subdirectory. The detailed description
22085 below explains the differences between the different libraries in terms of
22086 their thread support.
22088 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22089 This default run time is selected by the means of soft links.
22090 For example on x86-linux:
22092 @smallexample
22093 @group
22094  $(target-dir)
22095      |
22096      +--- adainclude----------+
22097      |                        |
22098      +--- adalib-----------+  |
22099      |                     |  |
22100      +--- rts-native       |  |
22101      |    |                |  |
22102      |    +--- adainclude <---+
22103      |    |                |
22104      |    +--- adalib <----+
22105      |
22106      +--- rts-sjlj
22107           |
22108           +--- adainclude
22109           |
22110           +--- adalib
22111 @end group
22112 @end smallexample
22114 @noindent
22115 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22116 these soft links can be modified with the following commands:
22118 @smallexample
22119 $ cd $target
22120 $ rm -f adainclude adalib
22121 $ ln -s rts-sjlj/adainclude adainclude
22122 $ ln -s rts-sjlj/adalib adalib
22123 @end smallexample
22125 @noindent
22126 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22127 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22128 @file{$target/ada_object_path}.
22130 Selecting another run-time library temporarily can be
22131 achieved by the regular mechanism for GNAT object or source path selection:
22133 @itemize @bullet
22134 @item
22135 Set the environment variables:
22137 @smallexample
22138 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
22139 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
22140 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
22141 @end smallexample
22143 @item
22144 Use @option{-aI$target/rts-sjlj/adainclude}
22145 and @option{-aO$target/rts-sjlj/adalib}
22146 on the @command{gnatmake} command line
22148 @item
22149 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
22150 @cindex @option{--RTS} option
22151 @end itemize
22153 @node Choosing the Scheduling Policy
22154 @section Choosing the Scheduling Policy
22156 @noindent
22157 When using a POSIX threads implementation, you have a choice of several
22158 scheduling policies: @code{SCHED_FIFO},
22159 @cindex @code{SCHED_FIFO} scheduling policy
22160 @code{SCHED_RR}
22161 @cindex @code{SCHED_RR} scheduling policy
22162 and @code{SCHED_OTHER}.
22163 @cindex @code{SCHED_OTHER} scheduling policy
22164 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22165 or @code{SCHED_RR} requires special (e.g., root) privileges.
22167 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22168 @code{SCHED_FIFO},
22169 @cindex @code{SCHED_FIFO} scheduling policy
22170 you can use one of the following:
22172 @itemize @bullet
22173 @item
22174 @code{pragma Time_Slice (0.0)}
22175 @cindex pragma Time_Slice
22176 @item
22177 the corresponding binder option @option{-T0}
22178 @cindex @option{-T0} option
22179 @item
22180 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22181 @cindex pragma Task_Dispatching_Policy
22182 @end itemize
22184 @noindent
22185 To specify @code{SCHED_RR},
22186 @cindex @code{SCHED_RR} scheduling policy
22187 you should use @code{pragma Time_Slice} with a
22188 value greater than @code{0.0}, or else use the corresponding @option{-T}
22189 binder option.
22191 @node Solaris-Specific Considerations
22192 @section Solaris-Specific Considerations
22193 @cindex Solaris Sparc threads libraries
22195 @noindent
22196 This section addresses some topics related to the various threads libraries
22197 on Sparc Solaris and then provides some information on building and
22198 debugging 64-bit applications.
22200 @menu
22201 * Solaris Threads Issues::
22202 * Building and Debugging 64-bit Applications::
22203 @end menu
22205 @node Solaris Threads Issues
22206 @subsection Solaris Threads Issues
22208 @noindent
22209 GNAT under Solaris comes with an alternate tasking run-time library
22210 based on POSIX threads --- @emph{rts-pthread}.
22211 @cindex rts-pthread threads library
22212 This run-time library has the advantage of being mostly shared across all
22213 POSIX-compliant thread implementations, and it also provides under
22214 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22215 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22216 and @code{PTHREAD_PRIO_PROTECT}
22217 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22218 semantics that can be selected using the predefined pragma
22219 @code{Locking_Policy}
22220 @cindex pragma Locking_Policy (under rts-pthread)
22221 with respectively
22222 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22223 @cindex @code{Inheritance_Locking} (under rts-pthread)
22224 @cindex @code{Ceiling_Locking} (under rts-pthread)
22226 As explained above, the native run-time library is based on the Solaris thread
22227 library (@code{libthread}) and is the default library.
22229 When the Solaris threads library is used (this is the default), programs
22230 compiled with GNAT can automatically take advantage of
22231 and can thus execute on multiple processors.
22232 The user can alternatively specify a processor on which the program should run
22233 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22234 is made by
22235 setting the environment variable @code{GNAT_PROCESSOR}
22236 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22237 to one of the following:
22239 @table @code
22240 @item -2
22241 Use the default configuration (run the program on all
22242          available processors) - this is the same as having
22243          @code{GNAT_PROCESSOR} unset
22245 @item -1
22246 Let the run-time implementation choose one processor and run the program on
22247          that processor
22249 @item 0 .. Last_Proc
22250 Run the program on the specified processor.
22251   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22252 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22253 @end table
22255 @node Building and Debugging 64-bit Applications
22256 @subsection Building and Debugging 64-bit Applications
22258 @noindent
22259 In a 64-bit application, all the sources involved must be compiled with the
22260 @option{-m64} command-line option, and a specific GNAT library (compiled with
22261 this option) is required.
22262 The easiest way to build a 64bit application is to add
22263 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
22265 To debug these applications, a special version of gdb called @command{gdb64}
22266 needs to be used.
22268 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
22269 amounts to:
22271 @smallexample
22272      $ gnatmake -m64 -g --RTS=m64 hello.adb
22273      $ gdb64 hello
22274 @end smallexample
22276 In addition, the following capabilities are not supported when using the
22277 @option{-m64} option:
22279 @table @code
22280 @item -fstack-check does not work together with -m64.
22281 Any application combining these options crashes at startup time.
22283 @item Call-chain backtrace computation does not work with -m64.
22284 Thus the gnatbind switch -E is not supported.
22285 @end table
22287 @node IRIX-Specific Considerations
22288 @section IRIX-Specific Considerations
22289 @cindex IRIX thread library
22291 @noindent
22292 On SGI IRIX, the thread library depends on which compiler is used.
22293 The @emph{o32 ABI} compiler comes with a run-time library based on the
22294 user-level @code{athread}
22295 library. Thus kernel-level capabilities such as nonblocking system
22296 calls or time slicing can only be achieved reliably by specifying different
22297 @code{sprocs} via the pragma @code{Task_Info}
22298 @cindex pragma Task_Info (and IRIX threads)
22299 and the
22300 @code{System.Task_Info} package.
22301 @cindex @code{System.Task_Info} package (and IRIX threads)
22302 See the @cite{GNAT Reference Manual} for further information.
22304 The @emph{n32 ABI} compiler comes with a run-time library based on the
22305 kernel POSIX threads and thus does not have the limitations mentioned above.
22307 @node Linux-Specific Considerations
22308 @section Linux-Specific Considerations
22309 @cindex Linux threads libraries
22311 @noindent
22312 The default thread library under GNU/Linux has the following disadvantages
22313 compared to other native thread libraries:
22315 @itemize @bullet
22316 @item The size of the task's stack is limited to 2 megabytes.
22317 @item  The signal model is not POSIX compliant, which means that to send a
22318   signal to the process, you need to send the signal to all threads,
22319   e.g. by using @code{killpg()}.
22320 @end itemize
22322 @node AIX-Specific Considerations
22323 @section AIX-Specific Considerations
22324 @cindex AIX resolver library
22326 @noindent
22327 On AIX, the resolver library initializes some internal structure on
22328 the first call to @code{get*by*} functions, which are used to implement
22329 @code{GNAT.Sockets.Get_Host_By_Name} and
22330 @code{GNAT.Sockets.Get_Host_By_Addrss}.
22331 If such initialization occurs within an Ada task, and the stack size for
22332 the task is the default size, a stack overflow may occur.
22334 To avoid this overflow, the user should either ensure that the first call
22335 to @code{GNAT.Sockets.Get_Host_By_Name} or
22336 @code{GNAT.Sockets.Get_Host_By_Addrss}
22337 occurs in the environment task, or use @code{pragma Storage_Size} to
22338 specify a sufficiently large size for the stack of the task that contains
22339 this call.
22341 @c *******************************
22342 @node Example of Binder Output File
22343 @appendix Example of Binder Output File
22345 @noindent
22346 This Appendix displays the source code for @command{gnatbind}'s output
22347 file generated for a simple ``Hello World'' program.
22348 Comments have been added for clarification purposes.
22350 @smallexample @c adanocomment
22351 @iftex
22352 @leftskip=0cm
22353 @end iftex
22354 --  The package is called Ada_Main unless this name is actually used
22355 --  as a unit name in the partition, in which case some other unique
22356 --  name is used.
22358 with System;
22359 package ada_main is
22361    Elab_Final_Code : Integer;
22362    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22364    --  The main program saves the parameters (argument count,
22365    --  argument values, environment pointer) in global variables
22366    --  for later access by other units including
22367    --  Ada.Command_Line.
22369    gnat_argc : Integer;
22370    gnat_argv : System.Address;
22371    gnat_envp : System.Address;
22373    --  The actual variables are stored in a library routine. This
22374    --  is useful for some shared library situations, where there
22375    --  are problems if variables are not in the library.
22377    pragma Import (C, gnat_argc);
22378    pragma Import (C, gnat_argv);
22379    pragma Import (C, gnat_envp);
22381    --  The exit status is similarly an external location
22383    gnat_exit_status : Integer;
22384    pragma Import (C, gnat_exit_status);
22386    GNAT_Version : constant String :=
22387                     "GNAT Version: 3.15w (20010315)";
22388    pragma Export (C, GNAT_Version, "__gnat_version");
22390    --  This is the generated adafinal routine that performs
22391    --  finalization at the end of execution. In the case where
22392    --  Ada is the main program, this main program makes a call
22393    --  to adafinal at program termination.
22395    procedure adafinal;
22396    pragma Export (C, adafinal, "adafinal");
22398    --  This is the generated adainit routine that performs
22399    --  initialization at the start of execution. In the case
22400    --  where Ada is the main program, this main program makes
22401    --  a call to adainit at program startup.
22403    procedure adainit;
22404    pragma Export (C, adainit, "adainit");
22406    --  This routine is called at the start of execution. It is
22407    --  a dummy routine that is used by the debugger to breakpoint
22408    --  at the start of execution.
22410    procedure Break_Start;
22411    pragma Import (C, Break_Start, "__gnat_break_start");
22413    --  This is the actual generated main program (it would be
22414    --  suppressed if the no main program switch were used). As
22415    --  required by standard system conventions, this program has
22416    --  the external name main.
22418    function main
22419      (argc : Integer;
22420       argv : System.Address;
22421       envp : System.Address)
22422       return Integer;
22423    pragma Export (C, main, "main");
22425    --  The following set of constants give the version
22426    --  identification values for every unit in the bound
22427    --  partition. This identification is computed from all
22428    --  dependent semantic units, and corresponds to the
22429    --  string that would be returned by use of the
22430    --  Body_Version or Version attributes.
22432    type Version_32 is mod 2 ** 32;
22433    u00001 : constant Version_32 := 16#7880BEB3#;
22434    u00002 : constant Version_32 := 16#0D24CBD0#;
22435    u00003 : constant Version_32 := 16#3283DBEB#;
22436    u00004 : constant Version_32 := 16#2359F9ED#;
22437    u00005 : constant Version_32 := 16#664FB847#;
22438    u00006 : constant Version_32 := 16#68E803DF#;
22439    u00007 : constant Version_32 := 16#5572E604#;
22440    u00008 : constant Version_32 := 16#46B173D8#;
22441    u00009 : constant Version_32 := 16#156A40CF#;
22442    u00010 : constant Version_32 := 16#033DABE0#;
22443    u00011 : constant Version_32 := 16#6AB38FEA#;
22444    u00012 : constant Version_32 := 16#22B6217D#;
22445    u00013 : constant Version_32 := 16#68A22947#;
22446    u00014 : constant Version_32 := 16#18CC4A56#;
22447    u00015 : constant Version_32 := 16#08258E1B#;
22448    u00016 : constant Version_32 := 16#367D5222#;
22449    u00017 : constant Version_32 := 16#20C9ECA4#;
22450    u00018 : constant Version_32 := 16#50D32CB6#;
22451    u00019 : constant Version_32 := 16#39A8BB77#;
22452    u00020 : constant Version_32 := 16#5CF8FA2B#;
22453    u00021 : constant Version_32 := 16#2F1EB794#;
22454    u00022 : constant Version_32 := 16#31AB6444#;
22455    u00023 : constant Version_32 := 16#1574B6E9#;
22456    u00024 : constant Version_32 := 16#5109C189#;
22457    u00025 : constant Version_32 := 16#56D770CD#;
22458    u00026 : constant Version_32 := 16#02F9DE3D#;
22459    u00027 : constant Version_32 := 16#08AB6B2C#;
22460    u00028 : constant Version_32 := 16#3FA37670#;
22461    u00029 : constant Version_32 := 16#476457A0#;
22462    u00030 : constant Version_32 := 16#731E1B6E#;
22463    u00031 : constant Version_32 := 16#23C2E789#;
22464    u00032 : constant Version_32 := 16#0F1BD6A1#;
22465    u00033 : constant Version_32 := 16#7C25DE96#;
22466    u00034 : constant Version_32 := 16#39ADFFA2#;
22467    u00035 : constant Version_32 := 16#571DE3E7#;
22468    u00036 : constant Version_32 := 16#5EB646AB#;
22469    u00037 : constant Version_32 := 16#4249379B#;
22470    u00038 : constant Version_32 := 16#0357E00A#;
22471    u00039 : constant Version_32 := 16#3784FB72#;
22472    u00040 : constant Version_32 := 16#2E723019#;
22473    u00041 : constant Version_32 := 16#623358EA#;
22474    u00042 : constant Version_32 := 16#107F9465#;
22475    u00043 : constant Version_32 := 16#6843F68A#;
22476    u00044 : constant Version_32 := 16#63305874#;
22477    u00045 : constant Version_32 := 16#31E56CE1#;
22478    u00046 : constant Version_32 := 16#02917970#;
22479    u00047 : constant Version_32 := 16#6CCBA70E#;
22480    u00048 : constant Version_32 := 16#41CD4204#;
22481    u00049 : constant Version_32 := 16#572E3F58#;
22482    u00050 : constant Version_32 := 16#20729FF5#;
22483    u00051 : constant Version_32 := 16#1D4F93E8#;
22484    u00052 : constant Version_32 := 16#30B2EC3D#;
22485    u00053 : constant Version_32 := 16#34054F96#;
22486    u00054 : constant Version_32 := 16#5A199860#;
22487    u00055 : constant Version_32 := 16#0E7F912B#;
22488    u00056 : constant Version_32 := 16#5760634A#;
22489    u00057 : constant Version_32 := 16#5D851835#;
22491    --  The following Export pragmas export the version numbers
22492    --  with symbolic names ending in B (for body) or S
22493    --  (for spec) so that they can be located in a link. The
22494    --  information provided here is sufficient to track down
22495    --  the exact versions of units used in a given build.
22497    pragma Export (C, u00001, "helloB");
22498    pragma Export (C, u00002, "system__standard_libraryB");
22499    pragma Export (C, u00003, "system__standard_libraryS");
22500    pragma Export (C, u00004, "adaS");
22501    pragma Export (C, u00005, "ada__text_ioB");
22502    pragma Export (C, u00006, "ada__text_ioS");
22503    pragma Export (C, u00007, "ada__exceptionsB");
22504    pragma Export (C, u00008, "ada__exceptionsS");
22505    pragma Export (C, u00009, "gnatS");
22506    pragma Export (C, u00010, "gnat__heap_sort_aB");
22507    pragma Export (C, u00011, "gnat__heap_sort_aS");
22508    pragma Export (C, u00012, "systemS");
22509    pragma Export (C, u00013, "system__exception_tableB");
22510    pragma Export (C, u00014, "system__exception_tableS");
22511    pragma Export (C, u00015, "gnat__htableB");
22512    pragma Export (C, u00016, "gnat__htableS");
22513    pragma Export (C, u00017, "system__exceptionsS");
22514    pragma Export (C, u00018, "system__machine_state_operationsB");
22515    pragma Export (C, u00019, "system__machine_state_operationsS");
22516    pragma Export (C, u00020, "system__machine_codeS");
22517    pragma Export (C, u00021, "system__storage_elementsB");
22518    pragma Export (C, u00022, "system__storage_elementsS");
22519    pragma Export (C, u00023, "system__secondary_stackB");
22520    pragma Export (C, u00024, "system__secondary_stackS");
22521    pragma Export (C, u00025, "system__parametersB");
22522    pragma Export (C, u00026, "system__parametersS");
22523    pragma Export (C, u00027, "system__soft_linksB");
22524    pragma Export (C, u00028, "system__soft_linksS");
22525    pragma Export (C, u00029, "system__stack_checkingB");
22526    pragma Export (C, u00030, "system__stack_checkingS");
22527    pragma Export (C, u00031, "system__tracebackB");
22528    pragma Export (C, u00032, "system__tracebackS");
22529    pragma Export (C, u00033, "ada__streamsS");
22530    pragma Export (C, u00034, "ada__tagsB");
22531    pragma Export (C, u00035, "ada__tagsS");
22532    pragma Export (C, u00036, "system__string_opsB");
22533    pragma Export (C, u00037, "system__string_opsS");
22534    pragma Export (C, u00038, "interfacesS");
22535    pragma Export (C, u00039, "interfaces__c_streamsB");
22536    pragma Export (C, u00040, "interfaces__c_streamsS");
22537    pragma Export (C, u00041, "system__file_ioB");
22538    pragma Export (C, u00042, "system__file_ioS");
22539    pragma Export (C, u00043, "ada__finalizationB");
22540    pragma Export (C, u00044, "ada__finalizationS");
22541    pragma Export (C, u00045, "system__finalization_rootB");
22542    pragma Export (C, u00046, "system__finalization_rootS");
22543    pragma Export (C, u00047, "system__finalization_implementationB");
22544    pragma Export (C, u00048, "system__finalization_implementationS");
22545    pragma Export (C, u00049, "system__string_ops_concat_3B");
22546    pragma Export (C, u00050, "system__string_ops_concat_3S");
22547    pragma Export (C, u00051, "system__stream_attributesB");
22548    pragma Export (C, u00052, "system__stream_attributesS");
22549    pragma Export (C, u00053, "ada__io_exceptionsS");
22550    pragma Export (C, u00054, "system__unsigned_typesS");
22551    pragma Export (C, u00055, "system__file_control_blockS");
22552    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22553    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22555    -- BEGIN ELABORATION ORDER
22556    -- ada (spec)
22557    -- gnat (spec)
22558    -- gnat.heap_sort_a (spec)
22559    -- gnat.heap_sort_a (body)
22560    -- gnat.htable (spec)
22561    -- gnat.htable (body)
22562    -- interfaces (spec)
22563    -- system (spec)
22564    -- system.machine_code (spec)
22565    -- system.parameters (spec)
22566    -- system.parameters (body)
22567    -- interfaces.c_streams (spec)
22568    -- interfaces.c_streams (body)
22569    -- system.standard_library (spec)
22570    -- ada.exceptions (spec)
22571    -- system.exception_table (spec)
22572    -- system.exception_table (body)
22573    -- ada.io_exceptions (spec)
22574    -- system.exceptions (spec)
22575    -- system.storage_elements (spec)
22576    -- system.storage_elements (body)
22577    -- system.machine_state_operations (spec)
22578    -- system.machine_state_operations (body)
22579    -- system.secondary_stack (spec)
22580    -- system.stack_checking (spec)
22581    -- system.soft_links (spec)
22582    -- system.soft_links (body)
22583    -- system.stack_checking (body)
22584    -- system.secondary_stack (body)
22585    -- system.standard_library (body)
22586    -- system.string_ops (spec)
22587    -- system.string_ops (body)
22588    -- ada.tags (spec)
22589    -- ada.tags (body)
22590    -- ada.streams (spec)
22591    -- system.finalization_root (spec)
22592    -- system.finalization_root (body)
22593    -- system.string_ops_concat_3 (spec)
22594    -- system.string_ops_concat_3 (body)
22595    -- system.traceback (spec)
22596    -- system.traceback (body)
22597    -- ada.exceptions (body)
22598    -- system.unsigned_types (spec)
22599    -- system.stream_attributes (spec)
22600    -- system.stream_attributes (body)
22601    -- system.finalization_implementation (spec)
22602    -- system.finalization_implementation (body)
22603    -- ada.finalization (spec)
22604    -- ada.finalization (body)
22605    -- ada.finalization.list_controller (spec)
22606    -- ada.finalization.list_controller (body)
22607    -- system.file_control_block (spec)
22608    -- system.file_io (spec)
22609    -- system.file_io (body)
22610    -- ada.text_io (spec)
22611    -- ada.text_io (body)
22612    -- hello (body)
22613    -- END ELABORATION ORDER
22615 end ada_main;
22617 --  The following source file name pragmas allow the generated file
22618 --  names to be unique for different main programs. They are needed
22619 --  since the package name will always be Ada_Main.
22621 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22622 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22624 --  Generated package body for Ada_Main starts here
22626 package body ada_main is
22628    --  The actual finalization is performed by calling the
22629    --  library routine in System.Standard_Library.Adafinal
22631    procedure Do_Finalize;
22632    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22634    -------------
22635    -- adainit --
22636    -------------
22638 @findex adainit
22639    procedure adainit is
22641       --  These booleans are set to True once the associated unit has
22642       --  been elaborated. It is also used to avoid elaborating the
22643       --  same unit twice.
22645       E040 : Boolean;
22646       pragma Import (Ada, E040, "interfaces__c_streams_E");
22648       E008 : Boolean;
22649       pragma Import (Ada, E008, "ada__exceptions_E");
22651       E014 : Boolean;
22652       pragma Import (Ada, E014, "system__exception_table_E");
22654       E053 : Boolean;
22655       pragma Import (Ada, E053, "ada__io_exceptions_E");
22657       E017 : Boolean;
22658       pragma Import (Ada, E017, "system__exceptions_E");
22660       E024 : Boolean;
22661       pragma Import (Ada, E024, "system__secondary_stack_E");
22663       E030 : Boolean;
22664       pragma Import (Ada, E030, "system__stack_checking_E");
22666       E028 : Boolean;
22667       pragma Import (Ada, E028, "system__soft_links_E");
22669       E035 : Boolean;
22670       pragma Import (Ada, E035, "ada__tags_E");
22672       E033 : Boolean;
22673       pragma Import (Ada, E033, "ada__streams_E");
22675       E046 : Boolean;
22676       pragma Import (Ada, E046, "system__finalization_root_E");
22678       E048 : Boolean;
22679       pragma Import (Ada, E048, "system__finalization_implementation_E");
22681       E044 : Boolean;
22682       pragma Import (Ada, E044, "ada__finalization_E");
22684       E057 : Boolean;
22685       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22687       E055 : Boolean;
22688       pragma Import (Ada, E055, "system__file_control_block_E");
22690       E042 : Boolean;
22691       pragma Import (Ada, E042, "system__file_io_E");
22693       E006 : Boolean;
22694       pragma Import (Ada, E006, "ada__text_io_E");
22696       --  Set_Globals is a library routine that stores away the
22697       --  value of the indicated set of global values in global
22698       --  variables within the library.
22700       procedure Set_Globals
22701         (Main_Priority            : Integer;
22702          Time_Slice_Value         : Integer;
22703          WC_Encoding              : Character;
22704          Locking_Policy           : Character;
22705          Queuing_Policy           : Character;
22706          Task_Dispatching_Policy  : Character;
22707          Adafinal                 : System.Address;
22708          Unreserve_All_Interrupts : Integer;
22709          Exception_Tracebacks     : Integer);
22710 @findex __gnat_set_globals
22711       pragma Import (C, Set_Globals, "__gnat_set_globals");
22713       --  SDP_Table_Build is a library routine used to build the
22714       --  exception tables. See unit Ada.Exceptions in files
22715       --  a-except.ads/adb for full details of how zero cost
22716       --  exception handling works. This procedure, the call to
22717       --  it, and the two following tables are all omitted if the
22718       --  build is in longjmp/setjump exception mode.
22720 @findex SDP_Table_Build
22721 @findex Zero Cost Exceptions
22722       procedure SDP_Table_Build
22723         (SDP_Addresses   : System.Address;
22724          SDP_Count       : Natural;
22725          Elab_Addresses  : System.Address;
22726          Elab_Addr_Count : Natural);
22727       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22729       --  Table of Unit_Exception_Table addresses. Used for zero
22730       --  cost exception handling to build the top level table.
22732       ST : aliased constant array (1 .. 23) of System.Address := (
22733         Hello'UET_Address,
22734         Ada.Text_Io'UET_Address,
22735         Ada.Exceptions'UET_Address,
22736         Gnat.Heap_Sort_A'UET_Address,
22737         System.Exception_Table'UET_Address,
22738         System.Machine_State_Operations'UET_Address,
22739         System.Secondary_Stack'UET_Address,
22740         System.Parameters'UET_Address,
22741         System.Soft_Links'UET_Address,
22742         System.Stack_Checking'UET_Address,
22743         System.Traceback'UET_Address,
22744         Ada.Streams'UET_Address,
22745         Ada.Tags'UET_Address,
22746         System.String_Ops'UET_Address,
22747         Interfaces.C_Streams'UET_Address,
22748         System.File_Io'UET_Address,
22749         Ada.Finalization'UET_Address,
22750         System.Finalization_Root'UET_Address,
22751         System.Finalization_Implementation'UET_Address,
22752         System.String_Ops_Concat_3'UET_Address,
22753         System.Stream_Attributes'UET_Address,
22754         System.File_Control_Block'UET_Address,
22755         Ada.Finalization.List_Controller'UET_Address);
22757       --  Table of addresses of elaboration routines. Used for
22758       --  zero cost exception handling to make sure these
22759       --  addresses are included in the top level procedure
22760       --  address table.
22762       EA : aliased constant array (1 .. 23) of System.Address := (
22763         adainit'Code_Address,
22764         Do_Finalize'Code_Address,
22765         Ada.Exceptions'Elab_Spec'Address,
22766         System.Exceptions'Elab_Spec'Address,
22767         Interfaces.C_Streams'Elab_Spec'Address,
22768         System.Exception_Table'Elab_Body'Address,
22769         Ada.Io_Exceptions'Elab_Spec'Address,
22770         System.Stack_Checking'Elab_Spec'Address,
22771         System.Soft_Links'Elab_Body'Address,
22772         System.Secondary_Stack'Elab_Body'Address,
22773         Ada.Tags'Elab_Spec'Address,
22774         Ada.Tags'Elab_Body'Address,
22775         Ada.Streams'Elab_Spec'Address,
22776         System.Finalization_Root'Elab_Spec'Address,
22777         Ada.Exceptions'Elab_Body'Address,
22778         System.Finalization_Implementation'Elab_Spec'Address,
22779         System.Finalization_Implementation'Elab_Body'Address,
22780         Ada.Finalization'Elab_Spec'Address,
22781         Ada.Finalization.List_Controller'Elab_Spec'Address,
22782         System.File_Control_Block'Elab_Spec'Address,
22783         System.File_Io'Elab_Body'Address,
22784         Ada.Text_Io'Elab_Spec'Address,
22785         Ada.Text_Io'Elab_Body'Address);
22787    --  Start of processing for adainit
22789    begin
22791       --  Call SDP_Table_Build to build the top level procedure
22792       --  table for zero cost exception handling (omitted in
22793       --  longjmp/setjump mode).
22795       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22797       --  Call Set_Globals to record various information for
22798       --  this partition.  The values are derived by the binder
22799       --  from information stored in the ali files by the compiler.
22801 @findex __gnat_set_globals
22802       Set_Globals
22803         (Main_Priority            => -1,
22804          --  Priority of main program, -1 if no pragma Priority used
22806          Time_Slice_Value         => -1,
22807          --  Time slice from Time_Slice pragma, -1 if none used
22809          WC_Encoding              => 'b',
22810          --  Wide_Character encoding used, default is brackets
22812          Locking_Policy           => ' ',
22813          --  Locking_Policy used, default of space means not
22814          --  specified, otherwise it is the first character of
22815          --  the policy name.
22817          Queuing_Policy           => ' ',
22818          --  Queuing_Policy used, default of space means not
22819          --  specified, otherwise it is the first character of
22820          --  the policy name.
22822          Task_Dispatching_Policy  => ' ',
22823          --  Task_Dispatching_Policy used, default of space means
22824          --  not specified, otherwise first character of the
22825          --  policy name.
22827          Adafinal                 => System.Null_Address,
22828          --  Address of Adafinal routine, not used anymore
22830          Unreserve_All_Interrupts => 0,
22831          --  Set true if pragma Unreserve_All_Interrupts was used
22833          Exception_Tracebacks     => 0);
22834          --  Indicates if exception tracebacks are enabled
22836       Elab_Final_Code := 1;
22838       --  Now we have the elaboration calls for all units in the partition.
22839       --  The Elab_Spec and Elab_Body attributes generate references to the
22840       --  implicit elaboration procedures generated by the compiler for
22841       --  each unit that requires elaboration.
22843       if not E040 then
22844          Interfaces.C_Streams'Elab_Spec;
22845       end if;
22846       E040 := True;
22847       if not E008 then
22848          Ada.Exceptions'Elab_Spec;
22849       end if;
22850       if not E014 then
22851          System.Exception_Table'Elab_Body;
22852          E014 := True;
22853       end if;
22854       if not E053 then
22855          Ada.Io_Exceptions'Elab_Spec;
22856          E053 := True;
22857       end if;
22858       if not E017 then
22859          System.Exceptions'Elab_Spec;
22860          E017 := True;
22861       end if;
22862       if not E030 then
22863          System.Stack_Checking'Elab_Spec;
22864       end if;
22865       if not E028 then
22866          System.Soft_Links'Elab_Body;
22867          E028 := True;
22868       end if;
22869       E030 := True;
22870       if not E024 then
22871          System.Secondary_Stack'Elab_Body;
22872          E024 := True;
22873       end if;
22874       if not E035 then
22875          Ada.Tags'Elab_Spec;
22876       end if;
22877       if not E035 then
22878          Ada.Tags'Elab_Body;
22879          E035 := True;
22880       end if;
22881       if not E033 then
22882          Ada.Streams'Elab_Spec;
22883          E033 := True;
22884       end if;
22885       if not E046 then
22886          System.Finalization_Root'Elab_Spec;
22887       end if;
22888       E046 := True;
22889       if not E008 then
22890          Ada.Exceptions'Elab_Body;
22891          E008 := True;
22892       end if;
22893       if not E048 then
22894          System.Finalization_Implementation'Elab_Spec;
22895       end if;
22896       if not E048 then
22897          System.Finalization_Implementation'Elab_Body;
22898          E048 := True;
22899       end if;
22900       if not E044 then
22901          Ada.Finalization'Elab_Spec;
22902       end if;
22903       E044 := True;
22904       if not E057 then
22905          Ada.Finalization.List_Controller'Elab_Spec;
22906       end if;
22907       E057 := True;
22908       if not E055 then
22909          System.File_Control_Block'Elab_Spec;
22910          E055 := True;
22911       end if;
22912       if not E042 then
22913          System.File_Io'Elab_Body;
22914          E042 := True;
22915       end if;
22916       if not E006 then
22917          Ada.Text_Io'Elab_Spec;
22918       end if;
22919       if not E006 then
22920          Ada.Text_Io'Elab_Body;
22921          E006 := True;
22922       end if;
22924       Elab_Final_Code := 0;
22925    end adainit;
22927    --------------
22928    -- adafinal --
22929    --------------
22931 @findex adafinal
22932    procedure adafinal is
22933    begin
22934       Do_Finalize;
22935    end adafinal;
22937    ----------
22938    -- main --
22939    ----------
22941    --  main is actually a function, as in the ANSI C standard,
22942    --  defined to return the exit status. The three parameters
22943    --  are the argument count, argument values and environment
22944    --  pointer.
22946 @findex Main Program
22947    function main
22948      (argc : Integer;
22949       argv : System.Address;
22950       envp : System.Address)
22951       return Integer
22952    is
22953       --  The initialize routine performs low level system
22954       --  initialization using a standard library routine which
22955       --  sets up signal handling and performs any other
22956       --  required setup. The routine can be found in file
22957       --  a-init.c.
22959 @findex __gnat_initialize
22960       procedure initialize;
22961       pragma Import (C, initialize, "__gnat_initialize");
22963       --  The finalize routine performs low level system
22964       --  finalization using a standard library routine. The
22965       --  routine is found in file a-final.c and in the standard
22966       --  distribution is a dummy routine that does nothing, so
22967       --  really this is a hook for special user finalization.
22969 @findex __gnat_finalize
22970       procedure finalize;
22971       pragma Import (C, finalize, "__gnat_finalize");
22973       --  We get to the main program of the partition by using
22974       --  pragma Import because if we try to with the unit and
22975       --  call it Ada style, then not only do we waste time
22976       --  recompiling it, but also, we don't really know the right
22977       --  switches (e.g. identifier character set) to be used
22978       --  to compile it.
22980       procedure Ada_Main_Program;
22981       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22983    --  Start of processing for main
22985    begin
22986       --  Save global variables
22988       gnat_argc := argc;
22989       gnat_argv := argv;
22990       gnat_envp := envp;
22992       --  Call low level system initialization
22994       Initialize;
22996       --  Call our generated Ada initialization routine
22998       adainit;
23000       --  This is the point at which we want the debugger to get
23001       --  control
23003       Break_Start;
23005       --  Now we call the main program of the partition
23007       Ada_Main_Program;
23009       --  Perform Ada finalization
23011       adafinal;
23013       --  Perform low level system finalization
23015       Finalize;
23017       --  Return the proper exit status
23018       return (gnat_exit_status);
23019    end;
23021 --  This section is entirely comments, so it has no effect on the
23022 --  compilation of the Ada_Main package. It provides the list of
23023 --  object files and linker options, as well as some standard
23024 --  libraries needed for the link. The gnatlink utility parses
23025 --  this b~hello.adb file to read these comment lines to generate
23026 --  the appropriate command line arguments for the call to the
23027 --  system linker. The BEGIN/END lines are used for sentinels for
23028 --  this parsing operation.
23030 --  The exact file names will of course depend on the environment,
23031 --  host/target and location of files on the host system.
23033 @findex Object file list
23034 -- BEGIN Object file/option list
23035    --   ./hello.o
23036    --   -L./
23037    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23038    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23039 -- END Object file/option list
23041 end ada_main;
23042 @end smallexample
23044 @noindent
23045 The Ada code in the above example is exactly what is generated by the
23046 binder. We have added comments to more clearly indicate the function
23047 of each part of the generated @code{Ada_Main} package.
23049 The code is standard Ada in all respects, and can be processed by any
23050 tools that handle Ada. In particular, it is possible to use the debugger
23051 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23052 suppose that for reasons that you do not understand, your program is crashing
23053 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23054 you can place a breakpoint on the call:
23056 @smallexample @c ada
23057 Ada.Text_Io'Elab_Body;
23058 @end smallexample
23060 @noindent
23061 and trace the elaboration routine for this package to find out where
23062 the problem might be (more usually of course you would be debugging
23063 elaboration code in your own application).
23065 @node Elaboration Order Handling in GNAT
23066 @appendix Elaboration Order Handling in GNAT
23067 @cindex Order of elaboration
23068 @cindex Elaboration control
23070 @menu
23071 * Elaboration Code in Ada 95::
23072 * Checking the Elaboration Order in Ada 95::
23073 * Controlling the Elaboration Order in Ada 95::
23074 * Controlling Elaboration in GNAT - Internal Calls::
23075 * Controlling Elaboration in GNAT - External Calls::
23076 * Default Behavior in GNAT - Ensuring Safety::
23077 * Treatment of Pragma Elaborate::
23078 * Elaboration Issues for Library Tasks::
23079 * Mixing Elaboration Models::
23080 * What to Do If the Default Elaboration Behavior Fails::
23081 * Elaboration for Access-to-Subprogram Values::
23082 * Summary of Procedures for Elaboration Control::
23083 * Other Elaboration Order Considerations::
23084 @end menu
23086 @noindent
23087 This chapter describes the handling of elaboration code in Ada 95 and
23088 in GNAT, and discusses how the order of elaboration of program units can
23089 be controlled in GNAT, either automatically or with explicit programming
23090 features.
23092 @node Elaboration Code in Ada 95
23093 @section Elaboration Code in Ada 95
23095 @noindent
23096 Ada 95 provides rather general mechanisms for executing code at elaboration
23097 time, that is to say before the main program starts executing. Such code arises
23098 in three contexts:
23100 @table @asis
23101 @item Initializers for variables.
23102 Variables declared at the library level, in package specs or bodies, can
23103 require initialization that is performed at elaboration time, as in:
23104 @smallexample @c ada
23105 @cartouche
23106 Sqrt_Half : Float := Sqrt (0.5);
23107 @end cartouche
23108 @end smallexample
23110 @item Package initialization code
23111 Code in a @code{BEGIN-END} section at the outer level of a package body is
23112 executed as part of the package body elaboration code.
23114 @item Library level task allocators
23115 Tasks that are declared using task allocators at the library level
23116 start executing immediately and hence can execute at elaboration time.
23117 @end table
23119 @noindent
23120 Subprogram calls are possible in any of these contexts, which means that
23121 any arbitrary part of the program may be executed as part of the elaboration
23122 code. It is even possible to write a program which does all its work at
23123 elaboration time, with a null main program, although stylistically this
23124 would usually be considered an inappropriate way to structure
23125 a program.
23127 An important concern arises in the context of elaboration code:
23128 we have to be sure that it is executed in an appropriate order. What we
23129 have is a series of elaboration code sections, potentially one section
23130 for each unit in the program. It is important that these execute
23131 in the correct order. Correctness here means that, taking the above
23132 example of the declaration of @code{Sqrt_Half},
23133 if some other piece of
23134 elaboration code references @code{Sqrt_Half},
23135 then it must run after the
23136 section of elaboration code that contains the declaration of
23137 @code{Sqrt_Half}.
23139 There would never be any order of elaboration problem if we made a rule
23140 that whenever you @code{with} a unit, you must elaborate both the spec and body
23141 of that unit before elaborating the unit doing the @code{with}'ing:
23143 @smallexample @c ada
23144 @group
23145 @cartouche
23146 with Unit_1;
23147 package Unit_2 is ...
23148 @end cartouche
23149 @end group
23150 @end smallexample
23152 @noindent
23153 would require that both the body and spec of @code{Unit_1} be elaborated
23154 before the spec of @code{Unit_2}. However, a rule like that would be far too
23155 restrictive. In particular, it would make it impossible to have routines
23156 in separate packages that were mutually recursive.
23158 You might think that a clever enough compiler could look at the actual
23159 elaboration code and determine an appropriate correct order of elaboration,
23160 but in the general case, this is not possible. Consider the following
23161 example.
23163 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23164 that references
23165 the variable @code{Sqrt_1}, which is declared in the elaboration code
23166 of the body of @code{Unit_1}:
23168 @smallexample @c ada
23169 @cartouche
23170 Sqrt_1 : Float := Sqrt (0.1);
23171 @end cartouche
23172 @end smallexample
23174 @noindent
23175 The elaboration code of the body of @code{Unit_1} also contains:
23177 @smallexample @c ada
23178 @group
23179 @cartouche
23180 if expression_1 = 1 then
23181    Q := Unit_2.Func_2;
23182 end if;
23183 @end cartouche
23184 @end group
23185 @end smallexample
23187 @noindent
23188 @code{Unit_2} is exactly parallel,
23189 it has a procedure @code{Func_2} that references
23190 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23191 the body @code{Unit_2}:
23193 @smallexample @c ada
23194 @cartouche
23195 Sqrt_2 : Float := Sqrt (0.1);
23196 @end cartouche
23197 @end smallexample
23199 @noindent
23200 The elaboration code of the body of @code{Unit_2} also contains:
23202 @smallexample @c ada
23203 @group
23204 @cartouche
23205 if expression_2 = 2 then
23206    Q := Unit_1.Func_1;
23207 end if;
23208 @end cartouche
23209 @end group
23210 @end smallexample
23212 @noindent
23213 Now the question is, which of the following orders of elaboration is
23214 acceptable:
23216 @smallexample
23217 @group
23218 Spec of Unit_1
23219 Spec of Unit_2
23220 Body of Unit_1
23221 Body of Unit_2
23222 @end group
23223 @end smallexample
23225 @noindent
23228 @smallexample
23229 @group
23230 Spec of Unit_2
23231 Spec of Unit_1
23232 Body of Unit_2
23233 Body of Unit_1
23234 @end group
23235 @end smallexample
23237 @noindent
23238 If you carefully analyze the flow here, you will see that you cannot tell
23239 at compile time the answer to this question.
23240 If @code{expression_1} is not equal to 1,
23241 and @code{expression_2} is not equal to 2,
23242 then either order is acceptable, because neither of the function calls is
23243 executed. If both tests evaluate to true, then neither order is acceptable
23244 and in fact there is no correct order.
23246 If one of the two expressions is true, and the other is false, then one
23247 of the above orders is correct, and the other is incorrect. For example,
23248 if @code{expression_1} = 1 and @code{expression_2} /= 2,
23249 then the call to @code{Func_2}
23250 will occur, but not the call to @code{Func_1.}
23251 This means that it is essential
23252 to elaborate the body of @code{Unit_1} before
23253 the body of @code{Unit_2}, so the first
23254 order of elaboration is correct and the second is wrong.
23256 By making @code{expression_1} and @code{expression_2}
23257 depend on input data, or perhaps
23258 the time of day, we can make it impossible for the compiler or binder
23259 to figure out which of these expressions will be true, and hence it
23260 is impossible to guarantee a safe order of elaboration at run time.
23262 @node Checking the Elaboration Order in Ada 95
23263 @section Checking the Elaboration Order in Ada 95
23265 @noindent
23266 In some languages that involve the same kind of elaboration problems,
23267 e.g. Java and C++, the programmer is expected to worry about these
23268 ordering problems himself, and it is common to
23269 write a program in which an incorrect elaboration order  gives
23270 surprising results, because it references variables before they
23271 are initialized.
23272 Ada 95 is designed to be a safe language, and a programmer-beware approach is
23273 clearly not sufficient. Consequently, the language provides three lines
23274 of defense:
23276 @table @asis
23277 @item Standard rules
23278 Some standard rules restrict the possible choice of elaboration
23279 order. In particular, if you @code{with} a unit, then its spec is always
23280 elaborated before the unit doing the @code{with}. Similarly, a parent
23281 spec is always elaborated before the child spec, and finally
23282 a spec is always elaborated before its corresponding body.
23284 @item Dynamic elaboration checks
23285 @cindex Elaboration checks
23286 @cindex Checks, elaboration
23287 Dynamic checks are made at run time, so that if some entity is accessed
23288 before it is elaborated (typically  by means of a subprogram call)
23289 then the exception (@code{Program_Error}) is raised.
23291 @item Elaboration control
23292 Facilities are provided for the programmer to specify the desired order
23293 of elaboration.
23294 @end table
23296 Let's look at these facilities in more detail. First, the rules for
23297 dynamic checking. One possible rule would be simply to say that the
23298 exception is raised if you access a variable which has not yet been
23299 elaborated. The trouble with this approach is that it could require
23300 expensive checks on every variable reference. Instead Ada 95 has two
23301 rules which are a little more restrictive, but easier to check, and
23302 easier to state:
23304 @table @asis
23305 @item Restrictions on calls
23306 A subprogram can only be called at elaboration time if its body
23307 has been elaborated. The rules for elaboration given above guarantee
23308 that the spec of the subprogram has been elaborated before the
23309 call, but not the body. If this rule is violated, then the
23310 exception @code{Program_Error} is raised.
23312 @item Restrictions on instantiations
23313 A generic unit can only be instantiated if the body of the generic
23314 unit has been elaborated. Again, the rules for elaboration given above
23315 guarantee that the spec of the generic unit has been elaborated
23316 before the instantiation, but not the body. If this rule is
23317 violated, then the exception @code{Program_Error} is raised.
23318 @end table
23320 @noindent
23321 The idea is that if the body has been elaborated, then any variables
23322 it references must have been elaborated; by checking for the body being
23323 elaborated we guarantee that none of its references causes any
23324 trouble. As we noted above, this is a little too restrictive, because a
23325 subprogram that has no non-local references in its body may in fact be safe
23326 to call. However, it really would be unsafe to rely on this, because
23327 it would mean that the caller was aware of details of the implementation
23328 in the body. This goes against the basic tenets of Ada.
23330 A plausible implementation can be described as follows.
23331 A Boolean variable is associated with each subprogram
23332 and each generic unit. This variable is initialized to False, and is set to
23333 True at the point body is elaborated. Every call or instantiation checks the
23334 variable, and raises @code{Program_Error} if the variable is False.
23336 Note that one might think that it would be good enough to have one Boolean
23337 variable for each package, but that would not deal with cases of trying
23338 to call a body in the same package as the call
23339 that has not been elaborated yet.
23340 Of course a compiler may be able to do enough analysis to optimize away
23341 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23342 does such optimizations, but still the easiest conceptual model is to
23343 think of there being one variable per subprogram.
23345 @node Controlling the Elaboration Order in Ada 95
23346 @section Controlling the Elaboration Order in Ada 95
23348 @noindent
23349 In the previous section we discussed the rules in Ada 95 which ensure
23350 that @code{Program_Error} is raised if an incorrect elaboration order is
23351 chosen. This prevents erroneous executions, but we need mechanisms to
23352 specify a correct execution and avoid the exception altogether.
23353 To achieve this, Ada 95 provides a number of features for controlling
23354 the order of elaboration. We discuss these features in this section.
23356 First, there are several ways of indicating to the compiler that a given
23357 unit has no elaboration problems:
23359 @table @asis
23360 @item packages that do not require a body
23361 In Ada 95, a library package that does not require a body does not permit
23362 a body. This means that if we have a such a package, as in:
23364 @smallexample @c ada
23365 @group
23366 @cartouche
23367 package Definitions is
23368    generic
23369       type m is new integer;
23370    package Subp is
23371       type a is array (1 .. 10) of m;
23372       type b is array (1 .. 20) of m;
23373    end Subp;
23374 end Definitions;
23375 @end cartouche
23376 @end group
23377 @end smallexample
23379 @noindent
23380 A package that @code{with}'s @code{Definitions} may safely instantiate
23381 @code{Definitions.Subp} because the compiler can determine that there
23382 definitely is no package body to worry about in this case
23384 @item pragma Pure
23385 @cindex pragma Pure
23386 @findex Pure
23387 Places sufficient restrictions on a unit to guarantee that
23388 no call to any subprogram in the unit can result in an
23389 elaboration problem. This means that the compiler does not need
23390 to worry about the point of elaboration of such units, and in
23391 particular, does not need to check any calls to any subprograms
23392 in this unit.
23394 @item pragma Preelaborate
23395 @findex Preelaborate
23396 @cindex pragma Preelaborate
23397 This pragma places slightly less stringent restrictions on a unit than
23398 does pragma Pure,
23399 but these restrictions are still sufficient to ensure that there
23400 are no elaboration problems with any calls to the unit.
23402 @item pragma Elaborate_Body
23403 @findex Elaborate_Body
23404 @cindex pragma Elaborate_Body
23405 This pragma requires that the body of a unit be elaborated immediately
23406 after its spec. Suppose a unit @code{A} has such a pragma,
23407 and unit @code{B} does
23408 a @code{with} of unit @code{A}. Recall that the standard rules require
23409 the spec of unit @code{A}
23410 to be elaborated before the @code{with}'ing unit; given the pragma in
23411 @code{A}, we also know that the body of @code{A}
23412 will be elaborated before @code{B}, so
23413 that calls to @code{A} are safe and do not need a check.
23414 @end table
23416 @noindent
23417 Note that,
23418 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23419 the use of
23420 @code{Elaborate_Body} does not guarantee that the program is
23421 free of elaboration problems, because it may not be possible
23422 to satisfy the requested elaboration order.
23423 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23424 If a programmer
23425 marks @code{Unit_1} as @code{Elaborate_Body},
23426 and not @code{Unit_2,} then the order of
23427 elaboration will be:
23429 @smallexample
23430 @group
23431 Spec of Unit_2
23432 Spec of Unit_1
23433 Body of Unit_1
23434 Body of Unit_2
23435 @end group
23436 @end smallexample
23438 @noindent
23439 Now that means that the call to @code{Func_1} in @code{Unit_2}
23440 need not be checked,
23441 it must be safe. But the call to @code{Func_2} in
23442 @code{Unit_1} may still fail if
23443 @code{Expression_1} is equal to 1,
23444 and the programmer must still take
23445 responsibility for this not being the case.
23447 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23448 eliminated, except for calls entirely within a body, which are
23449 in any case fully under programmer control. However, using the pragma
23450 everywhere is not always possible.
23451 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23452 we marked both of them as having pragma @code{Elaborate_Body}, then
23453 clearly there would be no possible elaboration order.
23455 The above pragmas allow a server to guarantee safe use by clients, and
23456 clearly this is the preferable approach. Consequently a good rule in
23457 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23458 and if this is not possible,
23459 mark them as @code{Elaborate_Body} if possible.
23460 As we have seen, there are situations where neither of these
23461 three pragmas can be used.
23462 So we also provide methods for clients to control the
23463 order of elaboration of the servers on which they depend:
23465 @table @asis
23466 @item pragma Elaborate (unit)
23467 @findex Elaborate
23468 @cindex pragma Elaborate
23469 This pragma is placed in the context clause, after a @code{with} clause,
23470 and it requires that the body of the named unit be elaborated before
23471 the unit in which the pragma occurs. The idea is to use this pragma
23472 if the current unit calls at elaboration time, directly or indirectly,
23473 some subprogram in the named unit.
23475 @item pragma Elaborate_All (unit)
23476 @findex Elaborate_All
23477 @cindex pragma Elaborate_All
23478 This is a stronger version of the Elaborate pragma. Consider the
23479 following example:
23481 @smallexample
23482 Unit A @code{with}'s unit B and calls B.Func in elab code
23483 Unit B @code{with}'s unit C, and B.Func calls C.Func
23484 @end smallexample
23486 @noindent
23487 Now if we put a pragma @code{Elaborate (B)}
23488 in unit @code{A}, this ensures that the
23489 body of @code{B} is elaborated before the call, but not the
23490 body of @code{C}, so
23491 the call to @code{C.Func} could still cause @code{Program_Error} to
23492 be raised.
23494 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23495 not only that the body of the named unit be elaborated before the
23496 unit doing the @code{with}, but also the bodies of all units that the
23497 named unit uses, following @code{with} links transitively. For example,
23498 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23499 then it requires
23500 not only that the body of @code{B} be elaborated before @code{A},
23501 but also the
23502 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23503 @end table
23505 @noindent
23506 We are now in a position to give a usage rule in Ada 95 for avoiding
23507 elaboration problems, at least if dynamic dispatching and access to
23508 subprogram values are not used. We will handle these cases separately
23509 later.
23511 The rule is simple. If a unit has elaboration code that can directly or
23512 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23513 a generic package in a @code{with}'ed unit,
23514 then if the @code{with}'ed unit does not have
23515 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23516 a pragma @code{Elaborate_All}
23517 for the @code{with}'ed unit. By following this rule a client is
23518 assured that calls can be made without risk of an exception.
23520 For generic subprogram instantiations, the rule can be relaxed to
23521 require only a pragma @code{Elaborate} since elaborating the body
23522 of a subprogram cannot cause any transitive elaboration (we are
23523 not calling the subprogram in this case, just elaborating its
23524 declaration).
23526 If this rule is not followed, then a program may be in one of four
23527 states:
23529 @table @asis
23530 @item No order exists
23531 No order of elaboration exists which follows the rules, taking into
23532 account any @code{Elaborate}, @code{Elaborate_All},
23533 or @code{Elaborate_Body} pragmas. In
23534 this case, an Ada 95 compiler must diagnose the situation at bind
23535 time, and refuse to build an executable program.
23537 @item One or more orders exist, all incorrect
23538 One or more acceptable elaboration orders exists, and all of them
23539 generate an elaboration order problem. In this case, the binder
23540 can build an executable program, but @code{Program_Error} will be raised
23541 when the program is run.
23543 @item Several orders exist, some right, some incorrect
23544 One or more acceptable elaboration orders exists, and some of them
23545 work, and some do not. The programmer has not controlled
23546 the order of elaboration, so the binder may or may not pick one of
23547 the correct orders, and the program may or may not raise an
23548 exception when it is run. This is the worst case, because it means
23549 that the program may fail when moved to another compiler, or even
23550 another version of the same compiler.
23552 @item One or more orders exists, all correct
23553 One ore more acceptable elaboration orders exist, and all of them
23554 work. In this case the program runs successfully. This state of
23555 affairs can be guaranteed by following the rule we gave above, but
23556 may be true even if the rule is not followed.
23557 @end table
23559 @noindent
23560 Note that one additional advantage of following our rules on the use
23561 of @code{Elaborate} and @code{Elaborate_All}
23562 is that the program continues to stay in the ideal (all orders OK) state
23563 even if maintenance
23564 changes some bodies of some units. Conversely, if a program that does
23565 not follow this rule happens to be safe at some point, this state of affairs
23566 may deteriorate silently as a result of maintenance changes.
23568 You may have noticed that the above discussion did not mention
23569 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23570 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23571 code in the body makes calls to some other unit, so it is still necessary
23572 to use @code{Elaborate_All} on such units.
23574 @node Controlling Elaboration in GNAT - Internal Calls
23575 @section Controlling Elaboration in GNAT - Internal Calls
23577 @noindent
23578 In the case of internal calls, i.e. calls within a single package, the
23579 programmer has full control over the order of elaboration, and it is up
23580 to the programmer to elaborate declarations in an appropriate order. For
23581 example writing:
23583 @smallexample @c ada
23584 @group
23585 @cartouche
23586 function One return Float;
23588 Q : Float := One;
23590 function One return Float is
23591 begin
23592      return 1.0;
23593 end One;
23594 @end cartouche
23595 @end group
23596 @end smallexample
23598 @noindent
23599 will obviously raise @code{Program_Error} at run time, because function
23600 One will be called before its body is elaborated. In this case GNAT will
23601 generate a warning that the call will raise @code{Program_Error}:
23603 @smallexample
23604 @group
23605 @cartouche
23606  1. procedure y is
23607  2.    function One return Float;
23608  3.
23609  4.    Q : Float := One;
23610                     |
23611     >>> warning: cannot call "One" before body is elaborated
23612     >>> warning: Program_Error will be raised at run time
23614  5.
23615  6.    function One return Float is
23616  7.    begin
23617  8.         return 1.0;
23618  9.    end One;
23620 11. begin
23621 12.    null;
23622 13. end;
23623 @end cartouche
23624 @end group
23625 @end smallexample
23627 @noindent
23628 Note that in this particular case, it is likely that the call is safe, because
23629 the function @code{One} does not access any global variables.
23630 Nevertheless in Ada 95, we do not want the validity of the check to depend on
23631 the contents of the body (think about the separate compilation case), so this
23632 is still wrong, as we discussed in the previous sections.
23634 The error is easily corrected by rearranging the declarations so that the
23635 body of One appears before the declaration containing the call
23636 (note that in Ada 95,
23637 declarations can appear in any order, so there is no restriction that
23638 would prevent this reordering, and if we write:
23640 @smallexample @c ada
23641 @group
23642 @cartouche
23643 function One return Float;
23645 function One return Float is
23646 begin
23647      return 1.0;
23648 end One;
23650 Q : Float := One;
23651 @end cartouche
23652 @end group
23653 @end smallexample
23655 @noindent
23656 then all is well, no warning is generated, and no
23657 @code{Program_Error} exception
23658 will be raised.
23659 Things are more complicated when a chain of subprograms is executed:
23661 @smallexample @c ada
23662 @group
23663 @cartouche
23664 function A return Integer;
23665 function B return Integer;
23666 function C return Integer;
23668 function B return Integer is begin return A; end;
23669 function C return Integer is begin return B; end;
23671 X : Integer := C;
23673 function A return Integer is begin return 1; end;
23674 @end cartouche
23675 @end group
23676 @end smallexample
23678 @noindent
23679 Now the call to @code{C}
23680 at elaboration time in the declaration of @code{X} is correct, because
23681 the body of @code{C} is already elaborated,
23682 and the call to @code{B} within the body of
23683 @code{C} is correct, but the call
23684 to @code{A} within the body of @code{B} is incorrect, because the body
23685 of @code{A} has not been elaborated, so @code{Program_Error}
23686 will be raised on the call to @code{A}.
23687 In this case GNAT will generate a
23688 warning that @code{Program_Error} may be
23689 raised at the point of the call. Let's look at the warning:
23691 @smallexample
23692 @group
23693 @cartouche
23694  1. procedure x is
23695  2.    function A return Integer;
23696  3.    function B return Integer;
23697  4.    function C return Integer;
23698  5.
23699  6.    function B return Integer is begin return A; end;
23700                                                     |
23701     >>> warning: call to "A" before body is elaborated may
23702                  raise Program_Error
23703     >>> warning: "B" called at line 7
23704     >>> warning: "C" called at line 9
23706  7.    function C return Integer is begin return B; end;
23707  8.
23708  9.    X : Integer := C;
23710 11.    function A return Integer is begin return 1; end;
23712 13. begin
23713 14.    null;
23714 15. end;
23715 @end cartouche
23716 @end group
23717 @end smallexample
23719 @noindent
23720 Note that the message here says ``may raise'', instead of the direct case,
23721 where the message says ``will be raised''. That's because whether
23722 @code{A} is
23723 actually called depends in general on run-time flow of control.
23724 For example, if the body of @code{B} said
23726 @smallexample @c ada
23727 @group
23728 @cartouche
23729 function B return Integer is
23730 begin
23731    if some-condition-depending-on-input-data then
23732       return A;
23733    else
23734       return 1;
23735    end if;
23736 end B;
23737 @end cartouche
23738 @end group
23739 @end smallexample
23741 @noindent
23742 then we could not know until run time whether the incorrect call to A would
23743 actually occur, so @code{Program_Error} might
23744 or might not be raised. It is possible for a compiler to
23745 do a better job of analyzing bodies, to
23746 determine whether or not @code{Program_Error}
23747 might be raised, but it certainly
23748 couldn't do a perfect job (that would require solving the halting problem
23749 and is provably impossible), and because this is a warning anyway, it does
23750 not seem worth the effort to do the analysis. Cases in which it
23751 would be relevant are rare.
23753 In practice, warnings of either of the forms given
23754 above will usually correspond to
23755 real errors, and should be examined carefully and eliminated.
23756 In the rare case where a warning is bogus, it can be suppressed by any of
23757 the following methods:
23759 @itemize @bullet
23760 @item
23761 Compile with the @option{-gnatws} switch set
23763 @item
23764 Suppress @code{Elaboration_Check} for the called subprogram
23766 @item
23767 Use pragma @code{Warnings_Off} to turn warnings off for the call
23768 @end itemize
23770 @noindent
23771 For the internal elaboration check case,
23772 GNAT by default generates the
23773 necessary run-time checks to ensure
23774 that @code{Program_Error} is raised if any
23775 call fails an elaboration check. Of course this can only happen if a
23776 warning has been issued as described above. The use of pragma
23777 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23778 some of these checks, meaning that it may be possible (but is not
23779 guaranteed) for a program to be able to call a subprogram whose body
23780 is not yet elaborated, without raising a @code{Program_Error} exception.
23782 @node Controlling Elaboration in GNAT - External Calls
23783 @section Controlling Elaboration in GNAT - External Calls
23785 @noindent
23786 The previous section discussed the case in which the execution of a
23787 particular thread of elaboration code occurred entirely within a
23788 single unit. This is the easy case to handle, because a programmer
23789 has direct and total control over the order of elaboration, and
23790 furthermore, checks need only be generated in cases which are rare
23791 and which the compiler can easily detect.
23792 The situation is more complex when separate compilation is taken into account.
23793 Consider the following:
23795 @smallexample @c ada
23796 @cartouche
23797 @group
23798 package Math is
23799    function Sqrt (Arg : Float) return Float;
23800 end Math;
23802 package body Math is
23803    function Sqrt (Arg : Float) return Float is
23804    begin
23805          ...
23806    end Sqrt;
23807 end Math;
23808 @end group
23809 @group
23810 with Math;
23811 package Stuff is
23812    X : Float := Math.Sqrt (0.5);
23813 end Stuff;
23815 with Stuff;
23816 procedure Main is
23817 begin
23818    ...
23819 end Main;
23820 @end group
23821 @end cartouche
23822 @end smallexample
23824 @noindent
23825 where @code{Main} is the main program. When this program is executed, the
23826 elaboration code must first be executed, and one of the jobs of the
23827 binder is to determine the order in which the units of a program are
23828 to be elaborated. In this case we have four units: the spec and body
23829 of @code{Math},
23830 the spec of @code{Stuff} and the body of @code{Main}).
23831 In what order should the four separate sections of elaboration code
23832 be executed?
23834 There are some restrictions in the order of elaboration that the binder
23835 can choose. In particular, if unit U has a @code{with}
23836 for a package @code{X}, then you
23837 are assured that the spec of @code{X}
23838 is elaborated before U , but you are
23839 not assured that the body of @code{X}
23840 is elaborated before U.
23841 This means that in the above case, the binder is allowed to choose the
23842 order:
23844 @smallexample
23845 spec of Math
23846 spec of Stuff
23847 body of Math
23848 body of Main
23849 @end smallexample
23851 @noindent
23852 but that's not good, because now the call to @code{Math.Sqrt}
23853 that happens during
23854 the elaboration of the @code{Stuff}
23855 spec happens before the body of @code{Math.Sqrt} is
23856 elaborated, and hence causes @code{Program_Error} exception to be raised.
23857 At first glance, one might say that the binder is misbehaving, because
23858 obviously you want to elaborate the body of something you @code{with}
23859 first, but
23860 that is not a general rule that can be followed in all cases. Consider
23862 @smallexample @c ada
23863 @group
23864 @cartouche
23865 package X is ...
23867 package Y is ...
23869 with X;
23870 package body Y is ...
23872 with Y;
23873 package body X is ...
23874 @end cartouche
23875 @end group
23876 @end smallexample
23878 @noindent
23879 This is a common arrangement, and, apart from the order of elaboration
23880 problems that might arise in connection with elaboration code, this works fine.
23881 A rule that says that you must first elaborate the body of anything you
23882 @code{with} cannot work in this case:
23883 the body of @code{X} @code{with}'s @code{Y},
23884 which means you would have to
23885 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23886 which means
23887 you have to elaborate the body of @code{X} first, but ... and we have a
23888 loop that cannot be broken.
23890 It is true that the binder can in many cases guess an order of elaboration
23891 that is unlikely to cause a @code{Program_Error}
23892 exception to be raised, and it tries to do so (in the
23893 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23894 by default
23895 elaborate the body of @code{Math} right after its spec, so all will be well).
23897 However, a program that blindly relies on the binder to be helpful can
23898 get into trouble, as we discussed in the previous sections, so
23899 GNAT
23900 provides a number of facilities for assisting the programmer in
23901 developing programs that are robust with respect to elaboration order.
23903 @node Default Behavior in GNAT - Ensuring Safety
23904 @section Default Behavior in GNAT - Ensuring Safety
23906 @noindent
23907 The default behavior in GNAT ensures elaboration safety. In its
23908 default mode GNAT implements the
23909 rule we previously described as the right approach. Let's restate it:
23911 @itemize
23912 @item
23913 @emph{If a unit has elaboration code that can directly or indirectly make a
23914 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23915 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23916 does not have pragma @code{Pure} or
23917 @code{Preelaborate}, then the client should have an
23918 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23920 @emph{In the case of instantiating a generic subprogram, it is always
23921 sufficient to have only an @code{Elaborate} pragma for the
23922 @code{with}'ed unit.}
23923 @end itemize
23925 @noindent
23926 By following this rule a client is assured that calls and instantiations
23927 can be made without risk of an exception.
23929 In this mode GNAT traces all calls that are potentially made from
23930 elaboration code, and puts in any missing implicit @code{Elaborate}
23931 and @code{Elaborate_All} pragmas.
23932 The advantage of this approach is that no elaboration problems
23933 are possible if the binder can find an elaboration order that is
23934 consistent with these implicit @code{Elaborate} and
23935 @code{Elaborate_All} pragmas. The
23936 disadvantage of this approach is that no such order may exist.
23938 If the binder does not generate any diagnostics, then it means that it has
23939 found an elaboration order that is guaranteed to be safe. However, the binder
23940 may still be relying on implicitly generated @code{Elaborate} and
23941 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23942 guaranteed.
23944 If it is important to guarantee portability, then the compilations should
23945 use the
23946 @option{-gnatwl}
23947 (warn on elaboration problems) switch. This will cause warning messages
23948 to be generated indicating the missing @code{Elaborate} and
23949 @code{Elaborate_All} pragmas.
23950 Consider the following source program:
23952 @smallexample @c ada
23953 @group
23954 @cartouche
23955 with k;
23956 package j is
23957   m : integer := k.r;
23958 end;
23959 @end cartouche
23960 @end group
23961 @end smallexample
23963 @noindent
23964 where it is clear that there
23965 should be a pragma @code{Elaborate_All}
23966 for unit @code{k}. An implicit pragma will be generated, and it is
23967 likely that the binder will be able to honor it. However, if you want
23968 to port this program to some other Ada compiler than GNAT.
23969 it is safer to include the pragma explicitly in the source. If this
23970 unit is compiled with the
23971 @option{-gnatwl}
23972 switch, then the compiler outputs a warning:
23974 @smallexample
23975 @group
23976 @cartouche
23977 1. with k;
23978 2. package j is
23979 3.   m : integer := k.r;
23980                      |
23981    >>> warning: call to "r" may raise Program_Error
23982    >>> warning: missing pragma Elaborate_All for "k"
23984 4. end;
23985 @end cartouche
23986 @end group
23987 @end smallexample
23989 @noindent
23990 and these warnings can be used as a guide for supplying manually
23991 the missing pragmas. It is usually a bad idea to use this warning
23992 option during development. That's because it will warn you when
23993 you need to put in a pragma, but cannot warn you when it is time
23994 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23995 unnecessary dependencies and even false circularities.
23997 This default mode is more restrictive than the Ada Reference
23998 Manual, and it is possible to construct programs which will compile
23999 using the dynamic model described there, but will run into a
24000 circularity using the safer static model we have described.
24002 Of course any Ada compiler must be able to operate in a mode
24003 consistent with the requirements of the Ada Reference Manual,
24004 and in particular must have the capability of implementing the
24005 standard dynamic model of elaboration with run-time checks.
24007 In GNAT, this standard mode can be achieved either by the use of
24008 the @option{-gnatE} switch on the compiler (@command{gcc} or
24009 @command{gnatmake}) command, or by the use of the configuration pragma:
24011 @smallexample @c ada
24012 pragma Elaboration_Checks (RM);
24013 @end smallexample
24015 @noindent
24016 Either approach will cause the unit affected to be compiled using the
24017 standard dynamic run-time elaboration checks described in the Ada
24018 Reference Manual. The static model is generally preferable, since it
24019 is clearly safer to rely on compile and link time checks rather than
24020 run-time checks. However, in the case of legacy code, it may be
24021 difficult to meet the requirements of the static model. This
24022 issue is further discussed in
24023 @ref{What to Do If the Default Elaboration Behavior Fails}.
24025 Note that the static model provides a strict subset of the allowed
24026 behavior and programs of the Ada Reference Manual, so if you do
24027 adhere to the static model and no circularities exist,
24028 then you are assured that your program will
24029 work using the dynamic model, providing that you remove any
24030 pragma Elaborate statements from the source.
24032 @node Treatment of Pragma Elaborate
24033 @section Treatment of Pragma Elaborate
24034 @cindex Pragma Elaborate
24036 @noindent
24037 The use of @code{pragma Elaborate}
24038 should generally be avoided in Ada 95 programs.
24039 The reason for this is that there is no guarantee that transitive calls
24040 will be properly handled. Indeed at one point, this pragma was placed
24041 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24043 Now that's a bit restrictive. In practice, the case in which
24044 @code{pragma Elaborate} is useful is when the caller knows that there
24045 are no transitive calls, or that the called unit contains all necessary
24046 transitive @code{pragma Elaborate} statements, and legacy code often
24047 contains such uses.
24049 Strictly speaking the static mode in GNAT should ignore such pragmas,
24050 since there is no assurance at compile time that the necessary safety
24051 conditions are met. In practice, this would cause GNAT to be incompatible
24052 with correctly written Ada 83 code that had all necessary
24053 @code{pragma Elaborate} statements in place. Consequently, we made the
24054 decision that GNAT in its default mode will believe that if it encounters
24055 a @code{pragma Elaborate} then the programmer knows what they are doing,
24056 and it will trust that no elaboration errors can occur.
24058 The result of this decision is two-fold. First to be safe using the
24059 static mode, you should remove all @code{pragma Elaborate} statements.
24060 Second, when fixing circularities in existing code, you can selectively
24061 use @code{pragma Elaborate} statements to convince the static mode of
24062 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24063 statement.
24065 When using the static mode with @option{-gnatwl}, any use of
24066 @code{pragma Elaborate} will generate a warning about possible
24067 problems.
24069 @node Elaboration Issues for Library Tasks
24070 @section Elaboration Issues for Library Tasks
24071 @cindex Library tasks, elaboration issues
24072 @cindex Elaboration of library tasks
24074 @noindent
24075 In this section we examine special elaboration issues that arise for
24076 programs that declare library level tasks.
24078 Generally the model of execution of an Ada program is that all units are
24079 elaborated, and then execution of the program starts. However, the
24080 declaration of library tasks definitely does not fit this model. The
24081 reason for this is that library tasks start as soon as they are declared
24082 (more precisely, as soon as the statement part of the enclosing package
24083 body is reached), that is to say before elaboration
24084 of the program is complete. This means that if such a task calls a
24085 subprogram, or an entry in another task, the callee may or may not be
24086 elaborated yet, and in the standard
24087 Reference Manual model of dynamic elaboration checks, you can even
24088 get timing dependent Program_Error exceptions, since there can be
24089 a race between the elaboration code and the task code.
24091 The static model of elaboration in GNAT seeks to avoid all such
24092 dynamic behavior, by being conservative, and the conservative
24093 approach in this particular case is to assume that all the code
24094 in a task body is potentially executed at elaboration time if
24095 a task is declared at the library level.
24097 This can definitely result in unexpected circularities. Consider
24098 the following example
24100 @smallexample @c ada
24101 package Decls is
24102   task Lib_Task is
24103      entry Start;
24104   end Lib_Task;
24106   type My_Int is new Integer;
24108   function Ident (M : My_Int) return My_Int;
24109 end Decls;
24111 with Utils;
24112 package body Decls is
24113   task body Lib_Task is
24114   begin
24115      accept Start;
24116      Utils.Put_Val (2);
24117   end Lib_Task;
24119   function Ident (M : My_Int) return My_Int is
24120   begin
24121      return M;
24122   end Ident;
24123 end Decls;
24125 with Decls;
24126 package Utils is
24127   procedure Put_Val (Arg : Decls.My_Int);
24128 end Utils;
24130 with Text_IO;
24131 package body Utils is
24132   procedure Put_Val (Arg : Decls.My_Int) is
24133   begin
24134      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24135   end Put_Val;
24136 end Utils;
24138 with Decls;
24139 procedure Main is
24140 begin
24141    Decls.Lib_Task.Start;
24142 end;
24143 @end smallexample
24145 @noindent
24146 If the above example is compiled in the default static elaboration
24147 mode, then a circularity occurs. The circularity comes from the call
24148 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24149 this call occurs in elaboration code, we need an implicit pragma
24150 @code{Elaborate_All} for @code{Utils}. This means that not only must
24151 the spec and body of @code{Utils} be elaborated before the body
24152 of @code{Decls}, but also the spec and body of any unit that is
24153 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24154 the body of @code{Decls}. This is the transitive implication of
24155 pragma @code{Elaborate_All} and it makes sense, because in general
24156 the body of @code{Put_Val} might have a call to something in a
24157 @code{with'ed} unit.
24159 In this case, the body of Utils (actually its spec) @code{with's}
24160 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24161 must be elaborated before itself, in case there is a call from the
24162 body of @code{Utils}.
24164 Here is the exact chain of events we are worrying about:
24166 @enumerate
24167 @item
24168 In the body of @code{Decls} a call is made from within the body of a library
24169 task to a subprogram in the package @code{Utils}. Since this call may
24170 occur at elaboration time (given that the task is activated at elaboration
24171 time), we have to assume the worst, i.e. that the
24172 call does happen at elaboration time.
24174 @item
24175 This means that the body and spec of @code{Util} must be elaborated before
24176 the body of @code{Decls} so that this call does not cause an access before
24177 elaboration.
24179 @item
24180 Within the body of @code{Util}, specifically within the body of
24181 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24182 by this package.
24184 @item
24185 One such @code{with}'ed package is package @code{Decls}, so there
24186 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24187 In fact there is such a call in this example, but we would have to
24188 assume that there was such a call even if it were not there, since
24189 we are not supposed to write the body of @code{Decls} knowing what
24190 is in the body of @code{Utils}; certainly in the case of the
24191 static elaboration model, the compiler does not know what is in
24192 other bodies and must assume the worst.
24194 @item
24195 This means that the spec and body of @code{Decls} must also be
24196 elaborated before we elaborate the unit containing the call, but
24197 that unit is @code{Decls}! This means that the body of @code{Decls}
24198 must be elaborated before itself, and that's a circularity.
24199 @end enumerate
24201 @noindent
24202 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24203 the body of @code{Decls} you will get a true Ada Reference Manual
24204 circularity that makes the program illegal.
24206 In practice, we have found that problems with the static model of
24207 elaboration in existing code often arise from library tasks, so
24208 we must address this particular situation.
24210 Note that if we compile and run the program above, using the dynamic model of
24211 elaboration (that is to say use the @option{-gnatE} switch),
24212 then it compiles, binds,
24213 links, and runs, printing the expected result of 2. Therefore in some sense
24214 the circularity here is only apparent, and we need to capture
24215 the properties of this program that  distinguish it from other library-level
24216 tasks that have real elaboration problems.
24218 We have four possible answers to this question:
24220 @itemize @bullet
24222 @item
24223 Use the dynamic model of elaboration.
24225 If we use the @option{-gnatE} switch, then as noted above, the program works.
24226 Why is this? If we examine the task body, it is apparent that the task cannot
24227 proceed past the
24228 @code{accept} statement until after elaboration has been completed, because
24229 the corresponding entry call comes from the main program, not earlier.
24230 This is why the dynamic model works here. But that's really giving
24231 up on a precise analysis, and we prefer to take this approach only if we cannot
24232 solve the
24233 problem in any other manner. So let us examine two ways to reorganize
24234 the program to avoid the potential elaboration problem.
24236 @item
24237 Split library tasks into separate packages.
24239 Write separate packages, so that library tasks are isolated from
24240 other declarations as much as possible. Let us look at a variation on
24241 the above program.
24243 @smallexample @c ada
24244 package Decls1 is
24245   task Lib_Task is
24246      entry Start;
24247   end Lib_Task;
24248 end Decls1;
24250 with Utils;
24251 package body Decls1 is
24252   task body Lib_Task is
24253   begin
24254      accept Start;
24255      Utils.Put_Val (2);
24256   end Lib_Task;
24257 end Decls1;
24259 package Decls2 is
24260   type My_Int is new Integer;
24261   function Ident (M : My_Int) return My_Int;
24262 end Decls2;
24264 with Utils;
24265 package body Decls2 is
24266   function Ident (M : My_Int) return My_Int is
24267   begin
24268      return M;
24269   end Ident;
24270 end Decls2;
24272 with Decls2;
24273 package Utils is
24274   procedure Put_Val (Arg : Decls2.My_Int);
24275 end Utils;
24277 with Text_IO;
24278 package body Utils is
24279   procedure Put_Val (Arg : Decls2.My_Int) is
24280   begin
24281      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24282   end Put_Val;
24283 end Utils;
24285 with Decls1;
24286 procedure Main is
24287 begin
24288    Decls1.Lib_Task.Start;
24289 end;
24290 @end smallexample
24292 @noindent
24293 All we have done is to split @code{Decls} into two packages, one
24294 containing the library task, and one containing everything else. Now
24295 there is no cycle, and the program compiles, binds, links and executes
24296 using the default static model of elaboration.
24298 @item
24299 Declare separate task types.
24301 A significant part of the problem arises because of the use of the
24302 single task declaration form. This means that the elaboration of
24303 the task type, and the elaboration of the task itself (i.e. the
24304 creation of the task) happen at the same time. A good rule
24305 of style in Ada 95 is to always create explicit task types. By
24306 following the additional step of placing task objects in separate
24307 packages from the task type declaration, many elaboration problems
24308 are avoided. Here is another modified example of the example program:
24310 @smallexample @c ada
24311 package Decls is
24312   task type Lib_Task_Type is
24313      entry Start;
24314   end Lib_Task_Type;
24316   type My_Int is new Integer;
24318   function Ident (M : My_Int) return My_Int;
24319 end Decls;
24321 with Utils;
24322 package body Decls is
24323   task body Lib_Task_Type is
24324   begin
24325      accept Start;
24326      Utils.Put_Val (2);
24327   end Lib_Task_Type;
24329   function Ident (M : My_Int) return My_Int is
24330   begin
24331      return M;
24332   end Ident;
24333 end Decls;
24335 with Decls;
24336 package Utils is
24337   procedure Put_Val (Arg : Decls.My_Int);
24338 end Utils;
24340 with Text_IO;
24341 package body Utils is
24342   procedure Put_Val (Arg : Decls.My_Int) is
24343   begin
24344      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24345   end Put_Val;
24346 end Utils;
24348 with Decls;
24349 package Declst is
24350    Lib_Task : Decls.Lib_Task_Type;
24351 end Declst;
24353 with Declst;
24354 procedure Main is
24355 begin
24356    Declst.Lib_Task.Start;
24357 end;
24358 @end smallexample
24360 @noindent
24361 What we have done here is to replace the @code{task} declaration in
24362 package @code{Decls} with a @code{task type} declaration. Then we
24363 introduce a separate package @code{Declst} to contain the actual
24364 task object. This separates the elaboration issues for
24365 the @code{task type}
24366 declaration, which causes no trouble, from the elaboration issues
24367 of the task object, which is also unproblematic, since it is now independent
24368 of the elaboration of  @code{Utils}.
24369 This separation of concerns also corresponds to
24370 a generally sound engineering principle of separating declarations
24371 from instances. This version of the program also compiles, binds, links,
24372 and executes, generating the expected output.
24374 @item
24375 Use No_Entry_Calls_In_Elaboration_Code restriction.
24376 @cindex No_Entry_Calls_In_Elaboration_Code
24378 The previous two approaches described how a program can be restructured
24379 to avoid the special problems caused by library task bodies. in practice,
24380 however, such restructuring may be difficult to apply to existing legacy code,
24381 so we must consider solutions that do not require massive rewriting.
24383 Let us consider more carefully why our original sample program works
24384 under the dynamic model of elaboration. The reason is that the code
24385 in the task body blocks immediately on the @code{accept}
24386 statement. Now of course there is nothing to prohibit elaboration
24387 code from making entry calls (for example from another library level task),
24388 so we cannot tell in isolation that
24389 the task will not execute the accept statement  during elaboration.
24391 However, in practice it is very unusual to see elaboration code
24392 make any entry calls, and the pattern of tasks starting
24393 at elaboration time and then immediately blocking on @code{accept} or
24394 @code{select} statements is very common. What this means is that
24395 the compiler is being too pessimistic when it analyzes the
24396 whole package body as though it might be executed at elaboration
24397 time.
24399 If we know that the elaboration code contains no entry calls, (a very safe
24400 assumption most of the time, that could almost be made the default
24401 behavior), then we can compile all units of the program under control
24402 of the following configuration pragma:
24404 @smallexample
24405 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24406 @end smallexample
24408 @noindent
24409 This pragma can be placed in the @file{gnat.adc} file in the usual
24410 manner. If we take our original unmodified program and compile it
24411 in the presence of a @file{gnat.adc} containing the above pragma,
24412 then once again, we can compile, bind, link, and execute, obtaining
24413 the expected result. In the presence of this pragma, the compiler does
24414 not trace calls in a task body, that appear after the first @code{accept}
24415 or @code{select} statement, and therefore does not report a potential
24416 circularity in the original program.
24418 The compiler will check to the extent it can that the above
24419 restriction is not violated, but it is not always possible to do a
24420 complete check at compile time, so it is important to use this
24421 pragma only if the stated restriction is in fact met, that is to say
24422 no task receives an entry call before elaboration of all units is completed.
24424 @end itemize
24426 @node Mixing Elaboration Models
24427 @section Mixing Elaboration Models
24428 @noindent
24429 So far, we have assumed that the entire program is either compiled
24430 using the dynamic model or static model, ensuring consistency. It
24431 is possible to mix the two models, but rules have to be followed
24432 if this mixing is done to ensure that elaboration checks are not
24433 omitted.
24435 The basic rule is that @emph{a unit compiled with the static model cannot
24436 be @code{with'ed} by a unit compiled with the dynamic model}. The
24437 reason for this is that in the static model, a unit assumes that
24438 its clients guarantee to use (the equivalent of) pragma
24439 @code{Elaborate_All} so that no elaboration checks are required
24440 in inner subprograms, and this assumption is violated if the
24441 client is compiled with dynamic checks.
24443 The precise rule is as follows. A unit that is compiled with dynamic
24444 checks can only @code{with} a unit that meets at least one of the
24445 following criteria:
24447 @itemize @bullet
24449 @item
24450 The @code{with'ed} unit is itself compiled with dynamic elaboration
24451 checks (that is with the @option{-gnatE} switch.
24453 @item
24454 The @code{with'ed} unit is an internal GNAT implementation unit from
24455 the System, Interfaces, Ada, or GNAT hierarchies.
24457 @item
24458 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24460 @item
24461 The @code{with'ing} unit (that is the client) has an explicit pragma
24462 @code{Elaborate_All} for the @code{with'ed} unit.
24464 @end itemize
24466 @noindent
24467 If this rule is violated, that is if a unit with dynamic elaboration
24468 checks @code{with's} a unit that does not meet one of the above four
24469 criteria, then the binder (@code{gnatbind}) will issue a warning
24470 similar to that in the following example:
24472 @smallexample
24473 warning: "x.ads" has dynamic elaboration checks and with's
24474 warning:   "y.ads" which has static elaboration checks
24475 @end smallexample
24477 @noindent
24478 These warnings indicate that the rule has been violated, and that as a result
24479 elaboration checks may be missed in the resulting executable file.
24480 This warning may be suppressed using the @option{-ws} binder switch
24481 in the usual manner.
24483 One useful application of this mixing rule is in the case of a subsystem
24484 which does not itself @code{with} units from the remainder of the
24485 application. In this case, the entire subsystem can be compiled with
24486 dynamic checks to resolve a circularity in the subsystem, while
24487 allowing the main application that uses this subsystem to be compiled
24488 using the more reliable default static model.
24490 @node What to Do If the Default Elaboration Behavior Fails
24491 @section What to Do If the Default Elaboration Behavior Fails
24493 @noindent
24494 If the binder cannot find an acceptable order, it outputs detailed
24495 diagnostics. For example:
24496 @smallexample
24497 @group
24498 @iftex
24499 @leftskip=0cm
24500 @end iftex
24501 error: elaboration circularity detected
24502 info:   "proc (body)" must be elaborated before "pack (body)"
24503 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24504 info:     recompile "pack (body)" with -gnatwl
24505 info:                             for full details
24506 info:       "proc (body)"
24507 info:         is needed by its spec:
24508 info:       "proc (spec)"
24509 info:         which is withed by:
24510 info:       "pack (body)"
24511 info:  "pack (body)" must be elaborated before "proc (body)"
24512 info:     reason: pragma Elaborate in unit "proc (body)"
24513 @end group
24515 @end smallexample
24517 @noindent
24518 In this case we have a cycle that the binder cannot break. On the one
24519 hand, there is an explicit pragma Elaborate in @code{proc} for
24520 @code{pack}. This means that the body of @code{pack} must be elaborated
24521 before the body of @code{proc}. On the other hand, there is elaboration
24522 code in @code{pack} that calls a subprogram in @code{proc}. This means
24523 that for maximum safety, there should really be a pragma
24524 Elaborate_All in @code{pack} for @code{proc} which would require that
24525 the body of @code{proc} be elaborated before the body of
24526 @code{pack}. Clearly both requirements cannot be satisfied.
24527 Faced with a circularity of this kind, you have three different options.
24529 @table @asis
24530 @item Fix the program
24531 The most desirable option from the point of view of long-term maintenance
24532 is to rearrange the program so that the elaboration problems are avoided.
24533 One useful technique is to place the elaboration code into separate
24534 child packages. Another is to move some of the initialization code to
24535 explicitly called subprograms, where the program controls the order
24536 of initialization explicitly. Although this is the most desirable option,
24537 it may be impractical and involve too much modification, especially in
24538 the case of complex legacy code.
24540 @item Perform dynamic checks
24541 If the compilations are done using the
24542 @option{-gnatE}
24543 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24544 manner. Dynamic checks are generated for all calls that could possibly result
24545 in raising an exception. With this switch, the compiler does not generate
24546 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24547 exactly as specified in the Ada 95 Reference Manual. The binder will generate
24548 an executable program that may or may not raise @code{Program_Error}, and then
24549 it is the programmer's job to ensure that it does not raise an exception. Note
24550 that it is important to compile all units with the switch, it cannot be used
24551 selectively.
24553 @item Suppress checks
24554 The drawback of dynamic checks is that they generate a
24555 significant overhead at run time, both in space and time. If you
24556 are absolutely sure that your program cannot raise any elaboration
24557 exceptions, and you still want to use the dynamic elaboration model,
24558 then you can use the configuration pragma
24559 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24560 example this pragma could be placed in the @file{gnat.adc} file.
24562 @item Suppress checks selectively
24563 When you know that certain calls or instantiations in elaboration code cannot
24564 possibly lead to an elaboration error, and the binder nevertheless complains
24565 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24566 elaboration circularities, it is possible to remove those warnings locally and
24567 obtain a program that will bind. Clearly this can be unsafe, and it is the
24568 responsibility of the programmer to make sure that the resulting program has no
24569 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24570 used with different granularity to suppress warnings and break elaboration
24571 circularities:
24573 @itemize @bullet
24574 @item
24575 Place the pragma that names the called subprogram in the declarative part
24576 that contains the call.
24578 @item
24579 Place the pragma in the declarative part, without naming an entity. This
24580 disables warnings on all calls in the corresponding  declarative region.
24582 @item
24583 Place the pragma in the package spec that declares the called subprogram,
24584 and name the subprogram. This disables warnings on all elaboration calls to
24585 that subprogram.
24587 @item
24588 Place the pragma in the package spec that declares the called subprogram,
24589 without naming any entity. This disables warnings on all elaboration calls to
24590 all subprograms declared in this spec.
24592 @item Use Pragma Elaborate
24593 As previously described in section @xref{Treatment of Pragma Elaborate},
24594 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24595 that no elaboration checks are required on calls to the designated unit.
24596 There may be cases in which the caller knows that no transitive calls
24597 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24598 case where @code{pragma Elaborate_All} would cause a circularity.
24599 @end itemize
24601 @noindent
24602 These five cases are listed in order of decreasing safety, and therefore
24603 require increasing programmer care in their application. Consider the
24604 following program:
24606 @smallexample @c adanocomment
24607 package Pack1 is
24608   function F1 return Integer;
24609   X1 : Integer;
24610 end Pack1;
24612 package Pack2 is
24613   function F2 return Integer;
24614   function Pure (x : integer) return integer;
24615   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24616   --  pragma Suppress (Elaboration_Check);              -- (4)
24617 end Pack2;
24619 with Pack2;
24620 package body Pack1 is
24621   function F1 return Integer is
24622   begin
24623     return 100;
24624   end F1;
24625   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24626 begin
24627   declare
24628     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24629     --  pragma Suppress(Elaboration_Check);             -- (2)
24630   begin
24631     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24632   end;
24633 end Pack1;
24635 with Pack1;
24636 package body Pack2 is
24637   function F2 return Integer is
24638   begin
24639      return Pack1.F1;
24640   end F2;
24641   function Pure (x : integer) return integer is
24642   begin
24643      return x ** 3 - 3 * x;
24644   end;
24645 end Pack2;
24647 with Pack1, Ada.Text_IO;
24648 procedure Proc3 is
24649 begin
24650   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24651 end Proc3;
24652 @end smallexample
24653 In the absence of any pragmas, an attempt to bind this program produces
24654 the following diagnostics:
24655 @smallexample
24656 @group
24657 @iftex
24658 @leftskip=.5cm
24659 @end iftex
24660 error: elaboration circularity detected
24661 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24662 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24663 info:       recompile "pack1 (body)" with -gnatwl for full details
24664 info:          "pack1 (body)"
24665 info:             must be elaborated along with its spec:
24666 info:          "pack1 (spec)"
24667 info:             which is withed by:
24668 info:          "pack2 (body)"
24669 info:             which must be elaborated along with its spec:
24670 info:          "pack2 (spec)"
24671 info:             which is withed by:
24672 info:          "pack1 (body)"
24673 @end group
24674 @end smallexample
24675 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24676 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24677 F2 is safe, even though F2 calls F1, because the call appears after the
24678 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24679 remove the warning on the call. It is also possible to use pragma (2)
24680 because there are no other potentially unsafe calls in the block.
24682 @noindent
24683 The call to @code{Pure} is safe because this function does not depend on the
24684 state of @code{Pack2}. Therefore any call to this function is safe, and it
24685 is correct to place pragma (3) in the corresponding package spec.
24687 @noindent
24688 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24689 warnings on all calls to functions declared therein. Note that this is not
24690 necessarily safe, and requires more detailed examination of the subprogram
24691 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24692 be already elaborated.
24693 @end table
24695 @noindent
24696 It is hard to generalize on which of these four approaches should be
24697 taken. Obviously if it is possible to fix the program so that the default
24698 treatment works, this is preferable, but this may not always be practical.
24699 It is certainly simple enough to use
24700 @option{-gnatE}
24701 but the danger in this case is that, even if the GNAT binder
24702 finds a correct elaboration order, it may not always do so,
24703 and certainly a binder from another Ada compiler might not. A
24704 combination of testing and analysis (for which the warnings generated
24705 with the
24706 @option{-gnatwl}
24707 switch can be useful) must be used to ensure that the program is free
24708 of errors. One switch that is useful in this testing is the
24709 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24710 switch for
24711 @code{gnatbind}.
24712 Normally the binder tries to find an order that has the best chance of
24713 of avoiding elaboration problems. With this switch, the binder
24714 plays a devil's advocate role, and tries to choose the order that
24715 has the best chance of failing. If your program works even with this
24716 switch, then it has a better chance of being error free, but this is still
24717 not a guarantee.
24719 For an example of this approach in action, consider the C-tests (executable
24720 tests) from the ACVC suite. If these are compiled and run with the default
24721 treatment, then all but one of them succeed without generating any error
24722 diagnostics from the binder. However, there is one test that fails, and
24723 this is not surprising, because the whole point of this test is to ensure
24724 that the compiler can handle cases where it is impossible to determine
24725 a correct order statically, and it checks that an exception is indeed
24726 raised at run time.
24728 This one test must be compiled and run using the
24729 @option{-gnatE}
24730 switch, and then it passes. Alternatively, the entire suite can
24731 be run using this switch. It is never wrong to run with the dynamic
24732 elaboration switch if your code is correct, and we assume that the
24733 C-tests are indeed correct (it is less efficient, but efficiency is
24734 not a factor in running the ACVC tests.)
24736 @node Elaboration for Access-to-Subprogram Values
24737 @section Elaboration for Access-to-Subprogram Values
24738 @cindex Access-to-subprogram
24740 @noindent
24741 The introduction of access-to-subprogram types in Ada 95 complicates
24742 the handling of elaboration. The trouble is that it becomes
24743 impossible to tell at compile time which procedure
24744 is being called. This means that it is not possible for the binder
24745 to analyze the elaboration requirements in this case.
24747 If at the point at which the access value is created
24748 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24749 the body of the subprogram is
24750 known to have been elaborated, then the access value is safe, and its use
24751 does not require a check. This may be achieved by appropriate arrangement
24752 of the order of declarations if the subprogram is in the current unit,
24753 or, if the subprogram is in another unit, by using pragma
24754 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24755 on the referenced unit.
24757 If the referenced body is not known to have been elaborated at the point
24758 the access value is created, then any use of the access value must do a
24759 dynamic check, and this dynamic check will fail and raise a
24760 @code{Program_Error} exception if the body has not been elaborated yet.
24761 GNAT will generate the necessary checks, and in addition, if the
24762 @option{-gnatwl}
24763 switch is set, will generate warnings that such checks are required.
24765 The use of dynamic dispatching for tagged types similarly generates
24766 a requirement for dynamic checks, and premature calls to any primitive
24767 operation of a tagged type before the body of the operation has been
24768 elaborated, will result in the raising of @code{Program_Error}.
24770 @node Summary of Procedures for Elaboration Control
24771 @section Summary of Procedures for Elaboration Control
24772 @cindex Elaboration control
24774 @noindent
24775 First, compile your program with the default options, using none of
24776 the special elaboration control switches. If the binder successfully
24777 binds your program, then you can be confident that, apart from issues
24778 raised by the use of access-to-subprogram types and dynamic dispatching,
24779 the program is free of elaboration errors. If it is important that the
24780 program be portable, then use the
24781 @option{-gnatwl}
24782 switch to generate warnings about missing @code{Elaborate} or
24783 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24785 If the program fails to bind using the default static elaboration
24786 handling, then you can fix the program to eliminate the binder
24787 message, or recompile the entire program with the
24788 @option{-gnatE} switch to generate dynamic elaboration checks,
24789 and, if you are sure there really are no elaboration problems,
24790 use a global pragma @code{Suppress (Elaboration_Check)}.
24792 @node Other Elaboration Order Considerations
24793 @section Other Elaboration Order Considerations
24794 @noindent
24795 This section has been entirely concerned with the issue of finding a valid
24796 elaboration order, as defined by the Ada Reference Manual. In a case
24797 where several elaboration orders are valid, the task is to find one
24798 of the possible valid elaboration orders (and the static model in GNAT
24799 will ensure that this is achieved).
24801 The purpose of the elaboration rules in the Ada Reference Manual is to
24802 make sure that no entity is accessed before it has been elaborated. For
24803 a subprogram, this means that the spec and body must have been elaborated
24804 before the subprogram is called. For an object, this means that the object
24805 must have been elaborated before its value is read or written. A violation
24806 of either of these two requirements is an access before elaboration order,
24807 and this section has been all about avoiding such errors.
24809 In the case where more than one order of elaboration is possible, in the
24810 sense that access before elaboration errors are avoided, then any one of
24811 the orders is ``correct'' in the sense that it meets the requirements of
24812 the Ada Reference Manual, and no such error occurs.
24814 However, it may be the case for a given program, that there are
24815 constraints on the order of elaboration that come not from consideration
24816 of avoiding elaboration errors, but rather from extra-lingual logic
24817 requirements. Consider this example:
24819 @smallexample @c ada
24820 with Init_Constants;
24821 package Constants is
24822    X : Integer := 0;
24823    Y : Integer := 0;
24824 end Constants;
24826 package Init_Constants is
24827    procedure P; -- require a body
24828 end Init_Constants;
24830 with Constants;
24831 package body Init_Constants is
24832    procedure P is begin null; end;
24833 begin
24834    Constants.X := 3;
24835    Constants.Y := 4;
24836 end Init_Constants;
24838 with Constants;
24839 package Calc is
24840    Z : Integer := Constants.X + Constants.Y;
24841 end Calc;
24843 with Calc;
24844 with Text_IO; use Text_IO;
24845 procedure Main is
24846 begin
24847    Put_Line (Calc.Z'Img);
24848 end Main;
24849 @end smallexample
24851 @noindent
24852 In this example, there is more than one valid order of elaboration. For
24853 example both the following are correct orders:
24855 @smallexample
24856 Init_Constants spec
24857 Constants spec
24858 Calc spec
24859 Init_Constants body
24860 Main body
24862   and
24864 Init_Constants spec
24865 Init_Constants body
24866 Constants spec
24867 Calc spec
24868 Main body
24869 @end smallexample
24871 @noindent
24872 There is no language rule to prefer one or the other, both are correct
24873 from an order of elaboration point of view. But the programmatic effects
24874 of the two orders are very different. In the first, the elaboration routine
24875 of @code{Calc} initializes @code{Z} to zero, and then the main program
24876 runs with this value of zero. But in the second order, the elaboration
24877 routine of @code{Calc} runs after the body of Init_Constants has set
24878 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24879 runs.
24881 One could perhaps by applying pretty clever non-artificial intelligence
24882 to the situation guess that it is more likely that the second order of
24883 elaboration is the one desired, but there is no formal linguistic reason
24884 to prefer one over the other. In fact in this particular case, GNAT will
24885 prefer the second order, because of the rule that bodies are elaborated
24886 as soon as possible, but it's just luck that this is what was wanted
24887 (if indeed the second order was preferred).
24889 If the program cares about the order of elaboration routines in a case like
24890 this, it is important to specify the order required. In this particular
24891 case, that could have been achieved by adding to the spec of Calc:
24893 @smallexample @c ada
24894 pragma Elaborate_All (Constants);
24895 @end smallexample
24897 @noindent
24898 which requires that the body (if any) and spec of @code{Constants},
24899 as well as the body and spec of any unit @code{with}'ed by
24900 @code{Constants} be elaborated before @code{Calc} is elaborated.
24902 Clearly no automatic method can always guess which alternative you require,
24903 and if you are working with legacy code that had constraints of this kind
24904 which were not properly specified by adding @code{Elaborate} or
24905 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24906 compilers can choose different orders.
24908 The @code{gnatbind}
24909 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24910 out problems. This switch causes bodies to be elaborated as late as possible
24911 instead of as early as possible. In the example above, it would have forced
24912 the choice of the first elaboration order. If you get different results
24913 when using this switch, and particularly if one set of results is right,
24914 and one is wrong as far as you are concerned, it shows that you have some
24915 missing @code{Elaborate} pragmas. For the example above, we have the
24916 following output:
24918 @smallexample
24919 gnatmake -f -q main
24920 main
24922 gnatmake -f -q main -bargs -p
24923 main
24925 @end smallexample
24927 @noindent
24928 It is of course quite unlikely that both these results are correct, so
24929 it is up to you in a case like this to investigate the source of the
24930 difference, by looking at the two elaboration orders that are chosen,
24931 and figuring out which is correct, and then adding the necessary
24932 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24934 @node Inline Assembler
24935 @appendix Inline Assembler
24937 @noindent
24938 If you need to write low-level software that interacts directly
24939 with the hardware, Ada provides two ways to incorporate assembly
24940 language code into your program.  First, you can import and invoke
24941 external routines written in assembly language, an Ada feature fully
24942 supported by GNAT.  However, for small sections of code it may be simpler
24943 or more efficient to include assembly language statements directly
24944 in your Ada source program, using the facilities of the implementation-defined
24945 package @code{System.Machine_Code}, which incorporates the gcc
24946 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
24947 including the following:
24949 @itemize @bullet
24950 @item No need to use non-Ada tools
24951 @item Consistent interface over different targets
24952 @item Automatic usage of the proper calling conventions
24953 @item Access to Ada constants and variables
24954 @item Definition of intrinsic routines
24955 @item Possibility of inlining a subprogram comprising assembler code
24956 @item Code optimizer can take Inline Assembler code into account
24957 @end itemize
24959 This chapter presents a series of examples to show you how to use
24960 the Inline Assembler.  Although it focuses on the Intel x86,
24961 the general approach applies also to other processors.
24962 It is assumed that you are familiar with Ada
24963 and with assembly language programming.
24965 @menu
24966 * Basic Assembler Syntax::
24967 * A Simple Example of Inline Assembler::
24968 * Output Variables in Inline Assembler::
24969 * Input Variables in Inline Assembler::
24970 * Inlining Inline Assembler Code::
24971 * Other Asm Functionality::
24972 @end menu
24974 @c ---------------------------------------------------------------------------
24975 @node Basic Assembler Syntax
24976 @section Basic Assembler Syntax
24978 @noindent
24979 The assembler used by GNAT and gcc is based not on the Intel assembly
24980 language, but rather on a language that descends from the AT&T Unix
24981 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24982 The following table summarizes the main features of @emph{as} syntax
24983 and points out the differences from the Intel conventions.
24984 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24985 pre-processor) documentation for further information.
24987 @table @asis
24988 @item Register names
24989 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24991 Intel: No extra punctuation; for example @code{eax}
24993 @item Immediate operand
24994 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24996 Intel: No extra punctuation; for example @code{4}
24998 @item Address
24999 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25001 Intel: No extra punctuation; for example @code{loc}
25003 @item Memory contents
25004 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25006 Intel: Square brackets; for example @code{[loc]}
25008 @item Register contents
25009 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25011 Intel: Square brackets; for example @code{[eax]}
25013 @item Hexadecimal numbers
25014 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25016 Intel: Trailing ``h''; for example @code{A0h}
25018 @item Operand size
25019 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25020 a 16-bit word
25022 Intel: Implicit, deduced by assembler; for example @code{mov}
25024 @item Instruction repetition
25025 gcc / @emph{as}: Split into two lines; for example
25027 @code{rep}
25029 @code{stosl}
25031 Intel: Keep on one line; for example @code{rep stosl}
25033 @item Order of operands
25034 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25036 Intel: Destination first; for example @code{mov eax, 4}
25037 @end table
25039 @c ---------------------------------------------------------------------------
25040 @node A Simple Example of Inline Assembler
25041 @section A Simple Example of Inline Assembler
25043 @noindent
25044 The following example will generate a single assembly language statement,
25045 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25046 the example will be useful in illustrating the basics of
25047 the Inline Assembler facility.
25049 @smallexample @c ada
25050 @group
25051 with System.Machine_Code; use System.Machine_Code;
25052 procedure Nothing is
25053 begin
25054    Asm ("nop");
25055 end Nothing;
25056 @end group
25057 @end smallexample
25059 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25060 here it takes one parameter, a @emph{template string} that must be a static
25061 expression and that will form the generated instruction.
25062 @code{Asm} may be regarded as a compile-time procedure that parses
25063 the template string and additional parameters (none here),
25064 from which it generates a sequence of assembly language instructions.
25066 The examples in this chapter will illustrate several of the forms
25067 for invoking @code{Asm}; a complete specification of the syntax
25068 is found in the @cite{GNAT Reference Manual}.
25070 Under the standard GNAT conventions, the @code{Nothing} procedure
25071 should be in a file named @file{nothing.adb}.
25072 You can build the executable in the usual way:
25073 @smallexample
25074 gnatmake nothing
25075 @end smallexample
25076 However, the interesting aspect of this example is not its run-time behavior
25077 but rather the generated assembly code.
25078 To see this output, invoke the compiler as follows:
25079 @smallexample
25080    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25081 @end smallexample
25082 where the options are:
25084 @table @code
25085 @item -c
25086 compile only (no bind or link)
25087 @item -S
25088 generate assembler listing
25089 @item -fomit-frame-pointer
25090 do not set up separate stack frames
25091 @item -gnatp
25092 do not add runtime checks
25093 @end table
25095 This gives a human-readable assembler version of the code. The resulting
25096 file will have the same name as the Ada source file, but with a @code{.s}
25097 extension. In our example, the file @file{nothing.s} has the following
25098 contents:
25100 @smallexample
25101 @group
25102 .file "nothing.adb"
25103 gcc2_compiled.:
25104 ___gnu_compiled_ada:
25105 .text
25106    .align 4
25107 .globl __ada_nothing
25108 __ada_nothing:
25109 #APP
25110    nop
25111 #NO_APP
25112    jmp L1
25113    .align 2,0x90
25115    ret
25116 @end group
25117 @end smallexample
25119 The assembly code you included is clearly indicated by
25120 the compiler, between the @code{#APP} and @code{#NO_APP}
25121 delimiters. The character before the 'APP' and 'NOAPP'
25122 can differ on different targets. For example, GNU/Linux uses '#APP' while
25123 on NT you will see '/APP'.
25125 If you make a mistake in your assembler code (such as using the
25126 wrong size modifier, or using a wrong operand for the instruction) GNAT
25127 will report this error in a temporary file, which will be deleted when
25128 the compilation is finished.  Generating an assembler file will help
25129 in such cases, since you can assemble this file separately using the
25130 @emph{as} assembler that comes with gcc.
25132 Assembling the file using the command
25134 @smallexample
25135 as @file{nothing.s}
25136 @end smallexample
25137 @noindent
25138 will give you error messages whose lines correspond to the assembler
25139 input file, so you can easily find and correct any mistakes you made.
25140 If there are no errors, @emph{as} will generate an object file
25141 @file{nothing.out}.
25143 @c ---------------------------------------------------------------------------
25144 @node Output Variables in Inline Assembler
25145 @section Output Variables in Inline Assembler
25147 @noindent
25148 The examples in this section, showing how to access the processor flags,
25149 illustrate how to specify the destination operands for assembly language
25150 statements.
25152 @smallexample @c ada
25153 @group
25154 with Interfaces; use Interfaces;
25155 with Ada.Text_IO; use Ada.Text_IO;
25156 with System.Machine_Code; use System.Machine_Code;
25157 procedure Get_Flags is
25158    Flags : Unsigned_32;
25159    use ASCII;
25160 begin
25161    Asm ("pushfl"          & LF & HT & -- push flags on stack
25162         "popl %%eax"      & LF & HT & -- load eax with flags
25163         "movl %%eax, %0",             -- store flags in variable
25164         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25165    Put_Line ("Flags register:" & Flags'Img);
25166 end Get_Flags;
25167 @end group
25168 @end smallexample
25170 In order to have a nicely aligned assembly listing, we have separated
25171 multiple assembler statements in the Asm template string with linefeed
25172 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25173 The resulting section of the assembly output file is:
25175 @smallexample
25176 @group
25177 #APP
25178    pushfl
25179    popl %eax
25180    movl %eax, -40(%ebp)
25181 #NO_APP
25182 @end group
25183 @end smallexample
25185 It would have been legal to write the Asm invocation as:
25187 @smallexample
25188 Asm ("pushfl popl %%eax movl %%eax, %0")
25189 @end smallexample
25191 but in the generated assembler file, this would come out as:
25193 @smallexample
25194 #APP
25195    pushfl popl %eax movl %eax, -40(%ebp)
25196 #NO_APP
25197 @end smallexample
25199 which is not so convenient for the human reader.
25201 We use Ada comments
25202 at the end of each line to explain what the assembler instructions
25203 actually do.  This is a useful convention.
25205 When writing Inline Assembler instructions, you need to precede each register
25206 and variable name with a percent sign.  Since the assembler already requires
25207 a percent sign at the beginning of a register name, you need two consecutive
25208 percent signs for such names in the Asm template string, thus @code{%%eax}.
25209 In the generated assembly code, one of the percent signs will be stripped off.
25211 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25212 variables: operands you later define using @code{Input} or @code{Output}
25213 parameters to @code{Asm}.
25214 An output variable is illustrated in
25215 the third statement in the Asm template string:
25216 @smallexample
25217 movl %%eax, %0
25218 @end smallexample
25219 The intent is to store the contents of the eax register in a variable that can
25220 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25221 necessarily work, since the compiler might optimize by using a register
25222 to hold Flags, and the expansion of the @code{movl} instruction would not be
25223 aware of this optimization.  The solution is not to store the result directly
25224 but rather to advise the compiler to choose the correct operand form;
25225 that is the purpose of the @code{%0} output variable.
25227 Information about the output variable is supplied in the @code{Outputs}
25228 parameter to @code{Asm}:
25229 @smallexample
25230 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25231 @end smallexample
25233 The output is defined by the @code{Asm_Output} attribute of the target type;
25234 the general format is
25235 @smallexample
25236 Type'Asm_Output (constraint_string, variable_name)
25237 @end smallexample
25239 The constraint string directs the compiler how
25240 to store/access the associated variable.  In the example
25241 @smallexample
25242 Unsigned_32'Asm_Output ("=m", Flags);
25243 @end smallexample
25244 the @code{"m"} (memory) constraint tells the compiler that the variable
25245 @code{Flags} should be stored in a memory variable, thus preventing
25246 the optimizer from keeping it in a register.  In contrast,
25247 @smallexample
25248 Unsigned_32'Asm_Output ("=r", Flags);
25249 @end smallexample
25250 uses the @code{"r"} (register) constraint, telling the compiler to
25251 store the variable in a register.
25253 If the constraint is preceded by the equal character (@strong{=}), it tells
25254 the compiler that the variable will be used to store data into it.
25256 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25257 allowing the optimizer to choose whatever it deems best.
25259 There are a fairly large number of constraints, but the ones that are
25260 most useful (for the Intel x86 processor) are the following:
25262 @table @code
25263 @item =
25264 output constraint
25265 @item g
25266 global (i.e. can be stored anywhere)
25267 @item m
25268 in memory
25269 @item I
25270 a constant
25271 @item a
25272 use eax
25273 @item b
25274 use ebx
25275 @item c
25276 use ecx
25277 @item d
25278 use edx
25279 @item S
25280 use esi
25281 @item D
25282 use edi
25283 @item r
25284 use one of eax, ebx, ecx or edx
25285 @item q
25286 use one of eax, ebx, ecx, edx, esi or edi
25287 @end table
25289 The full set of constraints is described in the gcc and @emph{as}
25290 documentation; note that it is possible to combine certain constraints
25291 in one constraint string.
25293 You specify the association of an output variable with an assembler operand
25294 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25295 integer.  Thus in
25296 @smallexample @c ada
25297 @group
25298 Asm ("pushfl"          & LF & HT & -- push flags on stack
25299      "popl %%eax"      & LF & HT & -- load eax with flags
25300      "movl %%eax, %0",             -- store flags in variable
25301      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25302 @end group
25303 @end smallexample
25304 @noindent
25305 @code{%0} will be replaced in the expanded code by the appropriate operand,
25306 whatever
25307 the compiler decided for the @code{Flags} variable.
25309 In general, you may have any number of output variables:
25310 @itemize @bullet
25311 @item
25312 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25313 @item
25314 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25315 of @code{Asm_Output} attributes
25316 @end itemize
25318 For example:
25319 @smallexample @c ada
25320 @group
25321 Asm ("movl %%eax, %0" & LF & HT &
25322      "movl %%ebx, %1" & LF & HT &
25323      "movl %%ecx, %2",
25324      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25325                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25326                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25327 @end group
25328 @end smallexample
25329 @noindent
25330 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25331 in the Ada program.
25333 As a variation on the @code{Get_Flags} example, we can use the constraints
25334 string to direct the compiler to store the eax register into the @code{Flags}
25335 variable, instead of including the store instruction explicitly in the
25336 @code{Asm} template string:
25338 @smallexample @c ada
25339 @group
25340 with Interfaces; use Interfaces;
25341 with Ada.Text_IO; use Ada.Text_IO;
25342 with System.Machine_Code; use System.Machine_Code;
25343 procedure Get_Flags_2 is
25344    Flags : Unsigned_32;
25345    use ASCII;
25346 begin
25347    Asm ("pushfl"      & LF & HT & -- push flags on stack
25348         "popl %%eax",             -- save flags in eax
25349         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25350    Put_Line ("Flags register:" & Flags'Img);
25351 end Get_Flags_2;
25352 @end group
25353 @end smallexample
25355 @noindent
25356 The @code{"a"} constraint tells the compiler that the @code{Flags}
25357 variable will come from the eax register. Here is the resulting code:
25359 @smallexample
25360 @group
25361 #APP
25362    pushfl
25363    popl %eax
25364 #NO_APP
25365    movl %eax,-40(%ebp)
25366 @end group
25367 @end smallexample
25369 @noindent
25370 The compiler generated the store of eax into Flags after
25371 expanding the assembler code.
25373 Actually, there was no need to pop the flags into the eax register;
25374 more simply, we could just pop the flags directly into the program variable:
25376 @smallexample @c ada
25377 @group
25378 with Interfaces; use Interfaces;
25379 with Ada.Text_IO; use Ada.Text_IO;
25380 with System.Machine_Code; use System.Machine_Code;
25381 procedure Get_Flags_3 is
25382    Flags : Unsigned_32;
25383    use ASCII;
25384 begin
25385    Asm ("pushfl"  & LF & HT & -- push flags on stack
25386         "pop %0",             -- save flags in Flags
25387         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25388    Put_Line ("Flags register:" & Flags'Img);
25389 end Get_Flags_3;
25390 @end group
25391 @end smallexample
25393 @c ---------------------------------------------------------------------------
25394 @node Input Variables in Inline Assembler
25395 @section Input Variables in Inline Assembler
25397 @noindent
25398 The example in this section illustrates how to specify the source operands
25399 for assembly language statements.
25400 The program simply increments its input value by 1:
25402 @smallexample @c ada
25403 @group
25404 with Interfaces; use Interfaces;
25405 with Ada.Text_IO; use Ada.Text_IO;
25406 with System.Machine_Code; use System.Machine_Code;
25407 procedure Increment is
25409    function Incr (Value : Unsigned_32) return Unsigned_32 is
25410       Result : Unsigned_32;
25411    begin
25412       Asm ("incl %0",
25413            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25414            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25415       return Result;
25416    end Incr;
25418    Value : Unsigned_32;
25420 begin
25421    Value := 5;
25422    Put_Line ("Value before is" & Value'Img);
25423    Value := Incr (Value);
25424    Put_Line ("Value after is" & Value'Img);
25425 end Increment;
25426 @end group
25427 @end smallexample
25429 The @code{Outputs} parameter to @code{Asm} specifies
25430 that the result will be in the eax register and that it is to be stored
25431 in the @code{Result} variable.
25433 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25434 but with an @code{Asm_Input} attribute.
25435 The @code{"="} constraint, indicating an output value, is not present.
25437 You can have multiple input variables, in the same way that you can have more
25438 than one output variable.
25440 The parameter count (%0, %1) etc, now starts at the first input
25441 statement, and continues with the output statements.
25442 When both parameters use the same variable, the
25443 compiler will treat them as the same %n operand, which is the case here.
25445 Just as the @code{Outputs} parameter causes the register to be stored into the
25446 target variable after execution of the assembler statements, so does the
25447 @code{Inputs} parameter cause its variable to be loaded into the register
25448 before execution of the assembler statements.
25450 Thus the effect of the @code{Asm} invocation is:
25451 @enumerate
25452 @item load the 32-bit value of @code{Value} into eax
25453 @item execute the @code{incl %eax} instruction
25454 @item store the contents of eax into the @code{Result} variable
25455 @end enumerate
25457 The resulting assembler file (with @option{-O2} optimization) contains:
25458 @smallexample
25459 @group
25460 _increment__incr.1:
25461    subl $4,%esp
25462    movl 8(%esp),%eax
25463 #APP
25464    incl %eax
25465 #NO_APP
25466    movl %eax,%edx
25467    movl %ecx,(%esp)
25468    addl $4,%esp
25469    ret
25470 @end group
25471 @end smallexample
25473 @c ---------------------------------------------------------------------------
25474 @node Inlining Inline Assembler Code
25475 @section Inlining Inline Assembler Code
25477 @noindent
25478 For a short subprogram such as the @code{Incr} function in the previous
25479 section, the overhead of the call and return (creating / deleting the stack
25480 frame) can be significant, compared to the amount of code in the subprogram
25481 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25482 which directs the compiler to expand invocations of the subprogram at the
25483 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25484 Here is the resulting program:
25486 @smallexample @c ada
25487 @group
25488 with Interfaces; use Interfaces;
25489 with Ada.Text_IO; use Ada.Text_IO;
25490 with System.Machine_Code; use System.Machine_Code;
25491 procedure Increment_2 is
25493    function Incr (Value : Unsigned_32) return Unsigned_32 is
25494       Result : Unsigned_32;
25495    begin
25496       Asm ("incl %0",
25497            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25498            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25499       return Result;
25500    end Incr;
25501    pragma Inline (Increment);
25503    Value : Unsigned_32;
25505 begin
25506    Value := 5;
25507    Put_Line ("Value before is" & Value'Img);
25508    Value := Increment (Value);
25509    Put_Line ("Value after is" & Value'Img);
25510 end Increment_2;
25511 @end group
25512 @end smallexample
25514 Compile the program with both optimization (@option{-O2}) and inlining
25515 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25517 The @code{Incr} function is still compiled as usual, but at the
25518 point in @code{Increment} where our function used to be called:
25520 @smallexample
25521 @group
25522 pushl %edi
25523 call _increment__incr.1
25524 @end group
25525 @end smallexample
25527 @noindent
25528 the code for the function body directly appears:
25530 @smallexample
25531 @group
25532 movl %esi,%eax
25533 #APP
25534    incl %eax
25535 #NO_APP
25536    movl %eax,%edx
25537 @end group
25538 @end smallexample
25540 @noindent
25541 thus saving the overhead of stack frame setup and an out-of-line call.
25543 @c ---------------------------------------------------------------------------
25544 @node Other Asm Functionality
25545 @section Other @code{Asm} Functionality
25547 @noindent
25548 This section describes two important parameters to the @code{Asm}
25549 procedure: @code{Clobber}, which identifies register usage;
25550 and @code{Volatile}, which inhibits unwanted optimizations.
25552 @menu
25553 * The Clobber Parameter::
25554 * The Volatile Parameter::
25555 @end menu
25557 @c ---------------------------------------------------------------------------
25558 @node The Clobber Parameter
25559 @subsection The @code{Clobber} Parameter
25561 @noindent
25562 One of the dangers of intermixing assembly language and a compiled language
25563 such as Ada is that the compiler needs to be aware of which registers are
25564 being used by the assembly code.  In some cases, such as the earlier examples,
25565 the constraint string is sufficient to indicate register usage (e.g.,
25566 @code{"a"} for
25567 the eax register).  But more generally, the compiler needs an explicit
25568 identification of the registers that are used by the Inline Assembly
25569 statements.
25571 Using a register that the compiler doesn't know about
25572 could be a side effect of an instruction (like @code{mull}
25573 storing its result in both eax and edx).
25574 It can also arise from explicit register usage in your
25575 assembly code; for example:
25576 @smallexample
25577 @group
25578 Asm ("movl %0, %%ebx" & LF & HT &
25579      "movl %%ebx, %1",
25580      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25581      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25582 @end group
25583 @end smallexample
25584 @noindent
25585 where the compiler (since it does not analyze the @code{Asm} template string)
25586 does not know you are using the ebx register.
25588 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25589 to identify the registers that will be used by your assembly code:
25591 @smallexample
25592 @group
25593 Asm ("movl %0, %%ebx" & LF & HT &
25594      "movl %%ebx, %1",
25595      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25596      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25597      Clobber => "ebx");
25598 @end group
25599 @end smallexample
25601 The Clobber parameter is a static string expression specifying the
25602 register(s) you are using.  Note that register names are @emph{not} prefixed
25603 by a percent sign. Also, if more than one register is used then their names
25604 are separated by commas; e.g., @code{"eax, ebx"}
25606 The @code{Clobber} parameter has several additional uses:
25607 @enumerate
25608 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25609 @item Use ``register'' name @code{memory} if you changed a memory location
25610 @end enumerate
25612 @c ---------------------------------------------------------------------------
25613 @node The Volatile Parameter
25614 @subsection The @code{Volatile} Parameter
25615 @cindex Volatile parameter
25617 @noindent
25618 Compiler optimizations in the presence of Inline Assembler may sometimes have
25619 unwanted effects.  For example, when an @code{Asm} invocation with an input
25620 variable is inside a loop, the compiler might move the loading of the input
25621 variable outside the loop, regarding it as a one-time initialization.
25623 If this effect is not desired, you can disable such optimizations by setting
25624 the @code{Volatile} parameter to @code{True}; for example:
25626 @smallexample @c ada
25627 @group
25628 Asm ("movl %0, %%ebx" & LF & HT &
25629      "movl %%ebx, %1",
25630      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25631      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25632      Clobber  => "ebx",
25633      Volatile => True);
25634 @end group
25635 @end smallexample
25637 By default, @code{Volatile} is set to @code{False} unless there is no
25638 @code{Outputs} parameter.
25640 Although setting @code{Volatile} to @code{True} prevents unwanted
25641 optimizations, it will also disable other optimizations that might be
25642 important for efficiency. In general, you should set @code{Volatile}
25643 to @code{True} only if the compiler's optimizations have created
25644 problems.
25645 @c END OF INLINE ASSEMBLER CHAPTER
25646 @c ===============================
25648 @c ***********************************
25649 @c * Compatibility and Porting Guide *
25650 @c ***********************************
25651 @node Compatibility and Porting Guide
25652 @appendix Compatibility and Porting Guide
25654 @noindent
25655 This chapter describes the compatibility issues that may arise between
25656 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25657 can expedite porting
25658 applications developed in other Ada environments.
25660 @menu
25661 * Compatibility with Ada 83::
25662 * Implementation-dependent characteristics::
25663 * Compatibility with Other Ada 95 Systems::
25664 * Representation Clauses::
25665 * Compatibility with HP Ada 83::
25666 @ifset vms
25667 * Transitioning from Alpha to Integrity OpenVMS::
25668 @end ifset
25669 @end menu
25671 @node Compatibility with Ada 83
25672 @section Compatibility with Ada 83
25673 @cindex Compatibility (between Ada 83 and Ada 95)
25675 @noindent
25676 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25677 particular, the design intention is that the difficulties associated
25678 with moving from Ada 83 to Ada 95 should be no greater than those
25679 that occur when moving from one Ada 83 system to another.
25681 However, there are a number of points at which there are minor
25682 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25683 full details of these issues,
25684 and should be consulted for a complete treatment.
25685 In practice the
25686 following subsections treat the most likely issues to be encountered.
25688 @menu
25689 * Legal Ada 83 programs that are illegal in Ada 95::
25690 * More deterministic semantics::
25691 * Changed semantics::
25692 * Other language compatibility issues::
25693 @end menu
25695 @node Legal Ada 83 programs that are illegal in Ada 95
25696 @subsection Legal Ada 83 programs that are illegal in Ada 95
25698 @table @asis
25699 @item Character literals
25700 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25701 @code{Wide_Character} as a new predefined character type, some uses of
25702 character literals that were legal in Ada 83 are illegal in Ada 95.
25703 For example:
25704 @smallexample @c ada
25705    for Char in 'A' .. 'Z' loop ... end loop;
25706 @end smallexample
25707 @noindent
25708 The problem is that @code{'A'} and @code{'Z'} could be from either
25709 @code{Character} or @code{Wide_Character}.  The simplest correction
25710 is to make the type explicit; e.g.:
25711 @smallexample @c ada
25712    for Char in Character range 'A' .. 'Z' loop ... end loop;
25713 @end smallexample
25715 @item New reserved words
25716 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25717 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25718 Existing Ada 83 code using any of these identifiers must be edited to
25719 use some alternative name.
25721 @item Freezing rules
25722 The rules in Ada 95 are slightly different with regard to the point at
25723 which entities are frozen, and representation pragmas and clauses are
25724 not permitted past the freeze point.  This shows up most typically in
25725 the form of an error message complaining that a representation item
25726 appears too late, and the appropriate corrective action is to move
25727 the item nearer to the declaration of the entity to which it refers.
25729 A particular case is that representation pragmas
25730 @ifset vms
25731 (including the
25732 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25733 @end ifset
25734 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25735 declaration must be introduced to which the pragma can be applied.
25737 @item Optional bodies for library packages
25738 In Ada 83, a package that did not require a package body was nevertheless
25739 allowed to have one.  This lead to certain surprises in compiling large
25740 systems (situations in which the body could be unexpectedly ignored by the
25741 binder).  In Ada 95, if a package does not require a body then it is not
25742 permitted to have a body.  To fix this problem, simply remove a redundant
25743 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25744 into the spec that makes the body required.  One approach is to add a private
25745 part to the package declaration (if necessary), and define a parameterless
25746 procedure called @code{Requires_Body}, which must then be given a dummy
25747 procedure body in the package body, which then becomes required.
25748 Another approach (assuming that this does not introduce elaboration
25749 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25750 since one effect of this pragma is to require the presence of a package body.
25752 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25753 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25754 @code{Constraint_Error}.
25755 This means that it is illegal to have separate exception handlers for
25756 the two exceptions.  The fix is simply to remove the handler for the
25757 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25758 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25760 @item Indefinite subtypes in generics
25761 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25762 as the actual for a generic formal private type, but then the instantiation
25763 would be illegal if there were any instances of declarations of variables
25764 of this type in the generic body.  In Ada 95, to avoid this clear violation
25765 of the methodological principle known as the ``contract model'',
25766 the generic declaration explicitly indicates whether
25767 or not such instantiations are permitted.  If a generic formal parameter
25768 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25769 type name, then it can be instantiated with indefinite types, but no
25770 stand-alone variables can be declared of this type.  Any attempt to declare
25771 such a variable will result in an illegality at the time the generic is
25772 declared.  If the @code{(<>)} notation is not used, then it is illegal
25773 to instantiate the generic with an indefinite type.
25774 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25775 It will show up as a compile time error, and
25776 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25777 @end table
25779 @node More deterministic semantics
25780 @subsection More deterministic semantics
25782 @table @asis
25783 @item Conversions
25784 Conversions from real types to integer types round away from 0.  In Ada 83
25785 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25786 implementation freedom was intended to support unbiased rounding in
25787 statistical applications, but in practice it interfered with portability.
25788 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25789 is required.  Numeric code may be affected by this change in semantics.
25790 Note, though, that this issue is no worse than already existed in Ada 83
25791 when porting code from one vendor to another.
25793 @item Tasking
25794 The Real-Time Annex introduces a set of policies that define the behavior of
25795 features that were implementation dependent in Ada 83, such as the order in
25796 which open select branches are executed.
25797 @end table
25799 @node Changed semantics
25800 @subsection Changed semantics
25802 @noindent
25803 The worst kind of incompatibility is one where a program that is legal in
25804 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25805 possible in Ada 83.  Fortunately this is extremely rare, but the one
25806 situation that you should be alert to is the change in the predefined type
25807 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25809 @table @asis
25810 @item range of @code{Character}
25811 The range of @code{Standard.Character} is now the full 256 characters
25812 of Latin-1, whereas in most Ada 83 implementations it was restricted
25813 to 128 characters. Although some of the effects of
25814 this change will be manifest in compile-time rejection of legal
25815 Ada 83 programs it is possible for a working Ada 83 program to have
25816 a different effect in Ada 95, one that was not permitted in Ada 83.
25817 As an example, the expression
25818 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25819 delivers @code{255} as its value.
25820 In general, you should look at the logic of any
25821 character-processing Ada 83 program and see whether it needs to be adapted
25822 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25823 character handling package that may be relevant if code needs to be adapted
25824 to account for the additional Latin-1 elements.
25825 The desirable fix is to
25826 modify the program to accommodate the full character set, but in some cases
25827 it may be convenient to define a subtype or derived type of Character that
25828 covers only the restricted range.
25829 @cindex Latin-1
25830 @end table
25832 @node Other language compatibility issues
25833 @subsection Other language compatibility issues
25834 @table @asis
25835 @item @option{-gnat83 switch}
25836 All implementations of GNAT provide a switch that causes GNAT to operate
25837 in Ada 83 mode.  In this mode, some but not all compatibility problems
25838 of the type described above are handled automatically.  For example, the
25839 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25840 However,
25841 in practice, it is usually advisable to make the necessary modifications
25842 to the program to remove the need for using this switch.
25843 See @ref{Compiling Different Versions of Ada}.
25845 @item Support for removed Ada 83 pragmas and attributes
25846 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25847 generally because they have been replaced by other mechanisms.  Ada 95
25848 compilers are allowed, but not required, to implement these missing
25849 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25850 such pragmas and attributes, eliminating this compatibility concern.  These
25851 include @code{pragma Interface} and the floating point type attributes
25852 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25853 @end table
25855 @node Implementation-dependent characteristics
25856 @section Implementation-dependent characteristics
25857 @noindent
25858 Although the Ada language defines the semantics of each construct as
25859 precisely as practical, in some situations (for example for reasons of
25860 efficiency, or where the effect is heavily dependent on the host or target
25861 platform) the implementation is allowed some freedom.  In porting Ada 83
25862 code to GNAT, you need to be aware of whether / how the existing code
25863 exercised such implementation dependencies.  Such characteristics fall into
25864 several categories, and GNAT offers specific support in assisting the
25865 transition from certain Ada 83 compilers.
25867 @menu
25868 * Implementation-defined pragmas::
25869 * Implementation-defined attributes::
25870 * Libraries::
25871 * Elaboration order::
25872 * Target-specific aspects::
25873 @end menu
25875 @node Implementation-defined pragmas
25876 @subsection Implementation-defined pragmas
25878 @noindent
25879 Ada compilers are allowed to supplement the language-defined pragmas, and
25880 these are a potential source of non-portability.  All GNAT-defined pragmas
25881 are described in the GNAT Reference Manual, and these include several that
25882 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25883 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25885 compatibility with HP Ada 83, GNAT supplies the pragmas
25886 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25887 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25888 and @code{Volatile}.
25889 Other relevant pragmas include @code{External} and @code{Link_With}.
25890 Some vendor-specific
25891 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25892 recognized, thus
25893 avoiding compiler rejection of units that contain such pragmas; they are not
25894 relevant in a GNAT context and hence are not otherwise implemented.
25896 @node Implementation-defined attributes
25897 @subsection Implementation-defined attributes
25899 Analogous to pragmas, the set of attributes may be extended by an
25900 implementation.  All GNAT-defined attributes are described in the
25901 @cite{GNAT Reference Manual}, and these include several that are specifically
25902 intended
25903 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25904 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
25905 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25906 @code{Type_Class}.
25908 @node Libraries
25909 @subsection Libraries
25910 @noindent
25911 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25912 code uses vendor-specific libraries then there are several ways to manage
25913 this in Ada 95:
25914 @enumerate
25915 @item
25916 If the source code for the libraries (specifications and bodies) are
25917 available, then the libraries can be migrated in the same way as the
25918 application.
25919 @item
25920 If the source code for the specifications but not the bodies are
25921 available, then you can reimplement the bodies.
25922 @item
25923 Some new Ada 95 features obviate the need for library support.  For
25924 example most Ada 83 vendors supplied a package for unsigned integers.  The
25925 Ada 95 modular type feature is the preferred way to handle this need, so
25926 instead of migrating or reimplementing the unsigned integer package it may
25927 be preferable to retrofit the application using modular types.
25928 @end enumerate
25930 @node Elaboration order
25931 @subsection Elaboration order
25932 @noindent
25933 The implementation can choose any elaboration order consistent with the unit
25934 dependency relationship.  This freedom means that some orders can result in
25935 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25936 to invoke a subprogram its body has been elaborated, or to instantiate a
25937 generic before the generic body has been elaborated.  By default GNAT
25938 attempts to choose a safe order (one that will not encounter access before
25939 elaboration problems) by implicitly inserting @code{Elaborate} or
25940 @code{Elaborate_All} pragmas where
25941 needed.  However, this can lead to the creation of elaboration circularities
25942 and a resulting rejection of the program by gnatbind.  This issue is
25943 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25944 In brief, there are several
25945 ways to deal with this situation:
25947 @itemize @bullet
25948 @item
25949 Modify the program to eliminate the circularities, e.g. by moving
25950 elaboration-time code into explicitly-invoked procedures
25951 @item
25952 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25953 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25954 @code{Elaborate_All}
25955 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25956 (by selectively suppressing elaboration checks via pragma
25957 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25958 @end itemize
25960 @node Target-specific aspects
25961 @subsection Target-specific aspects
25962 @noindent
25963 Low-level applications need to deal with machine addresses, data
25964 representations, interfacing with assembler code, and similar issues.  If
25965 such an Ada 83 application is being ported to different target hardware (for
25966 example where the byte endianness has changed) then you will need to
25967 carefully examine the program logic; the porting effort will heavily depend
25968 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25969 incompatible with typical Ada 83 compiler practices regarding implicit
25970 packing, the meaning of the Size attribute, and the size of access values.
25971 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25973 @node Compatibility with Other Ada 95 Systems
25974 @section Compatibility with Other Ada 95 Systems
25976 @noindent
25977 Providing that programs avoid the use of implementation dependent and
25978 implementation defined features of Ada 95, as documented in the Ada 95
25979 reference manual, there should be a high degree of portability between
25980 GNAT and other Ada 95 systems.  The following are specific items which
25981 have proved troublesome in moving GNAT programs to other Ada 95
25982 compilers, but do not affect porting code to GNAT@.
25984 @table @asis
25985 @item Ada 83 Pragmas and Attributes
25986 Ada 95 compilers are allowed, but not required, to implement the missing
25987 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25988 GNAT implements all such pragmas and attributes, eliminating this as
25989 a compatibility concern, but some other Ada 95 compilers reject these
25990 pragmas and attributes.
25992 @item Special-needs Annexes
25993 GNAT implements the full set of special needs annexes.  At the
25994 current time, it is the only Ada 95 compiler to do so.  This means that
25995 programs making use of these features may not be portable to other Ada
25996 95 compilation systems.
25998 @item Representation Clauses
25999 Some other Ada 95 compilers implement only the minimal set of
26000 representation clauses required by the Ada 95 reference manual.  GNAT goes
26001 far beyond this minimal set, as described in the next section.
26002 @end table
26004 @node Representation Clauses
26005 @section Representation Clauses
26007 @noindent
26008 The Ada 83 reference manual was quite vague in describing both the minimal
26009 required implementation of representation clauses, and also their precise
26010 effects.  The Ada 95 reference manual is much more explicit, but the minimal
26011 set of capabilities required in Ada 95 is quite limited.
26013 GNAT implements the full required set of capabilities described in the
26014 Ada 95 reference manual, but also goes much beyond this, and in particular
26015 an effort has been made to be compatible with existing Ada 83 usage to the
26016 greatest extent possible.
26018 A few cases exist in which Ada 83 compiler behavior is incompatible with
26019 requirements in the Ada 95 reference manual.  These are instances of
26020 intentional or accidental dependence on specific implementation dependent
26021 characteristics of these Ada 83 compilers.  The following is a list of
26022 the cases most likely to arise in existing legacy Ada 83 code.
26024 @table @asis
26025 @item Implicit Packing
26026 Some Ada 83 compilers allowed a Size specification to cause implicit
26027 packing of an array or record.  This could cause expensive implicit
26028 conversions for change of representation in the presence of derived
26029 types, and the Ada design intends to avoid this possibility.
26030 Subsequent AI's were issued to make it clear that such implicit
26031 change of representation in response to a Size clause is inadvisable,
26032 and this recommendation is represented explicitly in the Ada 95 RM
26033 as implementation advice that is followed by GNAT@.
26034 The problem will show up as an error
26035 message rejecting the size clause.  The fix is simply to provide
26036 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26037 a Component_Size clause.
26039 @item Meaning of Size Attribute
26040 The Size attribute in Ada 95 for discrete types is defined as being the
26041 minimal number of bits required to hold values of the type.  For example,
26042 on a 32-bit machine, the size of Natural will typically be 31 and not
26043 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26044 some 32 in this situation.  This problem will usually show up as a compile
26045 time error, but not always.  It is a good idea to check all uses of the
26046 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26047 Object_Size can provide a useful way of duplicating the behavior of
26048 some Ada 83 compiler systems.
26050 @item Size of Access Types
26051 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26052 and that therefore it will be the same size as a System.Address value.  This
26053 assumption is true for GNAT in most cases with one exception.  For the case of
26054 a pointer to an unconstrained array type (where the bounds may vary from one
26055 value of the access type to another), the default is to use a ``fat pointer'',
26056 which is represented as two separate pointers, one to the bounds, and one to
26057 the array.  This representation has a number of advantages, including improved
26058 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26059 code which makes the assumption that, for example, pointers fit in 32 bits on
26060 a machine with 32-bit addressing.
26062 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26063 access types in this case (where the designated type is an unconstrained array
26064 type).  These thin pointers are indeed the same size as a System.Address value.
26065 To specify a thin pointer, use a size clause for the type, for example:
26067 @smallexample @c ada
26068 type X is access all String;
26069 for X'Size use Standard'Address_Size;
26070 @end smallexample
26072 @noindent
26073 which will cause the type X to be represented using a single pointer.
26074 When using this representation, the bounds are right behind the array.
26075 This representation is slightly less efficient, and does not allow quite
26076 such flexibility in the use of foreign pointers or in using the
26077 Unrestricted_Access attribute to create pointers to non-aliased objects.
26078 But for any standard portable use of the access type it will work in
26079 a functionally correct manner and allow porting of existing code.
26080 Note that another way of forcing a thin pointer representation
26081 is to use a component size clause for the element size in an array,
26082 or a record representation clause for an access field in a record.
26083 @end table
26085 @node Compatibility with HP Ada 83
26086 @section Compatibility with HP Ada 83
26088 @noindent
26089 The VMS version of GNAT fully implements all the pragmas and attributes
26090 provided by HP Ada 83, as well as providing the standard HP Ada 83
26091 libraries, including Starlet.  In addition, data layouts and parameter
26092 passing conventions are highly compatible.  This means that porting
26093 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26094 most other porting efforts.  The following are some of the most
26095 significant differences between GNAT and HP Ada 83.
26097 @table @asis
26098 @item Default floating-point representation
26099 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26100 it is VMS format.  GNAT does implement the necessary pragmas
26101 (Long_Float, Float_Representation) for changing this default.
26103 @item System
26104 The package System in GNAT exactly corresponds to the definition in the
26105 Ada 95 reference manual, which means that it excludes many of the
26106 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26107 that contains the additional definitions, and a special pragma,
26108 Extend_System allows this package to be treated transparently as an
26109 extension of package System.
26111 @item To_Address
26112 The definitions provided by Aux_DEC are exactly compatible with those
26113 in the HP Ada 83 version of System, with one exception.
26114 HP Ada provides the following declarations:
26116 @smallexample @c ada
26117 TO_ADDRESS (INTEGER)
26118 TO_ADDRESS (UNSIGNED_LONGWORD)
26119 TO_ADDRESS (universal_integer)
26120 @end smallexample
26122 @noindent
26123 The version of TO_ADDRESS taking a universal integer argument is in fact
26124 an extension to Ada 83 not strictly compatible with the reference manual.
26125 In GNAT, we are constrained to be exactly compatible with the standard,
26126 and this means we cannot provide this capability.  In HP Ada 83, the
26127 point of this definition is to deal with a call like:
26129 @smallexample @c ada
26130 TO_ADDRESS (16#12777#);
26131 @end smallexample
26133 @noindent
26134 Normally, according to the Ada 83 standard, one would expect this to be
26135 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26136 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26137 definition using universal_integer takes precedence.
26139 In GNAT, since the version with universal_integer cannot be supplied, it is
26140 not possible to be 100% compatible.  Since there are many programs using
26141 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26142 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26143 declarations provided in the GNAT version of AUX_Dec are:
26145 @smallexample @c ada
26146 function To_Address (X : Integer) return Address;
26147 pragma Pure_Function (To_Address);
26149 function To_Address_Long (X : Unsigned_Longword)
26150  return Address;
26151 pragma Pure_Function (To_Address_Long);
26152 @end smallexample
26154 @noindent
26155 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26156 change the name to TO_ADDRESS_LONG@.
26158 @item Task_Id values
26159 The Task_Id values assigned will be different in the two systems, and GNAT
26160 does not provide a specified value for the Task_Id of the environment task,
26161 which in GNAT is treated like any other declared task.
26162 @end table
26164 For full details on these and other less significant compatibility issues,
26165 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26166 Overview and Comparison on HP Platforms}.
26168 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26169 attributes are recognized, although only a subset of them can sensibly
26170 be implemented.  The description of pragmas in this reference manual
26171 indicates whether or not they are applicable to non-VMS systems.
26174 @ifset vms
26175 @node Transitioning from Alpha to Integrity OpenVMS
26176 @section Transitioning from Alpha to Integrity OpenVMS
26178 @menu
26179 * Introduction to transitioning::
26180 * Migration of 32 bit code::
26181 * Taking advantage of 64 bit addressing::
26182 * Technical details::
26183 @end menu
26185 @node Introduction to transitioning
26186 @subsection Introduction to transitioning
26188 @noindent
26189 This guide is meant to assist users of GNAT Pro
26190 for Alpha OpenVMS who are planning to transition to the IA64 architecture.
26191 GNAT Pro for Open VMS Integrity has been designed to meet
26192 three main goals:
26194 @enumerate
26195 @item
26196 Providing a full conforming implementation of the Ada 95 language
26198 @item
26199 Allowing maximum backward compatibility, thus easing migration of existing
26200 Ada source code
26202 @item
26203 Supplying a path for exploiting the full IA64 address range
26204 @end enumerate
26206 @noindent
26207 Ada's strong typing semantics has made it
26208 impractical to have different 32-bit and 64-bit modes. As soon as
26209 one object could possibly be outside the 32-bit address space, this
26210 would make it necessary for the @code{System.Address} type to be 64 bits.
26211 In particular, this would cause inconsistencies if 32-bit code is
26212 called from 64-bit code that raises an exception.
26214 This issue has been resolved by always using 64-bit addressing
26215 at the system level, but allowing for automatic conversions between
26216 32-bit and 64-bit addresses where required. Thus users who
26217 do not currently require 64-bit addressing capabilities, can
26218 recompile their code with only minimal changes (and indeed
26219 if the code is written in portable Ada, with no assumptions about
26220 the size of the @code{Address} type, then no changes at all are necessary).
26221 At the same time,
26222 this approach provides a simple, gradual upgrade path to future
26223 use of larger memories than available for 32-bit systems.
26224 Also, newly written applications or libraries will by default
26225 be fully compatible with future systems exploiting 64-bit
26226 addressing capabilities present in IA64.
26228 @ref{Migration of 32 bit code}, will focus on porting applications
26229 that do not require more than 2 GB of
26230 addressable memory. This code will be referred to as
26231 @emph{32-bit code}.
26232 For applications intending to exploit the full ia64 address space,
26233 @ref{Taking advantage of 64 bit addressing},
26234 will consider further changes that may be required.
26235 Such code is called @emph{64-bit code} in the
26236 remainder of this guide.
26239 @node Migration of 32 bit code
26240 @subsection Migration of 32-bit code
26242 @menu
26243 * Address types::
26244 * Access types::
26245 * Unchecked conversions::
26246 * Predefined constants::
26247 * Single source compatibility::
26248 * Experience with source compatibility::
26249 @end menu
26251 @node Address types
26252 @subsubsection Address types
26254 @noindent
26255 To solve the problem of mixing 64-bit and 32-bit addressing,
26256 while maintaining maximum backward compatibility, the following
26257 approach has been taken:
26259 @itemize @bullet
26260 @item
26261 @code{System.Address} always has a size of 64 bits
26263 @item
26264 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26265 @end itemize
26268 @noindent
26269 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26270 a @code{Short_Address}
26271 may be used where an @code{Address} is required, and vice versa, without
26272 needing explicit type conversions.
26273 By virtue of the Open VMS Integrity parameter passing conventions,
26274 even imported
26275 and exported subprograms that have 32-bit address parameters are
26276 compatible with those that have 64-bit address parameters.
26277 (See @ref{Making code 64 bit clean} for details.)
26279 The areas that may need attention are those where record types have
26280 been defined that contain components of the type @code{System.Address}, and
26281 where objects of this type are passed to code expecting a record layout with
26282 32-bit addresses.
26284 Different compilers on different platforms cannot be
26285 expected to represent the same type in the same way,
26286 since alignment constraints
26287 and other system-dependent properties affect the compiler's decision.
26288 For that reason, Ada code
26289 generally uses representation clauses to specify the expected
26290 layout where required.
26292 If such a representation clause uses 32 bits for a component having
26293 the type @code{System.Address}, GNAT Pro for OpenVMS Integrity will detect
26294 that error and produce a specific diagnostic message.
26295 The developer should then determine whether the representation
26296 should be 64 bits or not and make either of two changes:
26297 change the size to 64 bits and leave the type as @code{System.Address}, or
26298 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26299 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26300 required in any code setting or accessing the field; the compiler will
26301 automatically perform any needed conversions between address
26302 formats.
26304 @node Access types
26305 @subsubsection Access types
26307 @noindent
26308 By default, objects designated by access values are always
26309 allocated in the 32-bit
26310 address space. Thus legacy code will never contain
26311 any objects that are not addressable with 32-bit addresses, and
26312 the compiler will never raise exceptions as result of mixing
26313 32-bit and 64-bit addresses.
26315 However, the access values themselves are represented in 64 bits, for optimum
26316 performance and future compatibility with 64-bit code. As was
26317 the case with @code{System.Address}, the compiler will give an error message
26318 if an object or record component has a representation clause that
26319 requires the access value to fit in 32 bits. In such a situation,
26320 an explicit size clause for the access type, specifying 32 bits,
26321 will have the desired effect.
26323 General access types (declared with @code{access all}) can never be
26324 32 bits, as values of such types must be able to refer to any object
26325 of the  designated type,
26326 including objects residing outside the 32-bit address range.
26327 Existing Ada 83 code will not contain such type definitions,
26328 however, since general access types were introduced in Ada 95.
26330 @node Unchecked conversions
26331 @subsubsection Unchecked conversions
26333 @noindent
26334 In the case of an @code{Unchecked_Conversion} where the source type is a
26335 64-bit access type or the type @code{System.Address}, and the target
26336 type is a 32-bit type, the compiler will generate a warning.
26337 Even though the generated code will still perform the required
26338 conversions, it is highly recommended in these cases to use
26339 respectively a 32-bit access type or @code{System.Short_Address}
26340 as the source type.
26342 @node Predefined constants
26343 @subsubsection Predefined constants
26345 @noindent
26346 The following predefined constants have changed:
26348 @multitable {@code{System.Address_Size}} {2**32} {2**64}
26349 @item   @b{Constant}               @tab @b{Old} @tab @b{New}
26350 @item   @code{System.Word_Size}    @tab 32      @tab 64
26351 @item   @code{System.Memory_Size}  @tab 2**32   @tab 2**64
26352 @item   @code{System.Address_Size} @tab 32      @tab 64
26353 @end multitable
26355 @noindent
26356 If you need to refer to the specific
26357 memory size of a 32-bit implementation, instead of the
26358 actual memory size, use @code{System.Short_Memory_Size}
26359 rather than @code{System.Memory_Size}.
26360 Similarly, references to @code{System.Address_Size} may need
26361 to be replaced by @code{System.Short_Address'Size}.
26362 The program @command{gnatfind} may be useful for locating
26363 references to the above constants, so that you can verify that they
26364 are still correct.
26366 @node Single source compatibility
26367 @subsubsection Single source compatibility
26369 @noindent
26370 In order to allow the same source code to be compiled on
26371 both Alpha and IA64 platforms, GNAT Pro for Alpha/OpenVMS
26372 defines @code{System.Short_Address} and System.Short_Memory_Size
26373 as aliases of respectively @code{System.Address} and
26374 @code{System.Memory_Size}.
26375 (These aliases also leave the door open for a possible
26376 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26378 @node Experience with source compatibility
26379 @subsubsection Experience with source compatibility
26381 @noindent
26382 The Security Server and STARLET provide an interesting ``test case''
26383 for source compatibility issues, since it is in such system code
26384 where assumptions about @code{Address} size might be expected to occur.
26385 Indeed, there were a small number of occasions in the Security Server
26386 file @file{jibdef.ads}
26387 where a representation clause for a record type specified
26388 32 bits for a component of type @code{Address}.
26389 All of these errors were detected by the compiler.
26390 The repair was obvious and immediate; to simply replace @code{Address} by
26391 @code{Short_Address}.
26393 In the case of STARLET, there were several record types that should
26394 have had representation clauses but did not.  In these record types
26395 there was an implicit assumption that an @code{Address} value occupied
26396 32 bits.
26397 These compiled without error, but their usage resulted in run-time error
26398 returns from STARLET system calls.
26399 To assist in the compile-time detection of such situations, we
26400 plan to include a switch to generate a warning message when a
26401 record component is of type @code{Address}.
26404 @c ****************************************
26405 @node Taking advantage of 64 bit addressing
26406 @subsection Taking advantage of 64-bit addressing
26408 @menu
26409 * Making code 64 bit clean::
26410 * Allocating memory from the 64 bit storage pool::
26411 * Restrictions on use of 64 bit objects::
26412 * Using 64 bit storage pools by default::
26413 * General access types::
26414 * STARLET and other predefined libraries::
26415 @end menu
26417 @node Making code 64 bit clean
26418 @subsubsection Making code 64-bit clean
26420 @noindent
26421 In order to prevent problems that may occur when (parts of) a
26422 system start using memory outside the 32-bit address range,
26423 we recommend some additional guidelines:
26425 @itemize @bullet
26426 @item
26427 For imported subprograms that take parameters of the
26428 type @code{System.Address}, ensure that these subprograms can
26429 indeed handle 64-bit addresses. If not, or when in doubt,
26430 change the subprogram declaration to specify
26431 @code{System.Short_Address} instead.
26433 @item
26434 Resolve all warnings related to size mismatches in
26435 unchecked conversions. Failing to do so causes
26436 erroneous execution if the source object is outside
26437 the 32-bit address space.
26439 @item
26440 (optional) Explicitly use the 32-bit storage pool
26441 for access types used in a 32-bit context, or use
26442 generic access types where possible
26443 (@pxref{Restrictions on use of 64 bit objects}).
26444 @end itemize
26446 @noindent
26447 If these rules are followed, the compiler will automatically insert
26448 any necessary checks to ensure that no addresses or access values
26449 passed to 32-bit code ever refer to objects outside the 32-bit
26450 address range.
26451 Any attempt to do this will raise @code{Constraint_Error}.
26453 @node Allocating memory from the 64 bit storage pool
26454 @subsubsection Allocating memory from the 64-bit storage pool
26456 @noindent
26457 For any access type @code{T} that potentially requires memory allocations
26458 beyond the 32-bit address space,
26459 use the following representation clause:
26461 @smallexample @c ada
26462    for T'Storage_Pool use System.Pool_64;
26463 @end smallexample
26466 @node Restrictions on use of 64 bit objects
26467 @subsubsection Restrictions on use of 64-bit objects
26469 @noindent
26470 Taking the address of an object allocated from a 64-bit storage pool,
26471 and then passing this address to a subprogram expecting
26472 @code{System.Short_Address},
26473 or assigning it to a variable of type @code{Short_Address}, will cause
26474 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26475 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26476 no exception is raised and execution
26477 will become erroneous.
26479 @node Using 64 bit storage pools by default
26480 @subsubsection Using 64-bit storage pools by default
26482 @noindent
26483 In some cases it may be desirable to have the compiler allocate
26484 from 64-bit storage pools by default. This may be the case for
26485 libraries that are 64-bit clean, but may be used in both 32-bit
26486 and 64-bit contexts. For these cases the following configuration
26487 pragma may be specified:
26489 @smallexample @c ada
26490   pragma Pool_64_Default;
26491 @end smallexample
26493 @noindent
26494 Any code compiled in the context of this pragma will by default
26495 use the @code{System.Pool_64} storage pool. This default may be overridden
26496 for a specific access type @code{T} by the representation clause:
26498 @smallexample @c ada
26499    for T'Storage_Pool use System.Pool_32;
26500 @end smallexample
26502 @noindent
26503 Any object whose address may be passed to a subprogram with a
26504 @code{Short_Address} argument, or assigned to a variable of type
26505 @code{Short_Address}, needs to be allocated from this pool.
26507 @node General access types
26508 @subsubsection General access types
26510 @noindent
26511 Objects designated by access values from a
26512 general access type (declared with @code{access all}) are never allocated
26513 from a 64-bit storage pool. Code that uses general access types will
26514 accept objects allocated in either 32-bit or 64-bit address spaces,
26515 but never allocate objects outside the 32-bit address space.
26516 Using general access types ensures maximum compatibility with both
26517 32-bit and 64-bit code.
26520 @node STARLET and other predefined libraries
26521 @subsubsection STARLET and other predefined libraries
26523 @noindent
26524 All code that comes as part of GNAT is 64-bit clean, but the
26525 restrictions given in @ref{Restrictions on use of 64 bit objects},
26526 still apply. Look at the package
26527 specifications to see in which contexts objects allocated
26528 in 64-bit address space are acceptable.
26530 @node Technical details
26531 @subsection Technical details
26533 @noindent
26534 GNAT Pro for Open VMS Integrity takes advantage of the freedom given in the Ada
26535 standard with respect to the type of @code{System.Address}. Previous versions
26536 of GNAT Pro have defined this type as private and implemented it as
26537 a modular type.
26539 In order to allow defining @code{System.Short_Address} as a proper subtype,
26540 and to match the implicit sign extension in parameter passing,
26541 in GNAT Pro for Open VMS Integrity, @code{System.Address} is defined as a
26542 visible (i.e., non-private) integer type.
26543 Standard operations on the type, such as the binary operators ``+'', ``-'',
26544 etc., that take @code{Address} operands and return an @code{Address} result,
26545 have been hidden by declaring these
26546 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
26547 that would otherwise result from overloading.
26548 (Note that, although @code{Address} is a visible integer type,
26549 good programming practice dictates against exploiting the type's
26550 integer properties such as literals, since this will compromise
26551 code portability.)
26553 Defining @code{Address} as a visible integer type helps achieve
26554 maximum compatibility for existing Ada code,
26555 without sacrificing the capabilities of the IA64 architecture.
26556 @end ifset
26559 @c ************************************************
26560 @ifset unw
26561 @node Microsoft Windows Topics
26562 @appendix Microsoft Windows Topics
26563 @cindex Windows NT
26564 @cindex Windows 95
26565 @cindex Windows 98
26567 @noindent
26568 This chapter describes topics that are specific to the Microsoft Windows
26569 platforms (NT, 2000, and XP Professional).
26571 @menu
26572 * Using GNAT on Windows::
26573 * Using a network installation of GNAT::
26574 * CONSOLE and WINDOWS subsystems::
26575 * Temporary Files::
26576 * Mixed-Language Programming on Windows::
26577 * Windows Calling Conventions::
26578 * Introduction to Dynamic Link Libraries (DLLs)::
26579 * Using DLLs with GNAT::
26580 * Building DLLs with GNAT::
26581 * Building DLLs with GNAT Project files::
26582 * Building DLLs with gnatdll::
26583 * GNAT and Windows Resources::
26584 * Debugging a DLL::
26585 * GNAT and COM/DCOM Objects::
26586 @end menu
26588 @node Using GNAT on Windows
26589 @section Using GNAT on Windows
26591 @noindent
26592 One of the strengths of the GNAT technology is that its tool set
26593 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26594 @code{gdb} debugger, etc.) is used in the same way regardless of the
26595 platform.
26597 On Windows this tool set is complemented by a number of Microsoft-specific
26598 tools that have been provided to facilitate interoperability with Windows
26599 when this is required. With these tools:
26601 @itemize @bullet
26603 @item
26604 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26605 subsystems.
26607 @item
26608 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26609 relocatable and non-relocatable DLLs are supported).
26611 @item
26612 You can build Ada DLLs for use in other applications. These applications
26613 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26614 relocatable and non-relocatable Ada DLLs are supported.
26616 @item
26617 You can include Windows resources in your Ada application.
26619 @item
26620 You can use or create COM/DCOM objects.
26621 @end itemize
26623 @noindent
26624 Immediately below are listed all known general GNAT-for-Windows restrictions.
26625 Other restrictions about specific features like Windows Resources and DLLs
26626 are listed in separate sections below.
26628 @itemize @bullet
26630 @item
26631 It is not possible to use @code{GetLastError} and @code{SetLastError}
26632 when tasking, protected records, or exceptions are used. In these
26633 cases, in order to implement Ada semantics, the GNAT run-time system
26634 calls certain Win32 routines that set the last error variable to 0 upon
26635 success. It should be possible to use @code{GetLastError} and
26636 @code{SetLastError} when tasking, protected record, and exception
26637 features are not used, but it is not guaranteed to work.
26639 @item
26640 It is not possible to link against Microsoft libraries except for
26641 import libraries. The library must be built to be compatible with
26642 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26643 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26644 not be compatible with the GNAT runtime. Even if the library is
26645 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26647 @item
26648 When the compilation environment is located on FAT32 drives, users may
26649 experience recompilations of the source files that have not changed if
26650 Daylight Saving Time (DST) state has changed since the last time files
26651 were compiled. NTFS drives do not have this problem.
26653 @item
26654 No components of the GNAT toolset use any entries in the Windows
26655 registry. The only entries that can be created are file associations and
26656 PATH settings, provided the user has chosen to create them at installation
26657 time, as well as some minimal book-keeping information needed to correctly
26658 uninstall or integrate different GNAT products.
26659 @end itemize
26661 @node Using a network installation of GNAT
26662 @section Using a network installation of GNAT
26664 @noindent
26665 Make sure the system on which GNAT is installed is accessible from the
26666 current machine, i.e. the install location is shared over the network.
26667 Shared resources are accessed on Windows by means of UNC paths, which
26668 have the format @code{\\server\sharename\path}
26670 In order to use such a network installation, simply add the UNC path of the
26671 @file{bin} directory of your GNAT installation in front of your PATH. For
26672 example, if GNAT is installed in @file{\GNAT} directory of a share location
26673 called @file{c-drive} on a machine @file{LOKI}, the following command will
26674 make it available:
26676 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26678 Be aware that every compilation using the network installation results in the
26679 transfer of large amounts of data across the network and will likely cause
26680 serious performance penalty.
26682 @node CONSOLE and WINDOWS subsystems
26683 @section CONSOLE and WINDOWS subsystems
26684 @cindex CONSOLE Subsystem
26685 @cindex WINDOWS Subsystem
26686 @cindex -mwindows
26688 @noindent
26689 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26690 (which is the default subsystem) will always create a console when
26691 launching the application. This is not something desirable when the
26692 application has a Windows GUI. To get rid of this console the
26693 application must be using the @code{WINDOWS} subsystem. To do so
26694 the @option{-mwindows} linker option must be specified.
26696 @smallexample
26697 $ gnatmake winprog -largs -mwindows
26698 @end smallexample
26700 @node Temporary Files
26701 @section Temporary Files
26702 @cindex Temporary files
26704 @noindent
26705 It is possible to control where temporary files gets created by setting
26706 the TMP environment variable. The file will be created:
26708 @itemize
26709 @item Under the directory pointed to by the TMP environment variable if
26710 this directory exists.
26712 @item Under c:\temp, if the TMP environment variable is not set (or not
26713 pointing to a directory) and if this directory exists.
26715 @item Under the current working directory otherwise.
26716 @end itemize
26718 @noindent
26719 This allows you to determine exactly where the temporary
26720 file will be created. This is particularly useful in networked
26721 environments where you may not have write access to some
26722 directories.
26724 @node Mixed-Language Programming on Windows
26725 @section Mixed-Language Programming on Windows
26727 @noindent
26728 Developing pure Ada applications on Windows is no different than on
26729 other GNAT-supported platforms. However, when developing or porting an
26730 application that contains a mix of Ada and C/C++, the choice of your
26731 Windows C/C++ development environment conditions your overall
26732 interoperability strategy.
26734 If you use @command{gcc} to compile the non-Ada part of your application,
26735 there are no Windows-specific restrictions that affect the overall
26736 interoperability with your Ada code. If you plan to use
26737 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26738 the following limitations:
26740 @itemize @bullet
26741 @item
26742 You cannot link your Ada code with an object or library generated with
26743 Microsoft tools if these use the @code{.tls} section (Thread Local
26744 Storage section) since the GNAT linker does not yet support this section.
26746 @item
26747 You cannot link your Ada code with an object or library generated with
26748 Microsoft tools if these use I/O routines other than those provided in
26749 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26750 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26751 libraries can cause a conflict with @code{msvcrt.dll} services. For
26752 instance Visual C++ I/O stream routines conflict with those in
26753 @code{msvcrt.dll}.
26754 @end itemize
26756 @noindent
26757 If you do want to use the Microsoft tools for your non-Ada code and hit one
26758 of the above limitations, you have two choices:
26760 @enumerate
26761 @item
26762 Encapsulate your non Ada code in a DLL to be linked with your Ada
26763 application. In this case, use the Microsoft or whatever environment to
26764 build the DLL and use GNAT to build your executable
26765 (@pxref{Using DLLs with GNAT}).
26767 @item
26768 Or you can encapsulate your Ada code in a DLL to be linked with the
26769 other part of your application. In this case, use GNAT to build the DLL
26770 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26771 environment to build your executable.
26772 @end enumerate
26774 @node Windows Calling Conventions
26775 @section Windows Calling Conventions
26776 @findex Stdcall
26777 @findex APIENTRY
26779 @menu
26780 * C Calling Convention::
26781 * Stdcall Calling Convention::
26782 * Win32 Calling Convention::
26783 * DLL Calling Convention::
26784 @end menu
26786 @noindent
26787 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26788 (callee), there are several ways to push @code{G}'s parameters on the
26789 stack and there are several possible scenarios to clean up the stack
26790 upon @code{G}'s return. A calling convention is an agreed upon software
26791 protocol whereby the responsibilities between the caller (@code{F}) and
26792 the callee (@code{G}) are clearly defined. Several calling conventions
26793 are available for Windows:
26795 @itemize @bullet
26796 @item
26797 @code{C} (Microsoft defined)
26799 @item
26800 @code{Stdcall} (Microsoft defined)
26802 @item
26803 @code{Win32} (GNAT specific)
26805 @item
26806 @code{DLL} (GNAT specific)
26807 @end itemize
26809 @node C Calling Convention
26810 @subsection @code{C} Calling Convention
26812 @noindent
26813 This is the default calling convention used when interfacing to C/C++
26814 routines compiled with either @command{gcc} or Microsoft Visual C++.
26816 In the @code{C} calling convention subprogram parameters are pushed on the
26817 stack by the caller from right to left. The caller itself is in charge of
26818 cleaning up the stack after the call. In addition, the name of a routine
26819 with @code{C} calling convention is mangled by adding a leading underscore.
26821 The name to use on the Ada side when importing (or exporting) a routine
26822 with @code{C} calling convention is the name of the routine. For
26823 instance the C function:
26825 @smallexample
26826 int get_val (long);
26827 @end smallexample
26829 @noindent
26830 should be imported from Ada as follows:
26832 @smallexample @c ada
26833 @group
26834 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26835 pragma Import (C, Get_Val, External_Name => "get_val");
26836 @end group
26837 @end smallexample
26839 @noindent
26840 Note that in this particular case the @code{External_Name} parameter could
26841 have been omitted since, when missing, this parameter is taken to be the
26842 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26843 is missing, as in the above example, this parameter is set to be the
26844 @code{External_Name} with a leading underscore.
26846 When importing a variable defined in C, you should always use the @code{C}
26847 calling convention unless the object containing the variable is part of a
26848 DLL (in which case you should use the @code{Stdcall} calling
26849 convention, @pxref{Stdcall Calling Convention}).
26851 @node Stdcall Calling Convention
26852 @subsection @code{Stdcall} Calling Convention
26854 @noindent
26855 This convention, which was the calling convention used for Pascal
26856 programs, is used by Microsoft for all the routines in the Win32 API for
26857 efficiency reasons. It must be used to import any routine for which this
26858 convention was specified.
26860 In the @code{Stdcall} calling convention subprogram parameters are pushed
26861 on the stack by the caller from right to left. The callee (and not the
26862 caller) is in charge of cleaning the stack on routine exit. In addition,
26863 the name of a routine with @code{Stdcall} calling convention is mangled by
26864 adding a leading underscore (as for the @code{C} calling convention) and a
26865 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26866 bytes) of the parameters passed to the routine.
26868 The name to use on the Ada side when importing a C routine with a
26869 @code{Stdcall} calling convention is the name of the C routine. The leading
26870 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26871 the compiler. For instance the Win32 function:
26873 @smallexample
26874 @b{APIENTRY} int get_val (long);
26875 @end smallexample
26877 @noindent
26878 should be imported from Ada as follows:
26880 @smallexample @c ada
26881 @group
26882 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26883 pragma Import (Stdcall, Get_Val);
26884 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26885 @end group
26886 @end smallexample
26888 @noindent
26889 As for the @code{C} calling convention, when the @code{External_Name}
26890 parameter is missing, it is taken to be the name of the Ada entity in lower
26891 case. If instead of writing the above import pragma you write:
26893 @smallexample @c ada
26894 @group
26895 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26896 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26897 @end group
26898 @end smallexample
26900 @noindent
26901 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26902 of specifying the @code{External_Name} parameter you specify the
26903 @code{Link_Name} as in the following example:
26905 @smallexample @c ada
26906 @group
26907 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26908 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26909 @end group
26910 @end smallexample
26912 @noindent
26913 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26914 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26915 added at the end of the @code{Link_Name} by the compiler.
26917 @noindent
26918 Note, that in some special cases a DLL's entry point name lacks a trailing
26919 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26920 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26921 to handle those cases (@pxref{Using gnatdll} for the description of
26922 the switches).
26924 @noindent
26925 It is also possible to import variables defined in a DLL by using an
26926 import pragma for a variable. As an example, if a DLL contains a
26927 variable defined as:
26929 @smallexample
26930 int my_var;
26931 @end smallexample
26933 @noindent
26934 then, to access this variable from Ada you should write:
26936 @smallexample @c ada
26937 @group
26938 My_Var : Interfaces.C.int;
26939 pragma Import (Stdcall, My_Var);
26940 @end group
26941 @end smallexample
26943 @noindent
26944 Note that to ease building cross-platform bindings this convention
26945 will be handled as a @code{C} calling convention on non Windows platforms.
26947 @node Win32 Calling Convention
26948 @subsection @code{Win32} Calling Convention
26950 @noindent
26951 This convention, which is GNAT-specific is fully equivalent to the
26952 @code{Stdcall} calling convention described above.
26954 @node DLL Calling Convention
26955 @subsection @code{DLL} Calling Convention
26957 @noindent
26958 This convention, which is GNAT-specific is fully equivalent to the
26959 @code{Stdcall} calling convention described above.
26961 @node Introduction to Dynamic Link Libraries (DLLs)
26962 @section Introduction to Dynamic Link Libraries (DLLs)
26963 @findex DLL
26965 @noindent
26966 A Dynamically Linked Library (DLL) is a library that can be shared by
26967 several applications running under Windows. A DLL can contain any number of
26968 routines and variables.
26970 One advantage of DLLs is that you can change and enhance them without
26971 forcing all the applications that depend on them to be relinked or
26972 recompiled. However, you should be aware than all calls to DLL routines are
26973 slower since, as you will understand below, such calls are indirect.
26975 To illustrate the remainder of this section, suppose that an application
26976 wants to use the services of a DLL @file{API.dll}. To use the services
26977 provided by @file{API.dll} you must statically link against the DLL or
26978 an import library which contains a jump table with an entry for each
26979 routine and variable exported by the DLL. In the Microsoft world this
26980 import library is called @file{API.lib}. When using GNAT this import
26981 library is called either @file{libAPI.a} or @file{libapi.a} (names are
26982 case insensitive).
26984 After you have linked your application with the DLL or the import library
26985 and you run your application, here is what happens:
26987 @enumerate
26988 @item
26989 Your application is loaded into memory.
26991 @item
26992 The DLL @file{API.dll} is mapped into the address space of your
26993 application. This means that:
26995 @itemize @bullet
26996 @item
26997 The DLL will use the stack of the calling thread.
26999 @item
27000 The DLL will use the virtual address space of the calling process.
27002 @item
27003 The DLL will allocate memory from the virtual address space of the calling
27004 process.
27006 @item
27007 Handles (pointers) can be safely exchanged between routines in the DLL
27008 routines and routines in the application using the DLL.
27009 @end itemize
27011 @item
27012 The entries in the jump table (from the import library @file{libAPI.a}
27013 or @file{API.lib} or automatically created when linking against a DLL)
27014 which is part of your application are initialized with the addresses
27015 of the routines and variables in @file{API.dll}.
27017 @item
27018 If present in @file{API.dll}, routines @code{DllMain} or
27019 @code{DllMainCRTStartup} are invoked. These routines typically contain
27020 the initialization code needed for the well-being of the routines and
27021 variables exported by the DLL.
27022 @end enumerate
27024 @noindent
27025 There is an additional point which is worth mentioning. In the Windows
27026 world there are two kind of DLLs: relocatable and non-relocatable
27027 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27028 in the target application address space. If the addresses of two
27029 non-relocatable DLLs overlap and these happen to be used by the same
27030 application, a conflict will occur and the application will run
27031 incorrectly. Hence, when possible, it is always preferable to use and
27032 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27033 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27034 User's Guide) removes the debugging symbols from the DLL but the DLL can
27035 still be relocated.
27037 As a side note, an interesting difference between Microsoft DLLs and
27038 Unix shared libraries, is the fact that on most Unix systems all public
27039 routines are exported by default in a Unix shared library, while under
27040 Windows it is possible (but not required) to list exported routines in
27041 a definition file (@pxref{The Definition File}).
27043 @node Using DLLs with GNAT
27044 @section Using DLLs with GNAT
27046 @menu
27047 * Creating an Ada Spec for the DLL Services::
27048 * Creating an Import Library::
27049 @end menu
27051 @noindent
27052 To use the services of a DLL, say @file{API.dll}, in your Ada application
27053 you must have:
27055 @enumerate
27056 @item
27057 The Ada spec for the routines and/or variables you want to access in
27058 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27059 header files provided with the DLL.
27061 @item
27062 The import library (@file{libAPI.a} or @file{API.lib}). As previously
27063 mentioned an import library is a statically linked library containing the
27064 import table which will be filled at load time to point to the actual
27065 @file{API.dll} routines. Sometimes you don't have an import library for the
27066 DLL you want to use. The following sections will explain how to build
27067 one. Note that this is optional.
27069 @item
27070 The actual DLL, @file{API.dll}.
27071 @end enumerate
27073 @noindent
27074 Once you have all the above, to compile an Ada application that uses the
27075 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27076 you simply issue the command
27078 @smallexample
27079 $ gnatmake my_ada_app -largs -lAPI
27080 @end smallexample
27082 @noindent
27083 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27084 tells the GNAT linker to look first for a library named @file{API.lib}
27085 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
27086 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
27087 contains the following pragma
27089 @smallexample @c ada
27090 pragma Linker_Options ("-lAPI");
27091 @end smallexample
27093 @noindent
27094 you do not have to add @option{-largs -lAPI} at the end of the
27095 @command{gnatmake} command.
27097 If any one of the items above is missing you will have to create it
27098 yourself. The following sections explain how to do so using as an
27099 example a fictitious DLL called @file{API.dll}.
27101 @node Creating an Ada Spec for the DLL Services
27102 @subsection Creating an Ada Spec for the DLL Services
27104 @noindent
27105 A DLL typically comes with a C/C++ header file which provides the
27106 definitions of the routines and variables exported by the DLL. The Ada
27107 equivalent of this header file is a package spec that contains definitions
27108 for the imported entities. If the DLL you intend to use does not come with
27109 an Ada spec you have to generate one such spec yourself. For example if
27110 the header file of @file{API.dll} is a file @file{api.h} containing the
27111 following two definitions:
27113 @smallexample
27114 @group
27115 @cartouche
27116 int some_var;
27117 int get (char *);
27118 @end cartouche
27119 @end group
27120 @end smallexample
27122 @noindent
27123 then the equivalent Ada spec could be:
27125 @smallexample @c ada
27126 @group
27127 @cartouche
27128 with Interfaces.C.Strings;
27129 package API is
27130    use Interfaces;
27132    Some_Var : C.int;
27133    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27135 private
27136    pragma Import (C, Get);
27137    pragma Import (DLL, Some_Var);
27138 end API;
27139 @end cartouche
27140 @end group
27141 @end smallexample
27143 @noindent
27144 Note that a variable is
27145 @strong{always imported with a Stdcall convention}. A function
27146 can have @code{C} or @code{Stdcall} convention.
27147 (@pxref{Windows Calling Conventions}).
27149 @node Creating an Import Library
27150 @subsection Creating an Import Library
27151 @cindex Import library
27153 @menu
27154 * The Definition File::
27155 * GNAT-Style Import Library::
27156 * Microsoft-Style Import Library::
27157 @end menu
27159 @noindent
27160 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27161 import library @file{libAPI.a} is available with @file{API.dll} you
27162 can skip this section. You can also skip this section if
27163 @file{API.dll} is built with GNU tools as in this case it is possible
27164 to link directly against the DLL. Otherwise read on.
27166 @node The Definition File
27167 @subsubsection The Definition File
27168 @cindex Definition file
27169 @findex .def
27171 @noindent
27172 As previously mentioned, and unlike Unix systems, the list of symbols
27173 that are exported from a DLL must be provided explicitly in Windows.
27174 The main goal of a definition file is precisely that: list the symbols
27175 exported by a DLL. A definition file (usually a file with a @code{.def}
27176 suffix) has the following structure:
27178 @smallexample
27179 @group
27180 @cartouche
27181 [LIBRARY @i{name}]
27182 [DESCRIPTION @i{string}]
27183 EXPORTS
27184    @i{symbol1}
27185    @i{symbol2}
27186    ...
27187 @end cartouche
27188 @end group
27189 @end smallexample
27191 @table @code
27192 @item LIBRARY @i{name}
27193 This section, which is optional, gives the name of the DLL.
27195 @item DESCRIPTION @i{string}
27196 This section, which is optional, gives a description string that will be
27197 embedded in the import library.
27199 @item EXPORTS
27200 This section gives the list of exported symbols (procedures, functions or
27201 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27202 section of @file{API.def} looks like:
27204 @smallexample
27205 @group
27206 @cartouche
27207 EXPORTS
27208    some_var
27209    get
27210 @end cartouche
27211 @end group
27212 @end smallexample
27213 @end table
27215 @noindent
27216 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
27217 (@pxref{Windows Calling Conventions}) for a Stdcall
27218 calling convention function in the exported symbols list.
27220 @noindent
27221 There can actually be other sections in a definition file, but these
27222 sections are not relevant to the discussion at hand.
27224 @node GNAT-Style Import Library
27225 @subsubsection GNAT-Style Import Library
27227 @noindent
27228 To create a static import library from @file{API.dll} with the GNAT tools
27229 you should proceed as follows:
27231 @enumerate
27232 @item
27233 Create the definition file @file{API.def} (@pxref{The Definition File}).
27234 For that use the @code{dll2def} tool as follows:
27236 @smallexample
27237 $ dll2def API.dll > API.def
27238 @end smallexample
27240 @noindent
27241 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27242 to standard output the list of entry points in the DLL. Note that if
27243 some routines in the DLL have the @code{Stdcall} convention
27244 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27245 suffix then you'll have to edit @file{api.def} to add it, and specify
27246 @code{-k} to @code{gnatdll} when creating the import library.
27248 @noindent
27249 Here are some hints to find the right @code{@@}@i{nn} suffix.
27251 @enumerate
27252 @item
27253 If you have the Microsoft import library (.lib), it is possible to get
27254 the right symbols by using Microsoft @code{dumpbin} tool (see the
27255 corresponding Microsoft documentation for further details).
27257 @smallexample
27258 $ dumpbin /exports api.lib
27259 @end smallexample
27261 @item
27262 If you have a message about a missing symbol at link time the compiler
27263 tells you what symbol is expected. You just have to go back to the
27264 definition file and add the right suffix.
27265 @end enumerate
27267 @item
27268 Build the import library @code{libAPI.a}, using @code{gnatdll}
27269 (@pxref{Using gnatdll}) as follows:
27271 @smallexample
27272 $ gnatdll -e API.def -d API.dll
27273 @end smallexample
27275 @noindent
27276 @code{gnatdll} takes as input a definition file @file{API.def} and the
27277 name of the DLL containing the services listed in the definition file
27278 @file{API.dll}. The name of the static import library generated is
27279 computed from the name of the definition file as follows: if the
27280 definition file name is @i{xyz}@code{.def}, the import library name will
27281 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27282 @option{-e} could have been removed because the name of the definition
27283 file (before the ``@code{.def}'' suffix) is the same as the name of the
27284 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27285 @end enumerate
27287 @node Microsoft-Style Import Library
27288 @subsubsection Microsoft-Style Import Library
27290 @noindent
27291 With GNAT you can either use a GNAT-style or Microsoft-style import
27292 library. A Microsoft import library is needed only if you plan to make an
27293 Ada DLL available to applications developed with Microsoft
27294 tools (@pxref{Mixed-Language Programming on Windows}).
27296 To create a Microsoft-style import library for @file{API.dll} you
27297 should proceed as follows:
27299 @enumerate
27300 @item
27301 Create the definition file @file{API.def} from the DLL. For this use either
27302 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27303 tool (see the corresponding Microsoft documentation for further details).
27305 @item
27306 Build the actual import library using Microsoft's @code{lib} utility:
27308 @smallexample
27309 $ lib -machine:IX86 -def:API.def -out:API.lib
27310 @end smallexample
27312 @noindent
27313 If you use the above command the definition file @file{API.def} must
27314 contain a line giving the name of the DLL:
27316 @smallexample
27317 LIBRARY      "API"
27318 @end smallexample
27320 @noindent
27321 See the Microsoft documentation for further details about the usage of
27322 @code{lib}.
27323 @end enumerate
27325 @node Building DLLs with GNAT
27326 @section Building DLLs with GNAT
27327 @cindex DLLs, building
27329 @noindent
27330 This section explain how to build DLLs using the GNAT built-in DLL
27331 support. With the following procedure it is straight forward to build
27332 and use DLLs with GNAT.
27334 @enumerate
27336 @item building object files
27338 The first step is to build all objects files that are to be included
27339 into the DLL. This is done by using the standard @command{gnatmake} tool.
27341 @item building the DLL
27343 To build the DLL you must use @command{gcc}'s @code{-shared}
27344 option. It is quite simple to use this method:
27346 @smallexample
27347 $ gcc -shared -o api.dll obj1.o obj2.o ...
27348 @end smallexample
27350 It is important to note that in this case all symbols found in the
27351 object files are automatically exported. It is possible to restrict
27352 the set of symbols to export by passing to @command{gcc} a definition
27353 file, @pxref{The Definition File}. For example:
27355 @smallexample
27356 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
27357 @end smallexample
27359 If you use a definition file you must export the elaboration procedures
27360 for every package that required one. Elaboration procedures are named
27361 using the package name followed by "_E".
27363 @item preparing DLL to be used
27365 For the DLL to be used by client programs the bodies must be hidden
27366 from it and the .ali set with read-only attribute. This is very important
27367 otherwise GNAT will recompile all packages and will not actually use
27368 the code in the DLL. For example:
27370 @smallexample
27371 $ mkdir apilib
27372 $ copy *.ads *.ali api.dll apilib
27373 $ attrib +R apilib\*.ali
27374 @end smallexample
27376 @end enumerate
27378 At this point it is possible to use the DLL by directly linking
27379 against it. Note that you must use the GNAT shared runtime when using
27380 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27381 option.
27383 @smallexample
27384 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27385 @end smallexample
27387 @node Building DLLs with GNAT Project files
27388 @section Building DLLs with GNAT Project files
27389 @cindex DLLs, building
27391 @noindent
27392 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27394 @node Building DLLs with gnatdll
27395 @section Building DLLs with gnatdll
27396 @cindex DLLs, building
27398 @menu
27399 * Limitations When Using Ada DLLs from Ada::
27400 * Exporting Ada Entities::
27401 * Ada DLLs and Elaboration::
27402 * Ada DLLs and Finalization::
27403 * Creating a Spec for Ada DLLs::
27404 * Creating the Definition File::
27405 * Using gnatdll::
27406 @end menu
27408 @noindent
27409 Note that it is preferred to use the built-in GNAT DLL support
27410 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27411 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27413 This section explains how to build DLLs containing Ada code using
27414 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27415 remainder of this section.
27417 The steps required to build an Ada DLL that is to be used by Ada as well as
27418 non-Ada applications are as follows:
27420 @enumerate
27421 @item
27422 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27423 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27424 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27425 skip this step if you plan to use the Ada DLL only from Ada applications.
27427 @item
27428 Your Ada code must export an initialization routine which calls the routine
27429 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27430 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27431 routine exported by the Ada DLL must be invoked by the clients of the DLL
27432 to initialize the DLL.
27434 @item
27435 When useful, the DLL should also export a finalization routine which calls
27436 routine @code{adafinal} generated by @command{gnatbind} to perform the
27437 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27438 The finalization routine exported by the Ada DLL must be invoked by the
27439 clients of the DLL when the DLL services are no further needed.
27441 @item
27442 You must provide a spec for the services exported by the Ada DLL in each
27443 of the programming languages to which you plan to make the DLL available.
27445 @item
27446 You must provide a definition file listing the exported entities
27447 (@pxref{The Definition File}).
27449 @item
27450 Finally you must use @code{gnatdll} to produce the DLL and the import
27451 library (@pxref{Using gnatdll}).
27452 @end enumerate
27454 @noindent
27455 Note that a relocatable DLL stripped using the @code{strip}
27456 binutils tool will not be relocatable anymore. To build a DLL without
27457 debug information pass @code{-largs -s} to @code{gnatdll}. This
27458 restriction does not apply to a DLL built using a Library Project.
27459 @pxref{Library Projects}.
27461 @node Limitations When Using Ada DLLs from Ada
27462 @subsection Limitations When Using Ada DLLs from Ada
27464 @noindent
27465 When using Ada DLLs from Ada applications there is a limitation users
27466 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27467 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27468 each Ada DLL includes the services of the GNAT run time that are necessary
27469 to the Ada code inside the DLL. As a result, when an Ada program uses an
27470 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27471 one in the main program.
27473 It is therefore not possible to exchange GNAT run-time objects between the
27474 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27475 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27476 types, etc.
27478 It is completely safe to exchange plain elementary, array or record types,
27479 Windows object handles, etc.
27481 @node Exporting Ada Entities
27482 @subsection Exporting Ada Entities
27483 @cindex Export table
27485 @noindent
27486 Building a DLL is a way to encapsulate a set of services usable from any
27487 application. As a result, the Ada entities exported by a DLL should be
27488 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27489 any Ada name mangling. As an example here is an Ada package
27490 @code{API}, spec and body, exporting two procedures, a function, and a
27491 variable:
27493 @smallexample @c ada
27494 @group
27495 @cartouche
27496 with Interfaces.C; use Interfaces;
27497 package API is
27498    Count : C.int := 0;
27499    function Factorial (Val : C.int) return C.int;
27501    procedure Initialize_API;
27502    procedure Finalize_API;
27503    --  Initialization & Finalization routines. More in the next section.
27504 private
27505    pragma Export (C, Initialize_API);
27506    pragma Export (C, Finalize_API);
27507    pragma Export (C, Count);
27508    pragma Export (C, Factorial);
27509 end API;
27510 @end cartouche
27511 @end group
27512 @end smallexample
27514 @smallexample @c ada
27515 @group
27516 @cartouche
27517 package body API is
27518    function Factorial (Val : C.int) return C.int is
27519       Fact : C.int := 1;
27520    begin
27521       Count := Count + 1;
27522       for K in 1 .. Val loop
27523          Fact := Fact * K;
27524       end loop;
27525       return Fact;
27526    end Factorial;
27528    procedure Initialize_API is
27529       procedure Adainit;
27530       pragma Import (C, Adainit);
27531    begin
27532       Adainit;
27533    end Initialize_API;
27535    procedure Finalize_API is
27536       procedure Adafinal;
27537       pragma Import (C, Adafinal);
27538    begin
27539       Adafinal;
27540    end Finalize_API;
27541 end API;
27542 @end cartouche
27543 @end group
27544 @end smallexample
27546 @noindent
27547 If the Ada DLL you are building will only be used by Ada applications
27548 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27549 convention. As an example, the previous package could be written as
27550 follows:
27552 @smallexample @c ada
27553 @group
27554 @cartouche
27555 package API is
27556    Count : Integer := 0;
27557    function Factorial (Val : Integer) return Integer;
27559    procedure Initialize_API;
27560    procedure Finalize_API;
27561    --  Initialization and Finalization routines.
27562 end API;
27563 @end cartouche
27564 @end group
27565 @end smallexample
27567 @smallexample @c ada
27568 @group
27569 @cartouche
27570 package body API is
27571    function Factorial (Val : Integer) return Integer is
27572       Fact : Integer := 1;
27573    begin
27574       Count := Count + 1;
27575       for K in 1 .. Val loop
27576          Fact := Fact * K;
27577       end loop;
27578       return Fact;
27579    end Factorial;
27581    ...
27582    --  The remainder of this package body is unchanged.
27583 end API;
27584 @end cartouche
27585 @end group
27586 @end smallexample
27588 @noindent
27589 Note that if you do not export the Ada entities with a @code{C} or
27590 @code{Stdcall} convention you will have to provide the mangled Ada names
27591 in the definition file of the Ada DLL
27592 (@pxref{Creating the Definition File}).
27594 @node Ada DLLs and Elaboration
27595 @subsection Ada DLLs and Elaboration
27596 @cindex DLLs and elaboration
27598 @noindent
27599 The DLL that you are building contains your Ada code as well as all the
27600 routines in the Ada library that are needed by it. The first thing a
27601 user of your DLL must do is elaborate the Ada code
27602 (@pxref{Elaboration Order Handling in GNAT}).
27604 To achieve this you must export an initialization routine
27605 (@code{Initialize_API} in the previous example), which must be invoked
27606 before using any of the DLL services. This elaboration routine must call
27607 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27608 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27609 @code{Initialize_Api} for an example. Note that the GNAT binder is
27610 automatically invoked during the DLL build process by the @code{gnatdll}
27611 tool (@pxref{Using gnatdll}).
27613 When a DLL is loaded, Windows systematically invokes a routine called
27614 @code{DllMain}. It would therefore be possible to call @code{adainit}
27615 directly from @code{DllMain} without having to provide an explicit
27616 initialization routine. Unfortunately, it is not possible to call
27617 @code{adainit} from the @code{DllMain} if your program has library level
27618 tasks because access to the @code{DllMain} entry point is serialized by
27619 the system (that is, only a single thread can execute ``through'' it at a
27620 time), which means that the GNAT run time will deadlock waiting for the
27621 newly created task to complete its initialization.
27623 @node Ada DLLs and Finalization
27624 @subsection Ada DLLs and Finalization
27625 @cindex DLLs and finalization
27627 @noindent
27628 When the services of an Ada DLL are no longer needed, the client code should
27629 invoke the DLL finalization routine, if available. The DLL finalization
27630 routine is in charge of releasing all resources acquired by the DLL. In the
27631 case of the Ada code contained in the DLL, this is achieved by calling
27632 routine @code{adafinal} generated by the GNAT binder
27633 (@pxref{Binding with Non-Ada Main Programs}).
27634 See the body of @code{Finalize_Api} for an
27635 example. As already pointed out the GNAT binder is automatically invoked
27636 during the DLL build process by the @code{gnatdll} tool
27637 (@pxref{Using gnatdll}).
27639 @node Creating a Spec for Ada DLLs
27640 @subsection Creating a Spec for Ada DLLs
27642 @noindent
27643 To use the services exported by the Ada DLL from another programming
27644 language (e.g. C), you have to translate the specs of the exported Ada
27645 entities in that language. For instance in the case of @code{API.dll},
27646 the corresponding C header file could look like:
27648 @smallexample
27649 @group
27650 @cartouche
27651 extern int *_imp__count;
27652 #define count (*_imp__count)
27653 int factorial (int);
27654 @end cartouche
27655 @end group
27656 @end smallexample
27658 @noindent
27659 It is important to understand that when building an Ada DLL to be used by
27660 other Ada applications, you need two different specs for the packages
27661 contained in the DLL: one for building the DLL and the other for using
27662 the DLL. This is because the @code{DLL} calling convention is needed to
27663 use a variable defined in a DLL, but when building the DLL, the variable
27664 must have either the @code{Ada} or @code{C} calling convention. As an
27665 example consider a DLL comprising the following package @code{API}:
27667 @smallexample @c ada
27668 @group
27669 @cartouche
27670 package API is
27671    Count : Integer := 0;
27672    ...
27673    --  Remainder of the package omitted.
27674 end API;
27675 @end cartouche
27676 @end group
27677 @end smallexample
27679 @noindent
27680 After producing a DLL containing package @code{API}, the spec that
27681 must be used to import @code{API.Count} from Ada code outside of the
27682 DLL is:
27684 @smallexample @c ada
27685 @group
27686 @cartouche
27687 package API is
27688    Count : Integer;
27689    pragma Import (DLL, Count);
27690 end API;
27691 @end cartouche
27692 @end group
27693 @end smallexample
27695 @node Creating the Definition File
27696 @subsection Creating the Definition File
27698 @noindent
27699 The definition file is the last file needed to build the DLL. It lists
27700 the exported symbols. As an example, the definition file for a DLL
27701 containing only package @code{API} (where all the entities are exported
27702 with a @code{C} calling convention) is:
27704 @smallexample
27705 @group
27706 @cartouche
27707 EXPORTS
27708     count
27709     factorial
27710     finalize_api
27711     initialize_api
27712 @end cartouche
27713 @end group
27714 @end smallexample
27716 @noindent
27717 If the @code{C} calling convention is missing from package @code{API},
27718 then the definition file contains the mangled Ada names of the above
27719 entities, which in this case are:
27721 @smallexample
27722 @group
27723 @cartouche
27724 EXPORTS
27725     api__count
27726     api__factorial
27727     api__finalize_api
27728     api__initialize_api
27729 @end cartouche
27730 @end group
27731 @end smallexample
27733 @node Using gnatdll
27734 @subsection Using @code{gnatdll}
27735 @findex gnatdll
27737 @menu
27738 * gnatdll Example::
27739 * gnatdll behind the Scenes::
27740 * Using dlltool::
27741 @end menu
27743 @noindent
27744 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27745 and non-Ada sources that make up your DLL have been compiled.
27746 @code{gnatdll} is actually in charge of two distinct tasks: build the
27747 static import library for the DLL and the actual DLL. The form of the
27748 @code{gnatdll} command is
27750 @smallexample
27751 @cartouche
27752 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27753 @end cartouche
27754 @end smallexample
27756 @noindent
27757 where @i{list-of-files} is a list of ALI and object files. The object
27758 file list must be the exact list of objects corresponding to the non-Ada
27759 sources whose services are to be included in the DLL. The ALI file list
27760 must be the exact list of ALI files for the corresponding Ada sources
27761 whose services are to be included in the DLL. If @i{list-of-files} is
27762 missing, only the static import library is generated.
27764 @noindent
27765 You may specify any of the following switches to @code{gnatdll}:
27767 @table @code
27768 @item -a[@var{address}]
27769 @cindex @option{-a} (@code{gnatdll})
27770 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27771 specified the default address @var{0x11000000} will be used. By default,
27772 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27773 advise the reader to build relocatable DLL.
27775 @item -b @var{address}
27776 @cindex @option{-b} (@code{gnatdll})
27777 Set the relocatable DLL base address. By default the address is
27778 @var{0x11000000}.
27780 @item -bargs @var{opts}
27781 @cindex @option{-bargs} (@code{gnatdll})
27782 Binder options. Pass @var{opts} to the binder.
27784 @item -d @var{dllfile}
27785 @cindex @option{-d} (@code{gnatdll})
27786 @var{dllfile} is the name of the DLL. This switch must be present for
27787 @code{gnatdll} to do anything. The name of the generated import library is
27788 obtained algorithmically from @var{dllfile} as shown in the following
27789 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27790 @code{libxyz.a}. The name of the definition file to use (if not specified
27791 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27792 as shown in the following example:
27793 if @var{dllfile} is @code{xyz.dll}, the definition
27794 file used is @code{xyz.def}.
27796 @item -e @var{deffile}
27797 @cindex @option{-e} (@code{gnatdll})
27798 @var{deffile} is the name of the definition file.
27800 @item -g
27801 @cindex @option{-g} (@code{gnatdll})
27802 Generate debugging information. This information is stored in the object
27803 file and copied from there to the final DLL file by the linker,
27804 where it can be read by the debugger. You must use the
27805 @option{-g} switch if you plan on using the debugger or the symbolic
27806 stack traceback.
27808 @item -h
27809 @cindex @option{-h} (@code{gnatdll})
27810 Help mode. Displays @code{gnatdll} switch usage information.
27812 @item -Idir
27813 @cindex @option{-I} (@code{gnatdll})
27814 Direct @code{gnatdll} to search the @var{dir} directory for source and
27815 object files needed to build the DLL.
27816 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27818 @item -k
27819 @cindex @option{-k} (@code{gnatdll})
27820 Removes the @code{@@}@i{nn} suffix from the import library's exported
27821 names, but keeps them for the link names. You must specify this
27822 option if you want to use a @code{Stdcall} function in a DLL for which
27823 the @code{@@}@i{nn} suffix has been removed. This is the case for most
27824 of the Windows NT DLL for example. This option has no effect when
27825 @option{-n} option is specified.
27827 @item -l @var{file}
27828 @cindex @option{-l} (@code{gnatdll})
27829 The list of ALI and object files used to build the DLL are listed in
27830 @var{file}, instead of being given in the command line. Each line in
27831 @var{file} contains the name of an ALI or object file.
27833 @item -n
27834 @cindex @option{-n} (@code{gnatdll})
27835 No Import. Do not create the import library.
27837 @item -q
27838 @cindex @option{-q} (@code{gnatdll})
27839 Quiet mode. Do not display unnecessary messages.
27841 @item -v
27842 @cindex @option{-v} (@code{gnatdll})
27843 Verbose mode. Display extra information.
27845 @item -largs @var{opts}
27846 @cindex @option{-largs} (@code{gnatdll})
27847 Linker options. Pass @var{opts} to the linker.
27848 @end table
27850 @node gnatdll Example
27851 @subsubsection @code{gnatdll} Example
27853 @noindent
27854 As an example the command to build a relocatable DLL from @file{api.adb}
27855 once @file{api.adb} has been compiled and @file{api.def} created is
27857 @smallexample
27858 $ gnatdll -d api.dll api.ali
27859 @end smallexample
27861 @noindent
27862 The above command creates two files: @file{libapi.a} (the import
27863 library) and @file{api.dll} (the actual DLL). If you want to create
27864 only the DLL, just type:
27866 @smallexample
27867 $ gnatdll -d api.dll -n api.ali
27868 @end smallexample
27870 @noindent
27871 Alternatively if you want to create just the import library, type:
27873 @smallexample
27874 $ gnatdll -d api.dll
27875 @end smallexample
27877 @node gnatdll behind the Scenes
27878 @subsubsection @code{gnatdll} behind the Scenes
27880 @noindent
27881 This section details the steps involved in creating a DLL. @code{gnatdll}
27882 does these steps for you. Unless you are interested in understanding what
27883 goes on behind the scenes, you should skip this section.
27885 We use the previous example of a DLL containing the Ada package @code{API},
27886 to illustrate the steps necessary to build a DLL. The starting point is a
27887 set of objects that will make up the DLL and the corresponding ALI
27888 files. In the case of this example this means that @file{api.o} and
27889 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27890 the following:
27892 @enumerate
27893 @item
27894 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27895 the information necessary to generate relocation information for the
27896 DLL.
27898 @smallexample
27899 @group
27900 $ gnatbind -n api
27901 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27902 @end group
27903 @end smallexample
27905 @noindent
27906 In addition to the base file, the @command{gnatlink} command generates an
27907 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27908 asks @command{gnatlink} to generate the routines @code{DllMain} and
27909 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27910 is loaded into memory.
27912 @item
27913 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27914 export table (@file{api.exp}). The export table contains the relocation
27915 information in a form which can be used during the final link to ensure
27916 that the Windows loader is able to place the DLL anywhere in memory.
27918 @smallexample
27919 @group
27920 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27921           --output-exp api.exp
27922 @end group
27923 @end smallexample
27925 @item
27926 @code{gnatdll} builds the base file using the new export table. Note that
27927 @command{gnatbind} must be called once again since the binder generated file
27928 has been deleted during the previous call to @command{gnatlink}.
27930 @smallexample
27931 @group
27932 $ gnatbind -n api
27933 $ gnatlink api -o api.jnk api.exp -mdll
27934       -Wl,--base-file,api.base
27935 @end group
27936 @end smallexample
27938 @item
27939 @code{gnatdll} builds the new export table using the new base file and
27940 generates the DLL import library @file{libAPI.a}.
27942 @smallexample
27943 @group
27944 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27945           --output-exp api.exp --output-lib libAPI.a
27946 @end group
27947 @end smallexample
27949 @item
27950 Finally @code{gnatdll} builds the relocatable DLL using the final export
27951 table.
27953 @smallexample
27954 @group
27955 $ gnatbind -n api
27956 $ gnatlink api api.exp -o api.dll -mdll
27957 @end group
27958 @end smallexample
27959 @end enumerate
27961 @node Using dlltool
27962 @subsubsection Using @code{dlltool}
27964 @noindent
27965 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27966 DLLs and static import libraries. This section summarizes the most
27967 common @code{dlltool} switches. The form of the @code{dlltool} command
27970 @smallexample
27971 $ dlltool [@var{switches}]
27972 @end smallexample
27974 @noindent
27975 @code{dlltool} switches include:
27977 @table @option
27978 @item --base-file @var{basefile}
27979 @cindex @option{--base-file} (@command{dlltool})
27980 Read the base file @var{basefile} generated by the linker. This switch
27981 is used to create a relocatable DLL.
27983 @item --def @var{deffile}
27984 @cindex @option{--def} (@command{dlltool})
27985 Read the definition file.
27987 @item --dllname @var{name}
27988 @cindex @option{--dllname} (@command{dlltool})
27989 Gives the name of the DLL. This switch is used to embed the name of the
27990 DLL in the static import library generated by @code{dlltool} with switch
27991 @option{--output-lib}.
27993 @item -k
27994 @cindex @option{-k} (@command{dlltool})
27995 Kill @code{@@}@i{nn} from exported names
27996 (@pxref{Windows Calling Conventions}
27997 for a discussion about @code{Stdcall}-style symbols.
27999 @item --help
28000 @cindex @option{--help} (@command{dlltool})
28001 Prints the @code{dlltool} switches with a concise description.
28003 @item --output-exp @var{exportfile}
28004 @cindex @option{--output-exp} (@command{dlltool})
28005 Generate an export file @var{exportfile}. The export file contains the
28006 export table (list of symbols in the DLL) and is used to create the DLL.
28008 @item --output-lib @i{libfile}
28009 @cindex @option{--output-lib} (@command{dlltool})
28010 Generate a static import library @var{libfile}.
28012 @item -v
28013 @cindex @option{-v} (@command{dlltool})
28014 Verbose mode.
28016 @item --as @i{assembler-name}
28017 @cindex @option{--as} (@command{dlltool})
28018 Use @i{assembler-name} as the assembler. The default is @code{as}.
28019 @end table
28021 @node GNAT and Windows Resources
28022 @section GNAT and Windows Resources
28023 @cindex Resources, windows
28025 @menu
28026 * Building Resources::
28027 * Compiling Resources::
28028 * Using Resources::
28029 @end menu
28031 @noindent
28032 Resources are an easy way to add Windows specific objects to your
28033 application. The objects that can be added as resources include:
28035 @itemize @bullet
28036 @item
28037 menus
28039 @item
28040 accelerators
28042 @item
28043 dialog boxes
28045 @item
28046 string tables
28048 @item
28049 bitmaps
28051 @item
28052 cursors
28054 @item
28055 icons
28057 @item
28058 fonts
28059 @end itemize
28061 @noindent
28062 This section explains how to build, compile and use resources.
28064 @node Building Resources
28065 @subsection Building Resources
28066 @cindex Resources, building
28068 @noindent
28069 A resource file is an ASCII file. By convention resource files have an
28070 @file{.rc} extension.
28071 The easiest way to build a resource file is to use Microsoft tools
28072 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28073 @code{dlgedit.exe} to build dialogs.
28074 It is always possible to build an @file{.rc} file yourself by writing a
28075 resource script.
28077 It is not our objective to explain how to write a resource file. A
28078 complete description of the resource script language can be found in the
28079 Microsoft documentation.
28081 @node Compiling Resources
28082 @subsection Compiling Resources
28083 @findex rc
28084 @findex windres
28085 @cindex Resources, compiling
28087 @noindent
28088 This section describes how to build a GNAT-compatible (COFF) object file
28089 containing the resources. This is done using the Resource Compiler
28090 @code{windres} as follows:
28092 @smallexample
28093 $ windres -i myres.rc -o myres.o
28094 @end smallexample
28096 @noindent
28097 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28098 file. You can specify an alternate preprocessor (usually named
28099 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28100 parameter. A list of all possible options may be obtained by entering
28101 the command @code{windres} @option{--help}.
28103 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28104 to produce a @file{.res} file (binary resource file). See the
28105 corresponding Microsoft documentation for further details. In this case
28106 you need to use @code{windres} to translate the @file{.res} file to a
28107 GNAT-compatible object file as follows:
28109 @smallexample
28110 $ windres -i myres.res -o myres.o
28111 @end smallexample
28113 @node Using Resources
28114 @subsection Using Resources
28115 @cindex Resources, using
28117 @noindent
28118 To include the resource file in your program just add the
28119 GNAT-compatible object file for the resource(s) to the linker
28120 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28121 option:
28123 @smallexample
28124 $ gnatmake myprog -largs myres.o
28125 @end smallexample
28127 @node Debugging a DLL
28128 @section Debugging a DLL
28129 @cindex DLL debugging
28131 @menu
28132 * Program and DLL Both Built with GCC/GNAT::
28133 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28134 @end menu
28136 @noindent
28137 Debugging a DLL is similar to debugging a standard program. But
28138 we have to deal with two different executable parts: the DLL and the
28139 program that uses it. We have the following four possibilities:
28141 @enumerate 1
28142 @item
28143 The program and the DLL are built with @code{GCC/GNAT}.
28144 @item
28145 The program is built with foreign tools and the DLL is built with
28146 @code{GCC/GNAT}.
28147 @item
28148 The program is built with @code{GCC/GNAT} and the DLL is built with
28149 foreign tools.
28150 @item
28151 @end enumerate
28153 @noindent
28154 In this section we address only cases one and two above.
28155 There is no point in trying to debug
28156 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28157 information in it. To do so you must use a debugger compatible with the
28158 tools suite used to build the DLL.
28160 @node Program and DLL Both Built with GCC/GNAT
28161 @subsection Program and DLL Both Built with GCC/GNAT
28163 @noindent
28164 This is the simplest case. Both the DLL and the program have @code{GDB}
28165 compatible debugging information. It is then possible to break anywhere in
28166 the process. Let's suppose here that the main procedure is named
28167 @code{ada_main} and that in the DLL there is an entry point named
28168 @code{ada_dll}.
28170 @noindent
28171 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28172 program must have been built with the debugging information (see GNAT -g
28173 switch). Here are the step-by-step instructions for debugging it:
28175 @enumerate 1
28176 @item Launch @code{GDB} on the main program.
28178 @smallexample
28179 $ gdb -nw ada_main
28180 @end smallexample
28182 @item Start the program and stop at the beginning of the main procedure
28184 @smallexample
28185 (gdb) start
28186 @end smallexample
28188 @noindent
28189 This step is required to be able to set a breakpoint inside the DLL. As long
28190 as the program is not run, the DLL is not loaded. This has the
28191 consequence that the DLL debugging information is also not loaded, so it is not
28192 possible to set a breakpoint in the DLL.
28194 @item Set a breakpoint inside the DLL
28196 @smallexample
28197 (gdb) break ada_dll
28198 (gdb) cont
28199 @end smallexample
28201 @end enumerate
28203 @noindent
28204 At this stage a breakpoint is set inside the DLL. From there on
28205 you can use the standard approach to debug the whole program
28206 (@pxref{Running and Debugging Ada Programs}).
28208 @ignore
28209 @c This used to work, probably because the DLLs were non-relocatable
28210 @c keep this section around until the problem is sorted out.
28212 To break on the @code{DllMain} routine it is not possible to follow
28213 the procedure above. At the time the program stop on @code{ada_main}
28214 the @code{DllMain} routine as already been called. Either you can use
28215 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28217 @enumerate 1
28218 @item Launch @code{GDB} on the main program.
28220 @smallexample
28221 $ gdb ada_main
28222 @end smallexample
28224 @item Load DLL symbols
28226 @smallexample
28227 (gdb) add-sym api.dll
28228 @end smallexample
28230 @item Set a breakpoint inside the DLL
28232 @smallexample
28233 (gdb) break ada_dll.adb:45
28234 @end smallexample
28236 Note that at this point it is not possible to break using the routine symbol
28237 directly as the program is not yet running. The solution is to break
28238 on the proper line (break in @file{ada_dll.adb} line 45).
28240 @item Start the program
28242 @smallexample
28243 (gdb) run
28244 @end smallexample
28246 @end enumerate
28247 @end ignore
28249 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28250 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28252 @menu
28253 * Debugging the DLL Directly::
28254 * Attaching to a Running Process::
28255 @end menu
28257 @noindent
28258 In this case things are slightly more complex because it is not possible to
28259 start the main program and then break at the beginning to load the DLL and the
28260 associated DLL debugging information. It is not possible to break at the
28261 beginning of the program because there is no @code{GDB} debugging information,
28262 and therefore there is no direct way of getting initial control. This
28263 section addresses this issue by describing some methods that can be used
28264 to break somewhere in the DLL to debug it.
28266 @noindent
28267 First suppose that the main procedure is named @code{main} (this is for
28268 example some C code built with Microsoft Visual C) and that there is a
28269 DLL named @code{test.dll} containing an Ada entry point named
28270 @code{ada_dll}.
28272 @noindent
28273 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28274 been built with debugging information (see GNAT -g option).
28276 @node Debugging the DLL Directly
28277 @subsubsection Debugging the DLL Directly
28279 @enumerate 1
28280 @item
28281 Find out the executable starting address
28283 @smallexample
28284 $ objdump --file-header main.exe
28285 @end smallexample
28287 The starting address is reported on the last line. For example:
28289 @smallexample
28290 main.exe:     file format pei-i386
28291 architecture: i386, flags 0x0000010a:
28292 EXEC_P, HAS_DEBUG, D_PAGED
28293 start address 0x00401010
28294 @end smallexample
28296 @item
28297 Launch the debugger on the executable.
28299 @smallexample
28300 $ gdb main.exe
28301 @end smallexample
28303 @item
28304 Set a breakpoint at the starting address, and launch the program.
28306 @smallexample
28307 $ (gdb) break *0x00401010
28308 $ (gdb) run
28309 @end smallexample
28311 The program will stop at the given address.
28313 @item
28314 Set a breakpoint on a DLL subroutine.
28316 @smallexample
28317 (gdb) break ada_dll.adb:45
28318 @end smallexample
28320 Or if you want to break using a symbol on the DLL, you need first to
28321 select the Ada language (language used by the DLL).
28323 @smallexample
28324 (gdb) set language ada
28325 (gdb) break ada_dll
28326 @end smallexample
28328 @item
28329 Continue the program.
28331 @smallexample
28332 (gdb) cont
28333 @end smallexample
28335 @noindent
28336 This will run the program until it reaches the breakpoint that has been
28337 set. From that point you can use the standard way to debug a program
28338 as described in (@pxref{Running and Debugging Ada Programs}).
28340 @end enumerate
28342 @noindent
28343 It is also possible to debug the DLL by attaching to a running process.
28345 @node Attaching to a Running Process
28346 @subsubsection Attaching to a Running Process
28347 @cindex DLL debugging, attach to process
28349 @noindent
28350 With @code{GDB} it is always possible to debug a running process by
28351 attaching to it. It is possible to debug a DLL this way. The limitation
28352 of this approach is that the DLL must run long enough to perform the
28353 attach operation. It may be useful for instance to insert a time wasting
28354 loop in the code of the DLL to meet this criterion.
28356 @enumerate 1
28358 @item Launch the main program @file{main.exe}.
28360 @smallexample
28361 $ main
28362 @end smallexample
28364 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28365 that the process PID for @file{main.exe} is 208.
28367 @item Launch gdb.
28369 @smallexample
28370 $ gdb
28371 @end smallexample
28373 @item Attach to the running process to be debugged.
28375 @smallexample
28376 (gdb) attach 208
28377 @end smallexample
28379 @item Load the process debugging information.
28381 @smallexample
28382 (gdb) symbol-file main.exe
28383 @end smallexample
28385 @item Break somewhere in the DLL.
28387 @smallexample
28388 (gdb) break ada_dll
28389 @end smallexample
28391 @item Continue process execution.
28393 @smallexample
28394 (gdb) cont
28395 @end smallexample
28397 @end enumerate
28399 @noindent
28400 This last step will resume the process execution, and stop at
28401 the breakpoint we have set. From there you can use the standard
28402 approach to debug a program as described in
28403 (@pxref{Running and Debugging Ada Programs}).
28405 @node GNAT and COM/DCOM Objects
28406 @section GNAT and COM/DCOM Objects
28407 @findex COM
28408 @findex DCOM
28410 @noindent
28411 This section is temporarily left blank.
28413 @end ifset
28415 @c **********************************
28416 @c * GNU Free Documentation License *
28417 @c **********************************
28418 @include fdl.texi
28419 @c GNU Free Documentation License
28421 @node Index,,GNU Free Documentation License, Top
28422 @unnumbered Index
28424 @printindex cp
28426 @contents
28427 @c Put table of contents at end, otherwise it precedes the "title page" in
28428 @c the .txt version
28429 @c Edit the pdf file to move the contents to the beginning, after the title
28430 @c page
28432 @bye