* config/rs6000/rs6000.md: Document why a pattern is not
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob795b2ec48b9e7ae6f52f319d990bb9e03c055d5c
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-2004 Ada Core Technologies, Inc.               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,  59 Temple Place - Suite 330,  Boston,  o
21 @c  MA 02111-1307, 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 @setfilename gnat_ugn.info
82 @ifset vms
83 @settitle GNAT User's Guide for Native Platforms / OpenVMS Alpha
84 @dircategory GNU Ada tools
85 @direntry
86 * GNAT User's Guide (gnat_ugn_vms) for Native Platforms / OpenVMS Alpha
87 @end direntry
88 @end ifset
90 @ifset unw
91 @settitle GNAT User's Guide for Native Platforms / Unix and Windows
92 @direntry
93 * GNAT User's Guide (gnat_ugn_unw) for Native Platforms / Unix and Windows
94 @end direntry
95 @end ifset
97 @include gcc-common.texi
99 @setchapternewpage odd
100 @syncodeindex fn cp
101 @c %**end of header
103 @copying
104 Copyright @copyright{} 1995-2004, Free Software Foundation
106 Permission is granted to copy, distribute and/or modify this document
107 under the terms of the GNU Free Documentation License, Version 1.2
108 or any later version published by the Free Software Foundation;
109 with the Invariant Sections being ``GNU Free Documentation License'', with the
110 Front-Cover Texts being
111 @ifset vms
112 ``GNAT User's Guide for Native Platforms / OpenVMS Alpha'',
113 @end ifset
114 @ifset unw
115 ``GNAT User's Guide for Native Platforms / Unix and Windows'',
116 @end ifset
117 and with no Back-Cover Texts.
118 A copy of the license is included in the section entitled
119 ``GNU Free Documentation License''.
120 @end copying
122 @titlepage
124 @title GNAT User's Guide
125 @center @titlefont{for Native Platforms}
126 @sp 1
128 @flushright
129 @ifset unw
130 @titlefont{@i{Unix and Windows}}
131 @end ifset
132 @ifset vms
133 @titlefont{@i{OpenVMS Alpha}}
134 @end ifset
135 @end flushright
136 @sp 2
138 @subtitle GNAT, The GNU Ada 95 Compiler
139 @subtitle GCC version @value{version-GCC}
141 @author Ada Core Technologies, Inc.
143 @page
144 @vskip 0pt plus 1filll
146 @insertcopying
148 @end titlepage
151 @ifnottex
152 @node Top, About This Guide, (dir), (dir)
153 @top GNAT User's Guide
155 @ifset vms
156 @noindent
157 GNAT User's Guide for Native Platforms / OpenVMS Alpha
158 @end ifset
160 @ifset unw
161 @noindent
162 GNAT User's Guide for Native Platforms / Unix and Windows
163 @end ifset
165 @noindent
166 GNAT, The GNU Ada 95 Compiler@*
167 GCC version @value{version-GCC}@*
169 @noindent
170 Ada Core Technologies, Inc.@*
172 @menu
173 * About This Guide::
174 * Getting Started with GNAT::
175 * The GNAT Compilation Model::
176 * Compiling Using gcc::
177 * Binding Using gnatbind::
178 * Linking Using gnatlink::
179 * The GNAT Make Program gnatmake::
180 * Improving Performance::
181 * Renaming Files Using gnatchop::
182 * Configuration Pragmas::
183 * Handling Arbitrary File Naming Conventions Using gnatname::
184 * GNAT Project Manager::
185 * The Cross-Referencing Tools gnatxref and gnatfind::
186 * The GNAT Pretty-Printer gnatpp::
187 * File Name Krunching Using gnatkr::
188 * Preprocessing Using gnatprep::
189 @ifset vms
190 * The GNAT Run-Time Library Builder gnatlbr::
191 @end ifset
192 * The GNAT Library Browser gnatls::
193 * Cleaning Up Using gnatclean::
194 @ifclear vms
195 * GNAT and Libraries::
196 * Using the GNU make Utility::
197 @end ifclear
198 * Finding Memory Problems::
199 * Creating Sample Bodies Using gnatstub::
200 * Other Utility Programs::
201 * Running and Debugging Ada Programs::
202 @ifset vms
203 * Compatibility with DEC Ada::
204 @end ifset
205 * Platform-Specific Information for the Run-Time Libraries::
206 * Example of Binder Output File::
207 * Elaboration Order Handling in GNAT::
208 * Inline Assembler::
209 * Compatibility and Porting Guide::
210 @ifset unw
211 * Microsoft Windows Topics::
212 @end ifset
213 * GNU Free Documentation License::
214 * Index::
216  --- The Detailed Node Listing ---
218 About This Guide
220 * What This Guide Contains::
221 * What You Should Know before Reading This Guide::
222 * Related Information::
223 * Conventions::
225 Getting Started with GNAT
227 * Running GNAT::
228 * Running a Simple Ada Program::
229 * Running a Program with Multiple Units::
230 * Using the gnatmake Utility::
231 @ifset vms
232 * Editing with Emacs::
233 @end ifset
234 @ifclear vms
235 * Introduction to GPS::
236 * Introduction to Glide and GVD::
237 @end ifclear
239 The GNAT Compilation Model
241 * Source Representation::
242 * Foreign Language Representation::
243 * File Naming Rules::
244 * Using Other File Names::
245 * Alternative File Naming Schemes::
246 * Generating Object Files::
247 * Source Dependencies::
248 * The Ada Library Information Files::
249 * Binding an Ada Program::
250 * Mixed Language Programming::
251 * Building Mixed Ada & C++ Programs::
252 * Comparison between GNAT and C/C++ Compilation Models::
253 * Comparison between GNAT and Conventional Ada Library Models::
254 @ifset vms
255 * Placement of temporary files::
256 @end ifset
258 Foreign Language Representation
260 * Latin-1::
261 * Other 8-Bit Codes::
262 * Wide Character Encodings::
264 Compiling Ada Programs With gcc
266 * Compiling Programs::
267 * Switches for gcc::
268 * Search Paths and the Run-Time Library (RTL)::
269 * Order of Compilation Issues::
270 * Examples::
272 Switches for gcc
274 * Output and Error Message Control::
275 * Warning Message Control::
276 * Debugging and Assertion Control::
277 * Run-Time Checks::
278 * Stack Overflow Checking::
279 * Validity Checking::
280 * Style Checking::
281 * Using gcc for Syntax Checking::
282 * Using gcc for Semantic Checking::
283 * Compiling Ada 83 Programs::
284 * Character Set Control::
285 * File Naming Control::
286 * Subprogram Inlining Control::
287 * Auxiliary Output Control::
288 * Debugging Control::
289 * Exception Handling Control::
290 * Units to Sources Mapping Files::
291 * Integrated Preprocessing::
292 @ifset vms
293 * Return Codes::
294 @end ifset
296 Binding Ada Programs With gnatbind
298 * Running gnatbind::
299 * Switches for gnatbind::
300 * Command-Line Access::
301 * Search Paths for gnatbind::
302 * Examples of gnatbind Usage::
304 Switches for gnatbind
306 * Consistency-Checking Modes::
307 * Binder Error Message Control::
308 * Elaboration Control::
309 * Output Control::
310 * Binding with Non-Ada Main Programs::
311 * Binding Programs with No Main Subprogram::
313 Linking Using gnatlink
315 * Running gnatlink::
316 * Switches for gnatlink::
317 * Setting Stack Size from gnatlink::
318 * Setting Heap Size from gnatlink::
320 The GNAT Make Program gnatmake
322 * Running gnatmake::
323 * Switches for gnatmake::
324 * Mode Switches for gnatmake::
325 * Notes on the Command Line::
326 * How gnatmake Works::
327 * Examples of gnatmake Usage::
330 Improving Performance
331 * Performance Considerations::
332 * Reducing the Size of Ada Executables with gnatelim::
334 Performance Considerations
335 * Controlling Run-Time Checks::
336 * Use of Restrictions::
337 * Optimization Levels::
338 * Debugging Optimized Code::
339 * Inlining of Subprograms::
340 * Optimization and Strict Aliasing::
341 @ifset vms
342 * Coverage Analysis::
343 @end ifset
345 Reducing the Size of Ada Executables with gnatelim
346 * About gnatelim::
347 * Running gnatelim::
348 * Correcting the List of Eliminate Pragmas::
349 * Making Your Executables Smaller::
350 * Summary of the gnatelim Usage Cycle::
352 Renaming Files Using gnatchop
354 * Handling Files with Multiple Units::
355 * Operating gnatchop in Compilation Mode::
356 * Command Line for gnatchop::
357 * Switches for gnatchop::
358 * Examples of gnatchop Usage::
360 Configuration Pragmas
362 * Handling of Configuration Pragmas::
363 * The Configuration Pragmas Files::
365 Handling Arbitrary File Naming Conventions Using gnatname
367 * Arbitrary File Naming Conventions::
368 * Running gnatname::
369 * Switches for gnatname::
370 * Examples of gnatname Usage::
372 GNAT Project Manager
374 * Introduction::
375 * Examples of Project Files::
376 * Project File Syntax::
377 * Objects and Sources in Project Files::
378 * Importing Projects::
379 * Project Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Using Third-Party Libraries through Projects::
386 * Stand-alone Library Projects::
387 * Switches Related to Project Files::
388 * Tools Supporting Project Files::
389 * An Extended Example::
390 * Project File Complete Syntax::
393 The Cross-Referencing Tools gnatxref and gnatfind
395 * gnatxref Switches::
396 * gnatfind Switches::
397 * Project Files for gnatxref and gnatfind::
398 * Regular Expressions in gnatfind and gnatxref::
399 * Examples of gnatxref Usage::
400 * Examples of gnatfind Usage::
403 The GNAT Pretty-Printer gnatpp
405 * Switches for gnatpp::
406 * Formatting Rules::
409 File Name Krunching Using gnatkr
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
416 Preprocessing Using gnatprep
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
431 The GNAT Library Browser gnatls
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
437 Cleaning Up Using gnatclean
439 * Running gnatclean::
440 * Switches for gnatclean::
441 * Examples of gnatclean Usage::
443 @ifclear vms
445 GNAT and Libraries
447 * Creating an Ada Library::
448 * Installing an Ada Library::
449 * Using an Ada Library::
450 * Creating an Ada Library to be Used in a Non-Ada Context::
451 * Rebuilding the GNAT Run-Time Library::
453 Using the GNU make Utility
455 * Using gnatmake in a Makefile::
456 * Automatically Creating a List of Directories::
457 * Generating the Command Line Switches::
458 * Overcoming Command Line Length Limits::
459 @end ifclear
461 Finding Memory Problems
463 @ifclear vms
464 * The gnatmem Tool::
465 @end ifclear
466 * The GNAT Debug Pool Facility::
468 @ifclear vms
469 The gnatmem Tool
471 * Running gnatmem::
472 * Switches for gnatmem::
473 * Example of gnatmem Usage::
474 @end ifclear
476 The GNAT Debug Pool Facility
478 Creating Sample Bodies Using gnatstub
480 * Running gnatstub::
481 * Switches for gnatstub::
483 Other Utility Programs
485 * Using Other Utility Programs with GNAT::
486 * The External Symbol Naming Scheme of GNAT::
487 @ifclear vms
488 * Ada Mode for Glide::
489 @end ifclear
490 * Converting Ada Files to html with gnathtml::
492 Running and Debugging Ada Programs
494 * The GNAT Debugger GDB::
495 * Running GDB::
496 * Introduction to GDB Commands::
497 * Using Ada Expressions::
498 * Calling User-Defined Subprograms::
499 * Using the Next Command in a Function::
500 * Ada Exceptions::
501 * Ada Tasks::
502 * Debugging Generic Units::
503 * GNAT Abnormal Termination or Failure to Terminate::
504 * Naming Conventions for GNAT Source Files::
505 * Getting Internal Debugging Information::
506 * Stack Traceback::
508 @ifset vms
509 * LSE::
510 @end ifset
512 @ifset vms
513 Compatibility with DEC Ada
515 * Ada 95 Compatibility::
516 * Differences in the Definition of Package System::
517 * Language-Related Features::
518 * The Package STANDARD::
519 * The Package SYSTEM::
520 * Tasking and Task-Related Features::
521 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
522 * Pragmas and Pragma-Related Features::
523 * Library of Predefined Units::
524 * Bindings::
525 * Main Program Definition::
526 * Implementation-Defined Attributes::
527 * Compiler and Run-Time Interfacing::
528 * Program Compilation and Library Management::
529 * Input-Output::
530 * Implementation Limits::
531 * Tools::
533 Language-Related Features
535 * Integer Types and Representations::
536 * Floating-Point Types and Representations::
537 * Pragmas Float_Representation and Long_Float::
538 * Fixed-Point Types and Representations::
539 * Record and Array Component Alignment::
540 * Address Clauses::
541 * Other Representation Clauses::
543 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
545 * Assigning Task IDs::
546 * Task IDs and Delays::
547 * Task-Related Pragmas::
548 * Scheduling and Task Priority::
549 * The Task Stack::
550 * External Interrupts::
552 Pragmas and Pragma-Related Features
554 * Restrictions on the Pragma INLINE::
555 * Restrictions on the Pragma INTERFACE::
556 * Restrictions on the Pragma SYSTEM_NAME::
558 Library of Predefined Units
560 * Changes to DECLIB::
562 Bindings
564 * Shared Libraries and Options Files::
565 * Interfaces to C::
566 @end ifset
568 Platform-Specific Information for the Run-Time Libraries
570 * Summary of Run-Time Configurations::
571 * Specifying a Run-Time Library::
572 * Choosing between Native and FSU Threads Libraries::
573 * Choosing the Scheduling Policy::
574 * Solaris-Specific Considerations::
575 * IRIX-Specific Considerations::
576 * Linux-Specific Considerations::
578 Example of Binder Output File
580 Elaboration Order Handling in GNAT
582 * Elaboration Code in Ada 95::
583 * Checking the Elaboration Order in Ada 95::
584 * Controlling the Elaboration Order in Ada 95::
585 * Controlling Elaboration in GNAT - Internal Calls::
586 * Controlling Elaboration in GNAT - External Calls::
587 * Default Behavior in GNAT - Ensuring Safety::
588 * Treatment of Pragma Elaborate::
589 * Elaboration Issues for Library Tasks::
590 * Mixing Elaboration Models::
591 * What to Do If the Default Elaboration Behavior Fails::
592 * Elaboration for Access-to-Subprogram Values::
593 * Summary of Procedures for Elaboration Control::
594 * Other Elaboration Order Considerations::
596 Inline Assembler
598 * Basic Assembler Syntax::
599 * A Simple Example of Inline Assembler::
600 * Output Variables in Inline Assembler::
601 * Input Variables in Inline Assembler::
602 * Inlining Inline Assembler Code::
603 * Other Asm Functionality::
604 * A Complete Example::
606 Compatibility and Porting Guide
608 * Compatibility with Ada 83::
609 * Implementation-dependent characteristics::
610 * Compatibility with DEC Ada 83::
611 * Compatibility with Other Ada 95 Systems::
612 * Representation Clauses::
614 @ifset unw
615 Microsoft Windows Topics
617 * Using GNAT on Windows::
618 * CONSOLE and WINDOWS subsystems::
619 * Temporary Files::
620 * Mixed-Language Programming on Windows::
621 * Windows Calling Conventions::
622 * Introduction to Dynamic Link Libraries (DLLs)::
623 * Using DLLs with GNAT::
624 * Building DLLs with GNAT::
625 * GNAT and Windows Resources::
626 * Debugging a DLL::
627 * GNAT and COM/DCOM Objects::
628 @end ifset
631 * Index::
632 @end menu
633 @end ifnottex
635 @node About This Guide
636 @unnumbered About This Guide
638 @noindent
639 @ifset vms
640 This guide describes the use of of GNAT, a full language compiler for the Ada
641 95 programming language, implemented on HP OpenVMS Alpha platforms.
642 @end ifset
643 @ifclear vms
644 This guide describes the use of GNAT, a compiler and software development
645 toolset for the full Ada 95 programming language.
646 @end ifclear
647 It describes the features of the compiler and tools, and details
648 how to use them to build Ada 95 applications.
650 @menu
651 * What This Guide Contains::
652 * What You Should Know before Reading This Guide::
653 * Related Information::
654 * Conventions::
655 @end menu
657 @node What This Guide Contains
658 @unnumberedsec What This Guide Contains
660 @noindent
661 This guide contains the following chapters:
662 @itemize @bullet
664 @item
665 @ref{Getting Started with GNAT}, describes how to get started compiling
666 and running Ada programs with the GNAT Ada programming environment.
667 @item
668 @ref{The GNAT Compilation Model}, describes the compilation model used
669 by GNAT.
671 @item
672 @ref{Compiling Using gcc}, describes how to compile
673 Ada programs with @code{gcc}, the Ada compiler.
675 @item
676 @ref{Binding Using gnatbind}, describes how to
677 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
678 utility.
680 @item
681 @ref{Linking Using gnatlink},
682 describes @code{gnatlink}, a
683 program that provides for linking using the GNAT run-time library to
684 construct a program. @code{gnatlink} can also incorporate foreign language
685 object units into the executable.
687 @item
688 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
689 utility that automatically determines the set of sources
690 needed by an Ada compilation unit, and executes the necessary compilations
691 binding and link.
693 @item
694 @ref{Improving Performance}, shows various techniques for making your
695 Ada program run faster or take less space.
696 It discusses the effect of the compiler's optimization switch and
697 also describes the @command{gnatelim} tool.
699 @item
700 @ref{Renaming Files Using gnatchop}, describes
701 @code{gnatchop}, a utility that allows you to preprocess a file that
702 contains Ada source code, and split it into one or more new files, one
703 for each compilation unit.
705 @item
706 @ref{Configuration Pragmas}, describes the configuration pragmas
707 handled by GNAT.
709 @item
710 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
711 shows how to override the default GNAT file naming conventions,
712 either for an individual unit or globally.
714 @item
715 @ref{GNAT Project Manager}, describes how to use project files
716 to organize large projects.
718 @item
719 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
720 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
721 way to navigate through sources.
723 @item
724 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
725 version of an Ada source file with control over casing, indentation,
726 comment placement, and other elements of program presentation style.
729 @item
730 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
731 file name krunching utility, used to handle shortened
732 file names on operating systems with a limit on the length of names.
734 @item
735 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
736 preprocessor utility that allows a single source file to be used to
737 generate multiple or parameterized source files, by means of macro
738 substitution.
740 @ifset vms
741 @item
742 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
743 a tool for rebuilding the GNAT run time with user-supplied
744 configuration pragmas.
745 @end ifset
747 @item
748 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
749 utility that displays information about compiled units, including dependences
750 on the corresponding sources files, and consistency of compilations.
752 @item
753 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
754 to delete files that are produced by the compiler, binder and linker.
756 @ifclear vms
757 @item
758 @ref{GNAT and Libraries}, describes the process of creating and using
759 Libraries with GNAT. It also describes how to recompile the GNAT run-time
760 library.
762 @item
763 @ref{Using the GNU make Utility}, describes some techniques for using
764 the GNAT toolset in Makefiles.
765 @end ifclear
767 @item
768 @ref{Finding Memory Problems}, describes
769 @ifclear vms
770 @command{gnatmem}, a utility that monitors dynamic allocation and deallocation
771 and helps detect ``memory leaks'', and
772 @end ifclear
773 the GNAT Debug Pool facility, which helps detect incorrect memory references.
775 @item
776 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
777 a utility that generates empty but compilable bodies for library units.
779 @item
780 @ref{Other Utility Programs}, discusses several other GNAT utilities,
781 including @code{gnathtml}.
783 @item
784 @ref{Running and Debugging Ada Programs}, describes how to run and debug
785 Ada programs.
787 @ifset vms
788 @item
789 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
790 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
791 developed by Digital Equipment Corporation and currently supported by HP.}
792 for OpenVMS Alpha.
793 @end ifset
795 @item
796 @ref{Platform-Specific Information for the Run-Time Libraries},
797 describes the various run-time
798 libraries supported by GNAT on various platforms and explains how to
799 choose a particular library.
801 @item
802 @ref{Example of Binder Output File}, shows the source code for the binder
803 output file for a sample program.
805 @item
806 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
807 you deal with elaboration order issues.
809 @item
810 @ref{Inline Assembler}, shows how to use the inline assembly facility
811 in an Ada program.
813 @item
814 @ref{Compatibility and Porting Guide}, includes sections on compatibility
815 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
816 in porting code from other environments.
818 @ifset unw
819 @item
820 @ref{Microsoft Windows Topics}, presents information relevant to the
821 Microsoft Windows platform.
822 @end ifset
823 @end itemize
826 @c *************************************************
827 @node What You Should Know before Reading This Guide
828 @c *************************************************
829 @unnumberedsec What You Should Know before Reading This Guide
831 @cindex Ada 95 Language Reference Manual
832 @noindent
833 This user's guide assumes that you are familiar with Ada 95 language, as
834 described in the International Standard ANSI/ISO/IEC-8652:1995, January
835 1995.
837 @node Related Information
838 @unnumberedsec Related Information
840 @noindent
841 For further information about related tools, refer to the following
842 documents:
844 @itemize @bullet
845 @item
846 @cite{GNAT Reference Manual}, which contains all reference
847 material for the GNAT implementation of Ada 95.
849 @ifset unw
850 @item
851 @cite{Using the GNAT Programming System}, which describes the GPS
852 integrated development environment.
854 @item
855 @cite{GNAT Programming System Tutorial}, which introduces the
856 main GPS features through examples.
857 @end ifset
859 @item
860 @cite{Ada 95 Language Reference Manual}, which contains all reference
861 material for the Ada 95 programming language.
863 @item
864 @cite{Debugging with GDB}
865 @ifset vms
866 , located in the GNU:[DOCS] directory,
867 @end ifset
868 contains all details on the use of the GNU source-level debugger.
870 @item
871 @cite{GNU Emacs Manual}
872 @ifset vms
873 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
874 @end ifset
875 contains full information on the extensible editor and programming
876 environment Emacs.
878 @end itemize
880 @c **************
881 @node Conventions
882 @unnumberedsec Conventions
883 @cindex Conventions
884 @cindex Typographical conventions
886 @noindent
887 Following are examples of the typographical and graphic conventions used
888 in this guide:
890 @itemize @bullet
891 @item
892 @code{Functions}, @code{utility program names}, @code{standard names},
893 and @code{classes}.
895 @item
896 @samp{Option flags}
898 @item
899 @file{File Names}, @file{button names}, and @file{field names}.
901 @item
902 @var{Variables}.
904 @item
905 @emph{Emphasis}.
907 @item
908 [optional information or parameters]
910 @item
911 Examples are described by text
912 @smallexample
913 and then shown this way.
914 @end smallexample
915 @end itemize
917 @noindent
918 Commands that are entered by the user are preceded in this manual by the
919 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
920 uses this sequence as a prompt, then the commands will appear exactly as
921 you see them in the manual. If your system uses some other prompt, then
922 the command will appear with the @code{$} replaced by whatever prompt
923 character you are using.
925 @ifset unw
926 Full file names are shown with the ``@code{/}'' character
927 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
928 If you are using GNAT on a Windows platform, please note that
929 the ``@code{\}'' character should be used instead.
930 @end ifset
934 @c ****************************
935 @node Getting Started with GNAT
936 @chapter Getting Started with GNAT
938 @noindent
939 This chapter describes some simple ways of using GNAT to build
940 executable Ada programs.
941 @ifset unw
942 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
943 show how to use the command line environment.
944 @ref{Introduction to Glide and GVD}, provides a brief
945 introduction to the visually-oriented IDE for GNAT.
946 Supplementing Glide on some platforms is GPS, the
947 GNAT Programming System, which offers a richer graphical
948 ``look and feel'', enhanced configurability, support for
949 development in other programming language, comprehensive
950 browsing features, and many other capabilities.
951 For information on GPS please refer to
952 @cite{Using the GNAT Programming System}.
953 @end ifset
955 @menu
956 * Running GNAT::
957 * Running a Simple Ada Program::
958 * Running a Program with Multiple Units::
959 * Using the gnatmake Utility::
960 @ifset vms
961 * Editing with Emacs::
962 @end ifset
963 @ifclear vms
964 * Introduction to GPS::
965 * Introduction to Glide and GVD::
966 @end ifclear
967 @end menu
969 @node Running GNAT
970 @section Running GNAT
972 @noindent
973 Three steps are needed to create an executable file from an Ada source
974 file:
976 @enumerate
977 @item
978 The source file(s) must be compiled.
979 @item
980 The file(s) must be bound using the GNAT binder.
981 @item
982 All appropriate object files must be linked to produce an executable.
983 @end enumerate
985 @noindent
986 All three steps are most commonly handled by using the @code{gnatmake}
987 utility program that, given the name of the main program, automatically
988 performs the necessary compilation, binding and linking steps.
991 @node Running a Simple Ada Program
992 @section Running a Simple Ada Program
994 @noindent
995 Any text editor may be used to prepare an Ada program.
996 @ifclear vms
997 If @code{Glide} is
998 used, the optional Ada mode may be helpful in laying out the program.
999 @end ifclear
1001 program text is a normal text file. We will suppose in our initial
1002 example that you have used your editor to prepare the following
1003 standard format text file:
1005 @smallexample @c ada
1006 @cartouche
1007 with Ada.Text_IO; use Ada.Text_IO;
1008 procedure Hello is
1009 begin
1010    Put_Line ("Hello WORLD!");
1011 end Hello;
1012 @end cartouche
1013 @end smallexample
1015 @noindent
1016 This file should be named @file{hello.adb}.
1017 With the normal default file naming conventions, GNAT requires
1018 that each file
1019 contain a single compilation unit whose file name is the
1020 unit name,
1021 with periods replaced by hyphens; the
1022 extension is @file{ads} for a
1023 spec and @file{adb} for a body.
1024 You can override this default file naming convention by use of the
1025 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1026 Alternatively, if you want to rename your files according to this default
1027 convention, which is probably more convenient if you will be using GNAT
1028 for all your compilations, then the @code{gnatchop} utility
1029 can be used to generate correctly-named source files
1030 (@pxref{Renaming Files Using gnatchop}).
1032 You can compile the program using the following command (@code{$} is used
1033 as the command prompt in the examples in this document):
1035 @smallexample
1036 $ gcc -c hello.adb
1037 @end smallexample
1039 @noindent
1040 @code{gcc} is the command used to run the compiler. This compiler is
1041 capable of compiling programs in several languages, including Ada 95 and
1042 C. It assumes that you have given it an Ada program if the file extension is
1043 either @file{.ads} or @file{.adb}, and it will then call
1044 the GNAT compiler to compile the specified file.
1046 @ifclear vms
1047 The @option{-c} switch is required. It tells @command{gcc} to only do a
1048 compilation. (For C programs, @command{gcc} can also do linking, but this
1049 capability is not used directly for Ada programs, so the @option{-c}
1050 switch must always be present.)
1051 @end ifclear
1053 This compile command generates a file
1054 @file{hello.o}, which is the object
1055 file corresponding to your Ada program. It also generates
1056 an ``Ada Library Information'' file @file{hello.ali},
1057 which contains additional information used to check
1058 that an Ada program is consistent.
1059 To build an executable file,
1060 use @code{gnatbind} to bind the program
1061 and @code{gnatlink} to link it. The
1062 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1063 @file{ALI} file, but the default extension of @file{.ali} can
1064 be omitted. This means that in the most common case, the argument
1065 is simply the name of the main program:
1067 @smallexample
1068 $ gnatbind hello
1069 $ gnatlink hello
1070 @end smallexample
1072 @noindent
1073 A simpler method of carrying out these steps is to use
1074 @command{gnatmake},
1075 a master program that invokes all the required
1076 compilation, binding and linking tools in the correct order. In particular,
1077 @command{gnatmake} automatically recompiles any sources that have been
1078 modified since they were last compiled, or sources that depend
1079 on such modified sources, so that ``version skew'' is avoided.
1080 @cindex Version skew (avoided by @command{gnatmake})
1082 @smallexample
1083 $ gnatmake hello.adb
1084 @end smallexample
1086 @noindent
1087 The result is an executable program called @file{hello}, which can be
1088 run by entering:
1090 @c The following should be removed (BMB 2001-01-23)
1091 @c @smallexample
1092 @c $ ^./hello^$ RUN HELLO^
1093 @c @end smallexample
1095 @smallexample
1096 $ hello
1097 @end smallexample
1099 @noindent
1100 assuming that the current directory is on the search path
1101 for executable programs.
1103 @noindent
1104 and, if all has gone well, you will see
1106 @smallexample
1107 Hello WORLD!
1108 @end smallexample
1110 @noindent
1111 appear in response to this command.
1114 @c ****************************************
1115 @node Running a Program with Multiple Units
1116 @section Running a Program with Multiple Units
1118 @noindent
1119 Consider a slightly more complicated example that has three files: a
1120 main program, and the spec and body of a package:
1122 @smallexample @c ada
1123 @cartouche
1124 @group
1125 package Greetings is
1126    procedure Hello;
1127    procedure Goodbye;
1128 end Greetings;
1130 with Ada.Text_IO; use Ada.Text_IO;
1131 package body Greetings is
1132    procedure Hello is
1133    begin
1134       Put_Line ("Hello WORLD!");
1135    end Hello;
1137    procedure Goodbye is
1138    begin
1139       Put_Line ("Goodbye WORLD!");
1140    end Goodbye;
1141 end Greetings;
1142 @end group
1144 @group
1145 with Greetings;
1146 procedure Gmain is
1147 begin
1148    Greetings.Hello;
1149    Greetings.Goodbye;
1150 end Gmain;
1151 @end group
1152 @end cartouche
1153 @end smallexample
1155 @noindent
1156 Following the one-unit-per-file rule, place this program in the
1157 following three separate files:
1159 @table @file
1160 @item greetings.ads
1161 spec of package @code{Greetings}
1163 @item greetings.adb
1164 body of package @code{Greetings}
1166 @item gmain.adb
1167 body of main program
1168 @end table
1170 @noindent
1171 To build an executable version of
1172 this program, we could use four separate steps to compile, bind, and link
1173 the program, as follows:
1175 @smallexample
1176 $ gcc -c gmain.adb
1177 $ gcc -c greetings.adb
1178 $ gnatbind gmain
1179 $ gnatlink gmain
1180 @end smallexample
1182 @noindent
1183 Note that there is no required order of compilation when using GNAT.
1184 In particular it is perfectly fine to compile the main program first.
1185 Also, it is not necessary to compile package specs in the case where
1186 there is an accompanying body; you only need to compile the body. If you want
1187 to submit these files to the compiler for semantic checking and not code
1188 generation, then use the
1189 @option{-gnatc} switch:
1191 @smallexample
1192 $ gcc -c greetings.ads -gnatc
1193 @end smallexample
1195 @noindent
1196 Although the compilation can be done in separate steps as in the
1197 above example, in practice it is almost always more convenient
1198 to use the @code{gnatmake} tool. All you need to know in this case
1199 is the name of the main program's source file. The effect of the above four
1200 commands can be achieved with a single one:
1202 @smallexample
1203 $ gnatmake gmain.adb
1204 @end smallexample
1206 @noindent
1207 In the next section we discuss the advantages of using @code{gnatmake} in
1208 more detail.
1210 @c *****************************
1211 @node Using the gnatmake Utility
1212 @section Using the @command{gnatmake} Utility
1214 @noindent
1215 If you work on a program by compiling single components at a time using
1216 @code{gcc}, you typically keep track of the units you modify. In order to
1217 build a consistent system, you compile not only these units, but also any
1218 units that depend on the units you have modified.
1219 For example, in the preceding case,
1220 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1221 you edit @file{greetings.ads}, you must recompile both
1222 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1223 units that depend on @file{greetings.ads}.
1225 @code{gnatbind} will warn you if you forget one of these compilation
1226 steps, so that it is impossible to generate an inconsistent program as a
1227 result of forgetting to do a compilation. Nevertheless it is tedious and
1228 error-prone to keep track of dependencies among units.
1229 One approach to handle the dependency-bookkeeping is to use a
1230 makefile. However, makefiles present maintenance problems of their own:
1231 if the dependencies change as you change the program, you must make
1232 sure that the makefile is kept up-to-date manually, which is also an
1233 error-prone process.
1235 The @code{gnatmake} utility takes care of these details automatically.
1236 Invoke it using either one of the following forms:
1238 @smallexample
1239 $ gnatmake gmain.adb
1240 $ gnatmake ^gmain^GMAIN^
1241 @end smallexample
1243 @noindent
1244 The argument is the name of the file containing the main program;
1245 you may omit the extension. @code{gnatmake}
1246 examines the environment, automatically recompiles any files that need
1247 recompiling, and binds and links the resulting set of object files,
1248 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1249 In a large program, it
1250 can be extremely helpful to use @code{gnatmake}, because working out by hand
1251 what needs to be recompiled can be difficult.
1253 Note that @code{gnatmake}
1254 takes into account all the Ada 95 rules that
1255 establish dependencies among units. These include dependencies that result
1256 from inlining subprogram bodies, and from
1257 generic instantiation. Unlike some other
1258 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1259 found by the compiler on a previous compilation, which may possibly
1260 be wrong when sources change. @code{gnatmake} determines the exact set of
1261 dependencies from scratch each time it is run.
1263 @ifset vms
1264 @node Editing with Emacs
1265 @section Editing with Emacs
1266 @cindex Emacs
1268 @noindent
1269 Emacs is an extensible self-documenting text editor that is available in a
1270 separate VMSINSTAL kit.
1272 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1273 click on the Emacs Help menu and run the Emacs Tutorial.
1274 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1275 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1277 Documentation on Emacs and other tools is available in Emacs under the
1278 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1279 use the middle mouse button to select a topic (e.g. Emacs).
1281 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1282 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1283 get to the Emacs manual.
1284 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1285 prompt.
1287 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1288 which is sufficiently extensible to provide for a complete programming
1289 environment and shell for the sophisticated user.
1290 @end ifset
1292 @ifclear vms
1293 @node Introduction to GPS
1294 @section Introduction to GPS
1295 @cindex GPS (GNAT Programming System)
1296 @cindex GNAT Programming System (GPS)
1297 @noindent
1298 Although the command line interface (@command{gnatmake}, etc.) alone
1299 is sufficient, a graphical Interactive Development
1300 Environment can make it easier for you to compose, navigate, and debug
1301 programs.  This section describes the main features of GPS
1302 (``GNAT Programming System''), the GNAT graphical IDE.
1303 You will see how to use GPS to build and debug an executable, and
1304 you will also learn some of the basics of the GNAT ``project'' facility.
1306 GPS enables you to do much more than is presented here;
1307 e.g., you can produce a call graph, interface to a third-party
1308 Version Control System, and inspect the generated assembly language
1309 for a program.
1310 Indeed, GPS also supports languages other than Ada.
1311 Such additional information, and an explanation of all of the GPS menu
1312 items. may be found in the on-line help, which includes
1313 a user's guide and a tutorial (these are also accessible from the GNAT
1314 startup menu).
1316 @menu
1317 * Building a New Program with GPS::
1318 * Simple Debugging with GPS::
1319 @end menu
1322 @node Building a New Program with GPS
1323 @subsection Building a New Program with GPS
1324 @noindent
1325 GPS invokes the GNAT compilation tools using information
1326 contained in a @emph{project} (also known as a @emph{project file}):
1327 a collection of properties such
1328 as source directories, identities of main subprograms, tool switches, etc.,
1329 and their associated values.
1330 (See @ref{GNAT Project Manager}, for details.)
1331 In order to run GPS, you will need to either create a new project
1332 or else open an existing one.
1334 This section will explain how you can use GPS to create a project,
1335 to associate Ada source files with a project, and to build and run
1336 programs.
1338 @enumerate
1339 @item @emph{Creating a project}
1341 Invoke GPS, either from the command line or the platform's IDE.
1342 After it starts, GPS will display a ``Welcome'' screen with three
1343 radio buttons:
1345 @itemize @bullet
1346 @item
1347 @code{Start with default project in directory}
1349 @item
1350 @code{Create new project with wizard}
1352 @item
1353 @code{Open existing project}
1354 @end itemize
1356 @noindent
1357 Select @code{Create new project with wizard} and press @code{OK}.
1358 A new window will appear.  In the text box labeled with
1359 @code{Enter the name of the project to create}, type @file{sample}
1360 as the project name.
1361 In the next box, browse to choose the directory in which you
1362 would like to create the project file.
1363 After selecting an appropriate directory, press @code{Forward}.
1365 A window will appear with the title
1366 @code{Version Control System Configuration}.
1367 Simply press @code{Forward}.
1369 A window will appear with the title
1370 @code{Please select the source directories for this project}.
1371 The directory that you specified for the project file will be selected
1372 by default as the one to use for sources; simply press @code{Forward}.
1374 A window will appear with the title
1375 @code{Please select the build directory for this project}.
1376 The directory that you specified for the project file will be selected
1377 by default for object files and executables;
1378 simply press @code{Forward}.
1380 A window will appear with the title
1381 @code{Please select the main units for this project}.
1382 You will supply this information later, after creating the source file.
1383 Simply press @code{Forward} for now.
1385 A window will appear with the title
1386 @code{Please select the switches to build the project}.
1387 Press @code{Apply}.  This will create a project file named
1388 @file{sample.prj} in the directory that you had specified.
1390 @item @emph{Creating and saving the source file}
1392 After you create the new project, a GPS window will appear, which is
1393 partitioned into two main sections:
1395 @itemize @bullet
1396 @item
1397 A @emph{Workspace area}, initially greyed out, which you will use for
1398 creating and editing source files
1400 @item
1401 Directly below, a @emph{Messages area}, which initially displays a
1402 ``Welcome'' message.
1403 (If the Messages area is not visible, drag its border upward to expand it.)
1404 @end itemize
1406 @noindent
1407 Select @code{File} on the menu bar, and then the @code{New} command.
1408 The Workspace area will become white, and you can now
1409 enter the source program explicitly.
1410 Type the following text
1412 @smallexample @c ada
1413 @group
1414 with Ada.Text_IO; use Ada.Text_IO;
1415 procedure Hello is
1416 begin
1417   Put_Line("Hello from GPS!");
1418 end Hello;
1419 @end group
1420 @end smallexample
1422 @noindent
1423 Select @code{File}, then @code{Save As}, and enter the source file name
1424 @file{hello.adb}.
1425 The file will be saved in the same directory you specified as the
1426 location of the default project file.
1429 @item @emph{Updating the project file}
1431 You need to add the new source file to the project.
1432 To do this, select
1433 the @code{Project} menu and then @code{Edit project properties}.
1434 Click the @code{Main files} tab on the left, and then the
1435 @code{Add} button.
1436 Choose @file{hello.adb} from the list, and press @code{Open}.
1437 The project settings window will reflect this action.
1438 Click @code{OK}.
1440 @item @emph{Building and running the program}
1442 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1443 and select @file{hello.adb}.
1444 The Messages window will display the resulting invocations of @command{gcc},
1445 @command{gnatbind}, and @command{gnatlink}
1446 (reflecting the default switch settings from the
1447 project file that you created) and then a ``successful compilation/build''
1448 message.
1450 To run the program, choose the @code{Build} menu, then @code{Run}, and
1451 select @command{hello}.
1452 An @emph{Arguments Selection} window will appear.
1453 There are no command line arguments, so just click @code{OK}.
1455 The Messages window will now display the program's output (the string
1456 @code{Hello from GPS}), and at the bottom of the GPS window a status
1457 update is displayed (@code{Run: hello}).
1458 Close the GPS window (or select @code{File}, then @code{Exit}) to
1459 terminate this GPS session.
1460 @end enumerate
1464 @node Simple Debugging with GPS
1465 @subsection Simple Debugging with GPS
1466 @noindent
1467 This section illustrates basic debugging techniques (setting breakpoints,
1468 examining/modifying variables, single stepping).
1470 @enumerate
1471 @item @emph{Opening a project}
1473 Start GPS and select @code{Open existing project}; browse to
1474 specify the project file @file{sample.prj} that you had created in the
1475 earlier example.
1477 @item @emph{Creating a source file}
1479 Select @code{File}, then @code{New}, and type in the following program:
1481 @smallexample @c ada
1482 @group
1483 with Ada.Text_IO; use Ada.Text_IO;
1484 procedure Example is
1485    Line : String (1..80);
1486    N    : Natural;
1487 begin
1488    Put_Line("Type a line of text at each prompt; an empty line to exit");
1489    loop
1490       Put(": ");
1491       Get_Line (Line, N);
1492       Put_Line (Line (1..N) );
1493       exit when N=0;
1494    end loop;
1495 end Example;
1496 @end group
1497 @end smallexample
1499 @noindent
1500 Select @code{File}, then @code{Save as}, and enter the file name
1501 @file{example.adb}.
1503 @item @emph{Updating the project file}
1505 Add @code{Example} as a new main unit for the project:
1506 @enumerate a
1507 @item
1508 Select @code{Project}, then @code{Edit Project Properties}.
1510 @item
1511 Select the @code{Main files} tab, click @code{Add}, then
1512 select the file @file{example.adb} from the list, and
1513 click @code{Open}.
1514 You will see the file name appear in the list of main units
1516 @item
1517 Click @code{OK}
1518 @end enumerate
1520 @item @emph{Building/running the executable}
1522 To build the executable
1523 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1525 Run the program to see its effect (in the Messages area).
1526 Each line that you enter is displayed; an empty line will
1527 cause the loop to exit and the program to terminate.
1529 @item @emph{Debugging the program}
1531 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1532 which are required for debugging, are on by default when you create
1533 a new project.
1534 Thus unless you intentionally remove these settings, you will be able
1535 to debug any program that you develop using GPS.
1537 @enumerate a
1538 @item @emph{Initializing}
1540 Select @code{Debug}, then @code{Initialize}, then @file{example}
1542 @item @emph{Setting a breakpoint}
1544 After performing the initialization step, you will observe a small
1545 icon to the right of each line number.
1546 This serves as a toggle for breakpoints; clicking the icon will
1547 set a breakpoint at the corresponding line (the icon will change to
1548 a red circle with an ``x''), and clicking it again
1549 will remove the breakpoint / reset the icon.
1551 For purposes of this example, set a breakpoint at line 10 (the
1552 statement @code{Put_Line@ (Line@ (1..N));}
1554 @item @emph{Starting program execution}
1556 Select @code{Debug}, then @code{Run}.  When the
1557 @code{Program Arguments} window appears, click @code{OK}.
1558 A console window will appear; enter some line of text,
1559 e.g. @code{abcde}, at the prompt.
1560 The program will pause execution when it gets to the
1561 breakpoint, and the corresponding line is highlighted.
1563 @item @emph{Examining a variable}
1565 Move the mouse over one of the occurrences of the variable @code{N}.
1566 You will see the value (5) displayed, in ``tool tip'' fashion.
1567 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1568 You will see information about @code{N} appear in the @code{Debugger Data}
1569 pane, showing the value as 5.
1572 @item @emph{Assigning a new value to a variable}
1574 Right click on the @code{N} in the @code{Debugger Data} pane, and
1575 select @code{Set value of N}.
1576 When the input window appears, enter the value @code{4} and click
1577 @code{OK}.
1578 This value does not automatically appear in the @code{Debugger Data}
1579 pane; to see it, right click again on the @code{N} in the
1580 @code{Debugger Data} pane and select @code{Update value}.
1581 The new value, 4, will appear in red.
1583 @item @emph{Single stepping}
1585 Select @code{Debug}, then @code{Next}.
1586 This will cause the next statement to be executed, in this case the
1587 call of @code{Put_Line} with the string slice.
1588 Notice in the console window that the displayed string is simply
1589 @code{abcd} and not @code{abcde} which you had entered.
1590 This is because the upper bound of the slice is now 4 rather than 5.
1592 @item @emph{Removing a breakpoint}
1594 Toggle the breakpoint icon at line 10.
1596 @item @emph{Resuming execution from a breakpoint}
1598 Select @code{Debug}, then @code{Continue}.
1599 The program will reach the next iteration of the loop, and
1600 wait for input after displaying the prompt.
1601 This time, just hit the @kbd{Enter} key.
1602 The value of @code{N} will be 0, and the program will terminate.
1603 The console window will disappear.
1604 @end enumerate
1605 @end enumerate
1608 @node Introduction to Glide and GVD
1609 @section Introduction to Glide and GVD
1610 @cindex Glide
1611 @cindex GVD
1612 @noindent
1613 This section describes the main features of Glide,
1614 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1615 the GNU Visual Debugger.
1616 These tools may be present in addition to, or in place of, GPS on some
1617 platforms.
1618 Additional information on Glide and GVD may be found
1619 in the on-line help for these tools.
1621 @menu
1622 * Building a New Program with Glide::
1623 * Simple Debugging with GVD::
1624 * Other Glide Features::
1625 @end menu
1627 @node Building a New Program with Glide
1628 @subsection Building a New Program with Glide
1629 @noindent
1630 The simplest way to invoke Glide is to enter @command{glide}
1631 at the command prompt.  It will generally be useful to issue this
1632 as a background command, thus allowing you to continue using
1633 your command window for other purposes while Glide is running:
1635 @smallexample
1636 $ glide&
1637 @end smallexample
1639 @noindent
1640 Glide will start up with an initial screen displaying the top-level menu items
1641 as well as some other information.  The menu selections are as follows
1642 @itemize @bullet
1643 @item @code{Buffers}
1644 @item @code{Files}
1645 @item @code{Tools}
1646 @item @code{Edit}
1647 @item @code{Search}
1648 @item @code{Mule}
1649 @item @code{Glide}
1650 @item @code{Help}
1651 @end itemize
1653 @noindent
1654 For this introductory example, you will need to create a new Ada source file.
1655 First, select the @code{Files} menu.  This will pop open a menu with around
1656 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1657 Depending on the platform, you may see a pop-up window where you can browse
1658 to an appropriate directory and then enter the file name, or else simply
1659 see a line at the bottom of the Glide window where you can likewise enter
1660 the file name.  Note that in Glide, when you attempt to open a non-existent
1661 file, the effect is to create a file with that name.  For this example enter
1662 @file{hello.adb} as the name of the file.
1664 A new buffer will now appear, occupying the entire Glide window,
1665 with the file name at the top.  The menu selections are slightly different
1666 from the ones you saw on the opening screen; there is an @code{Entities} item,
1667 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1668 the file extension to identify the source language, so @file{adb} indicates
1669 an Ada source file.
1671 You will enter some of the source program lines explicitly,
1672 and use the syntax-oriented template mechanism to enter other lines.
1673 First, type the following text:
1674 @smallexample
1675 with Ada.Text_IO; use Ada.Text_IO;
1676 procedure Hello is
1677 begin
1678 @end smallexample
1680 @noindent
1681 Observe that Glide uses different colors to distinguish reserved words from
1682 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1683 automatically indented in anticipation of declarations.  When you enter
1684 @code{begin}, Glide recognizes that there are no declarations and thus places
1685 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1686 indented, where the statement(s) will be placed.
1688 The main part of the program will be a @code{for} loop.  Instead of entering
1689 the text explicitly, however, use a statement template.  Select the @code{Ada}
1690 item on the top menu bar, move the mouse to the @code{Statements} item,
1691 and you will see a large selection of alternatives.  Choose @code{for loop}.
1692 You will be prompted (at the bottom of the buffer) for a loop name;
1693 simply press the @key{Enter} key since a loop name is not needed.
1694 You should see the beginning of a @code{for} loop appear in the source
1695 program window.  You will now be prompted for the name of the loop variable;
1696 enter a line with the identifier @code{ind} (lower case).  Note that,
1697 by default, Glide capitalizes the name (you can override such behavior
1698 if you wish, although this is outside the scope of this introduction).
1699 Next, Glide prompts you for the loop range; enter a line containing
1700 @code{1..5} and you will see this also appear in the source program,
1701 together with the remaining elements of the @code{for} loop syntax.
1703 Next enter the statement (with an intentional error, a missing semicolon)
1704 that will form the body of the loop:
1705 @smallexample
1706 Put_Line("Hello, World" & Integer'Image(I))
1707 @end smallexample
1709 @noindent
1710 Finally, type @code{end Hello;} as the last line in the program.
1711 Now save the file: choose the @code{File} menu item, and then the
1712 @code{Save buffer} selection.  You will see a message at the bottom
1713 of the buffer confirming that the file has been saved.
1715 You are now ready to attempt to build the program.  Select the @code{Ada}
1716 item from the top menu bar.  Although we could choose simply to compile
1717 the file, we will instead attempt to do a build (which invokes
1718 @command{gnatmake}) since, if the compile is successful, we want to build
1719 an executable.  Thus select @code{Ada build}.  This will fail because of the
1720 compilation error, and you will notice that the Glide window has been split:
1721 the top window contains the source file, and the bottom window contains the
1722 output from the GNAT tools. Glide allows you to navigate from a compilation
1723 error to the source file position corresponding to the error: click the
1724 middle mouse button (or simultaneously press the left and right buttons,
1725 on a two-button mouse) on the diagnostic line in the tool window.  The
1726 focus will shift to the source window, and the cursor will be positioned
1727 on the character at which the error was detected.
1729 Correct the error: type in a semicolon to terminate the statement.
1730 Although you can again save the file explicitly, you can also simply invoke
1731 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1732 This time the build will succeed; the tool output window shows you the
1733 options that are supplied by default.  The GNAT tools' output (e.g.
1734 object and ALI files, executable) will go in the directory from which
1735 Glide was launched.
1737 To execute the program, choose @code{Ada} and then @code{Run}.
1738 You should see the program's output displayed in the bottom window:
1740 @smallexample
1741 Hello, world 1
1742 Hello, world 2
1743 Hello, world 3
1744 Hello, world 4
1745 Hello, world 5
1746 @end smallexample
1748 @node Simple Debugging with GVD
1749 @subsection Simple Debugging with GVD
1751 @noindent
1752 This section describes how to set breakpoints, examine/modify variables,
1753 and step through execution.
1755 In order to enable debugging, you need to pass the @option{-g} switch
1756 to both the compiler and to @command{gnatlink}.  If you are using
1757 the command line, passing @option{-g} to @command{gnatmake} will have
1758 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1759 by issuing the command:
1761 @smallexample
1762 $ gvd hello
1763 @end smallexample
1765 @noindent
1766 If you are using Glide, then @option{-g} is passed to the relevant tools
1767 by default when you do a build.  Start the debugger by selecting the
1768 @code{Ada} menu item, and then @code{Debug}.
1770 GVD comes up in a multi-part window.  One pane shows the names of files
1771 comprising your executable; another pane shows the source code of the current
1772 unit (initially your main subprogram), another pane shows the debugger output
1773 and user interactions, and the fourth pane (the data canvas at the top
1774 of the window) displays data objects that you have selected.
1776 To the left of the source file pane, you will notice green dots adjacent
1777 to some lines.  These are lines for which object code exists and where
1778 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1779 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1780 in a red circle.  Clicking the circle toggles the breakpoint off,
1781 and the red circle is replaced by the green dot.
1783 For this example, set a breakpoint at the statement where @code{Put_Line}
1784 is invoked.
1786 Start program execution by selecting the @code{Run} button on the top menu bar.
1787 (The @code{Start} button will also start your program, but it will
1788 cause program execution to break at the entry to your main subprogram.)
1789 Evidence of reaching the breakpoint will appear: the source file line will be
1790 highlighted, and the debugger interactions pane will display
1791 a relevant message.
1793 You can examine the values of variables in several ways.  Move the mouse
1794 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1795 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1796 and select @code{Display Ind}; a box showing the variable's name and value
1797 will appear in the data canvas.
1799 Although a loop index is a constant with respect to Ada semantics,
1800 you can change its value in the debugger.  Right-click in the box
1801 for @code{Ind}, and select the @code{Set Value of Ind} item.
1802 Enter @code{2} as the new value, and press @command{OK}.
1803 The box for @code{Ind} shows the update.
1805 Press the @code{Step} button on the top menu bar; this will step through
1806 one line of program text (the invocation of @code{Put_Line}), and you can
1807 observe the effect of having modified @code{Ind} since the value displayed
1808 is @code{2}.
1810 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1811 button.  You will see the remaining output lines displayed in the debugger
1812 interaction window, along with a message confirming normal program
1813 termination.
1815 @node Other Glide Features
1816 @subsection Other Glide Features
1818 @noindent
1819 You may have observed that some of the menu selections contain abbreviations;
1820 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1821 These are @emph{shortcut keys} that you can use instead of selecting
1822 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1823 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1824 of selecting @code{Files} and then @code{Open file...}.
1826 To abort a Glide command, type @key{Ctrl-g}.
1828 If you want Glide to start with an existing source file, you can either
1829 launch Glide as above and then open the file via @code{Files} @result{}
1830 @code{Open file...}, or else simply pass the name of the source file
1831 on the command line:
1833 @smallexample
1834 $ glide hello.adb&
1835 @end smallexample
1837 @noindent
1838 While you are using Glide, a number of @emph{buffers} exist.
1839 You create some explicitly; e.g., when you open/create a file.
1840 Others arise as an effect of the commands that you issue; e.g., the buffer
1841 containing the output of the tools invoked during a build.  If a buffer
1842 is hidden, you can bring it into a visible window by first opening
1843 the @code{Buffers} menu and then selecting the desired entry.
1845 If a buffer occupies only part of the Glide screen and you want to expand it
1846 to fill the entire screen, then click in the buffer and then select
1847 @code{Files} @result{} @code{One Window}.
1849 If a window is occupied by one buffer and you want to split the window
1850 to bring up a second buffer, perform the following steps:
1851 @itemize @bullet
1852 @item Select @code{Files} @result{} @code{Split Window};
1853 this will produce two windows each of which holds the original buffer
1854 (these are not copies, but rather different views of the same buffer contents)
1856 @item With the focus in one of the windows,
1857 select the desired buffer from the @code{Buffers} menu
1858 @end itemize
1860 @noindent
1861 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1862 @end ifclear
1864 @node The GNAT Compilation Model
1865 @chapter The GNAT Compilation Model
1866 @cindex GNAT compilation model
1867 @cindex Compilation model
1869 @menu
1870 * Source Representation::
1871 * Foreign Language Representation::
1872 * File Naming Rules::
1873 * Using Other File Names::
1874 * Alternative File Naming Schemes::
1875 * Generating Object Files::
1876 * Source Dependencies::
1877 * The Ada Library Information Files::
1878 * Binding an Ada Program::
1879 * Mixed Language Programming::
1880 * Building Mixed Ada & C++ Programs::
1881 * Comparison between GNAT and C/C++ Compilation Models::
1882 * Comparison between GNAT and Conventional Ada Library Models::
1883 @ifset vms
1884 * Placement of temporary files::
1885 @end ifset
1886 @end menu
1888 @noindent
1889 This chapter describes the compilation model used by GNAT. Although
1890 similar to that used by other languages, such as C and C++, this model
1891 is substantially different from the traditional Ada compilation models,
1892 which are based on a library. The model is initially described without
1893 reference to the library-based model. If you have not previously used an
1894 Ada compiler, you need only read the first part of this chapter. The
1895 last section describes and discusses the differences between the GNAT
1896 model and the traditional Ada compiler models. If you have used other
1897 Ada compilers, this section will help you to understand those
1898 differences, and the advantages of the GNAT model.
1900 @node Source Representation
1901 @section Source Representation
1902 @cindex Latin-1
1904 @noindent
1905 Ada source programs are represented in standard text files, using
1906 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1907 7-bit ASCII set, plus additional characters used for
1908 representing foreign languages (@pxref{Foreign Language Representation}
1909 for support of non-USA character sets). The format effector characters
1910 are represented using their standard ASCII encodings, as follows:
1912 @table @code
1913 @item VT
1914 @findex VT
1915 Vertical tab, @code{16#0B#}
1917 @item HT
1918 @findex HT
1919 Horizontal tab, @code{16#09#}
1921 @item CR
1922 @findex CR
1923 Carriage return, @code{16#0D#}
1925 @item LF
1926 @findex LF
1927 Line feed, @code{16#0A#}
1929 @item FF
1930 @findex FF
1931 Form feed, @code{16#0C#}
1932 @end table
1934 @noindent
1935 Source files are in standard text file format. In addition, GNAT will
1936 recognize a wide variety of stream formats, in which the end of physical
1937 physical lines is marked by any of the following sequences:
1938 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1939 in accommodating files that are imported from other operating systems.
1941 @cindex End of source file
1942 @cindex Source file, end
1943 @findex SUB
1944 The end of a source file is normally represented by the physical end of
1945 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1946 recognized as signalling the end of the source file. Again, this is
1947 provided for compatibility with other operating systems where this
1948 code is used to represent the end of file.
1950 Each file contains a single Ada compilation unit, including any pragmas
1951 associated with the unit. For example, this means you must place a
1952 package declaration (a package @dfn{spec}) and the corresponding body in
1953 separate files. An Ada @dfn{compilation} (which is a sequence of
1954 compilation units) is represented using a sequence of files. Similarly,
1955 you will place each subunit or child unit in a separate file.
1957 @node Foreign Language Representation
1958 @section Foreign Language Representation
1960 @noindent
1961 GNAT supports the standard character sets defined in Ada 95 as well as
1962 several other non-standard character sets for use in localized versions
1963 of the compiler (@pxref{Character Set Control}).
1964 @menu
1965 * Latin-1::
1966 * Other 8-Bit Codes::
1967 * Wide Character Encodings::
1968 @end menu
1970 @node Latin-1
1971 @subsection Latin-1
1972 @cindex Latin-1
1974 @noindent
1975 The basic character set is Latin-1. This character set is defined by ISO
1976 standard 8859, part 1. The lower half (character codes @code{16#00#}
1977 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1978 is used to represent additional characters. These include extended letters
1979 used by European languages, such as French accents, the vowels with umlauts
1980 used in German, and the extra letter A-ring used in Swedish.
1982 @findex Ada.Characters.Latin_1
1983 For a complete list of Latin-1 codes and their encodings, see the source
1984 file of library unit @code{Ada.Characters.Latin_1} in file
1985 @file{a-chlat1.ads}.
1986 You may use any of these extended characters freely in character or
1987 string literals. In addition, the extended characters that represent
1988 letters can be used in identifiers.
1990 @node Other 8-Bit Codes
1991 @subsection Other 8-Bit Codes
1993 @noindent
1994 GNAT also supports several other 8-bit coding schemes:
1996 @table @asis
1997 @item ISO 8859-2 (Latin-2)
1998 @cindex Latin-2
1999 @cindex ISO 8859-2
2000 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2001 equivalence.
2003 @item ISO 8859-3 (Latin-3)
2004 @cindex Latin-3
2005 @cindex ISO 8859-3
2006 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2007 equivalence.
2009 @item ISO 8859-4 (Latin-4)
2010 @cindex Latin-4
2011 @cindex ISO 8859-4
2012 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2013 equivalence.
2015 @item ISO 8859-5 (Cyrillic)
2016 @cindex ISO 8859-5
2017 @cindex Cyrillic
2018 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2019 lowercase equivalence.
2021 @item ISO 8859-15 (Latin-9)
2022 @cindex ISO 8859-15
2023 @cindex Latin-9
2024 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2025 lowercase equivalence
2027 @item IBM PC (code page 437)
2028 @cindex code page 437
2029 This code page is the normal default for PCs in the U.S. It corresponds
2030 to the original IBM PC character set. This set has some, but not all, of
2031 the extended Latin-1 letters, but these letters do not have the same
2032 encoding as Latin-1. In this mode, these letters are allowed in
2033 identifiers with uppercase and lowercase equivalence.
2035 @item IBM PC (code page 850)
2036 @cindex code page 850
2037 This code page is a modification of 437 extended to include all the
2038 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2039 mode, all these letters are allowed in identifiers with uppercase and
2040 lowercase equivalence.
2042 @item Full Upper 8-bit
2043 Any character in the range 80-FF allowed in identifiers, and all are
2044 considered distinct. In other words, there are no uppercase and lowercase
2045 equivalences in this range. This is useful in conjunction with
2046 certain encoding schemes used for some foreign character sets (e.g.
2047 the typical method of representing Chinese characters on the PC).
2049 @item No Upper-Half
2050 No upper-half characters in the range 80-FF are allowed in identifiers.
2051 This gives Ada 83 compatibility for identifier names.
2052 @end table
2054 @noindent
2055 For precise data on the encodings permitted, and the uppercase and lowercase
2056 equivalences that are recognized, see the file @file{csets.adb} in
2057 the GNAT compiler sources. You will need to obtain a full source release
2058 of GNAT to obtain this file.
2060 @node Wide Character Encodings
2061 @subsection Wide Character Encodings
2063 @noindent
2064 GNAT allows wide character codes to appear in character and string
2065 literals, and also optionally in identifiers, by means of the following
2066 possible encoding schemes:
2068 @table @asis
2070 @item Hex Coding
2071 In this encoding, a wide character is represented by the following five
2072 character sequence:
2074 @smallexample
2075 ESC a b c d
2076 @end smallexample
2078 @noindent
2079 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2080 characters (using uppercase letters) of the wide character code. For
2081 example, ESC A345 is used to represent the wide character with code
2082 @code{16#A345#}.
2083 This scheme is compatible with use of the full Wide_Character set.
2085 @item Upper-Half Coding
2086 @cindex Upper-Half Coding
2087 The wide character with encoding @code{16#abcd#} where the upper bit is on
2088 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2089 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2090 character, but is not required to be in the upper half. This method can
2091 be also used for shift-JIS or EUC, where the internal coding matches the
2092 external coding.
2094 @item Shift JIS Coding
2095 @cindex Shift JIS Coding
2096 A wide character is represented by a two-character sequence,
2097 @code{16#ab#} and
2098 @code{16#cd#}, with the restrictions described for upper-half encoding as
2099 described above. The internal character code is the corresponding JIS
2100 character according to the standard algorithm for Shift-JIS
2101 conversion. Only characters defined in the JIS code set table can be
2102 used with this encoding method.
2104 @item EUC Coding
2105 @cindex EUC Coding
2106 A wide character is represented by a two-character sequence
2107 @code{16#ab#} and
2108 @code{16#cd#}, with both characters being in the upper half. The internal
2109 character code is the corresponding JIS character according to the EUC
2110 encoding algorithm. Only characters defined in the JIS code set table
2111 can be used with this encoding method.
2113 @item UTF-8 Coding
2114 A wide character is represented using
2115 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2116 10646-1/Am.2. Depending on the character value, the representation
2117 is a one, two, or three byte sequence:
2118 @smallexample
2119 @iftex
2120 @leftskip=.7cm
2121 @end iftex
2122 16#0000#-16#007f#: 2#0xxxxxxx#
2123 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2124 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2126 @end smallexample
2128 @noindent
2129 where the xxx bits correspond to the left-padded bits of the
2130 16-bit character value. Note that all lower half ASCII characters
2131 are represented as ASCII bytes and all upper half characters and
2132 other wide characters are represented as sequences of upper-half
2133 (The full UTF-8 scheme allows for encoding 31-bit characters as
2134 6-byte sequences, but in this implementation, all UTF-8 sequences
2135 of four or more bytes length will be treated as illegal).
2136 @item Brackets Coding
2137 In this encoding, a wide character is represented by the following eight
2138 character sequence:
2140 @smallexample
2141 [ " a b c d " ]
2142 @end smallexample
2144 @noindent
2145 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2146 characters (using uppercase letters) of the wide character code. For
2147 example, [``A345''] is used to represent the wide character with code
2148 @code{16#A345#}. It is also possible (though not required) to use the
2149 Brackets coding for upper half characters. For example, the code
2150 @code{16#A3#} can be represented as @code{[``A3'']}.
2152 This scheme is compatible with use of the full Wide_Character set,
2153 and is also the method used for wide character encoding in the standard
2154 ACVC (Ada Compiler Validation Capability) test suite distributions.
2156 @end table
2158 @noindent
2159 Note: Some of these coding schemes do not permit the full use of the
2160 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2161 use of the upper half of the Latin-1 set.
2163 @node File Naming Rules
2164 @section File Naming Rules
2166 @noindent
2167 The default file name is determined by the name of the unit that the
2168 file contains. The name is formed by taking the full expanded name of
2169 the unit and replacing the separating dots with hyphens and using
2170 ^lowercase^uppercase^ for all letters.
2172 An exception arises if the file name generated by the above rules starts
2173 with one of the characters
2174 @ifset vms
2175 A,G,I, or S,
2176 @end ifset
2177 @ifclear vms
2178 a,g,i, or s,
2179 @end ifclear
2180 and the second character is a
2181 minus. In this case, the character ^tilde^dollar sign^ is used in place
2182 of the minus. The reason for this special rule is to avoid clashes with
2183 the standard names for child units of the packages System, Ada,
2184 Interfaces, and GNAT, which use the prefixes
2185 @ifset vms
2186 S- A- I- and G-
2187 @end ifset
2188 @ifclear vms
2189 s- a- i- and g-
2190 @end ifclear
2191 respectively.
2193 The file extension is @file{.ads} for a spec and
2194 @file{.adb} for a body. The following list shows some
2195 examples of these rules.
2197 @table @file
2198 @item main.ads
2199 Main (spec)
2200 @item main.adb
2201 Main (body)
2202 @item arith_functions.ads
2203 Arith_Functions (package spec)
2204 @item arith_functions.adb
2205 Arith_Functions (package body)
2206 @item func-spec.ads
2207 Func.Spec (child package spec)
2208 @item func-spec.adb
2209 Func.Spec (child package body)
2210 @item main-sub.adb
2211 Sub (subunit of Main)
2212 @item ^a~bad.adb^A$BAD.ADB^
2213 A.Bad (child package body)
2214 @end table
2216 @noindent
2217 Following these rules can result in excessively long
2218 file names if corresponding
2219 unit names are long (for example, if child units or subunits are
2220 heavily nested). An option is available to shorten such long file names
2221 (called file name ``krunching''). This may be particularly useful when
2222 programs being developed with GNAT are to be used on operating systems
2223 with limited file name lengths. @xref{Using gnatkr}.
2225 Of course, no file shortening algorithm can guarantee uniqueness over
2226 all possible unit names; if file name krunching is used, it is your
2227 responsibility to ensure no name clashes occur. Alternatively you
2228 can specify the exact file names that you want used, as described
2229 in the next section. Finally, if your Ada programs are migrating from a
2230 compiler with a different naming convention, you can use the gnatchop
2231 utility to produce source files that follow the GNAT naming conventions.
2232 (For details @pxref{Renaming Files Using gnatchop}.)
2234 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2235 systems, case is not significant. So for example on @code{Windows XP}
2236 if the canonical name is @code{main-sub.adb}, you can use the file name
2237 @code{Main-Sub.adb} instead. However, case is significant for other
2238 operating systems, so for example, if you want to use other than
2239 canonically cased file names on a Unix system, you need to follow
2240 the procedures described in the next section.
2242 @node Using Other File Names
2243 @section Using Other File Names
2244 @cindex File names
2246 @noindent
2247 In the previous section, we have described the default rules used by
2248 GNAT to determine the file name in which a given unit resides. It is
2249 often convenient to follow these default rules, and if you follow them,
2250 the compiler knows without being explicitly told where to find all
2251 the files it needs.
2253 However, in some cases, particularly when a program is imported from
2254 another Ada compiler environment, it may be more convenient for the
2255 programmer to specify which file names contain which units. GNAT allows
2256 arbitrary file names to be used by means of the Source_File_Name pragma.
2257 The form of this pragma is as shown in the following examples:
2258 @cindex Source_File_Name pragma
2260 @smallexample @c ada
2261 @cartouche
2262 pragma Source_File_Name (My_Utilities.Stacks,
2263   Spec_File_Name => "myutilst_a.ada");
2264 pragma Source_File_name (My_Utilities.Stacks,
2265   Body_File_Name => "myutilst.ada");
2266 @end cartouche
2267 @end smallexample
2269 @noindent
2270 As shown in this example, the first argument for the pragma is the unit
2271 name (in this example a child unit). The second argument has the form
2272 of a named association. The identifier
2273 indicates whether the file name is for a spec or a body;
2274 the file name itself is given by a string literal.
2276 The source file name pragma is a configuration pragma, which means that
2277 normally it will be placed in the @file{gnat.adc}
2278 file used to hold configuration
2279 pragmas that apply to a complete compilation environment.
2280 For more details on how the @file{gnat.adc} file is created and used
2281 @pxref{Handling of Configuration Pragmas}
2282 @cindex @file{gnat.adc}
2284 @ifclear vms
2285 GNAT allows completely arbitrary file names to be specified using the
2286 source file name pragma. However, if the file name specified has an
2287 extension other than @file{.ads} or @file{.adb} it is necessary to use
2288 a special syntax when compiling the file. The name in this case must be
2289 preceded by the special sequence @code{-x} followed by a space and the name
2290 of the language, here @code{ada}, as in:
2292 @smallexample
2293 $ gcc -c -x ada peculiar_file_name.sim
2294 @end smallexample
2295 @end ifclear
2297 @noindent
2298 @code{gnatmake} handles non-standard file names in the usual manner (the
2299 non-standard file name for the main program is simply used as the
2300 argument to gnatmake). Note that if the extension is also non-standard,
2301 then it must be included in the gnatmake command, it may not be omitted.
2303 @node Alternative File Naming Schemes
2304 @section Alternative File Naming Schemes
2305 @cindex File naming schemes, alternative
2306 @cindex File names
2308 In the previous section, we described the use of the @code{Source_File_Name}
2309 pragma to allow arbitrary names to be assigned to individual source files.
2310 However, this approach requires one pragma for each file, and especially in
2311 large systems can result in very long @file{gnat.adc} files, and also create
2312 a maintenance problem.
2314 GNAT also provides a facility for specifying systematic file naming schemes
2315 other than the standard default naming scheme previously described. An
2316 alternative scheme for naming is specified by the use of
2317 @code{Source_File_Name} pragmas having the following format:
2318 @cindex Source_File_Name pragma
2320 @smallexample @c ada
2321 pragma Source_File_Name (
2322    Spec_File_Name  => FILE_NAME_PATTERN
2323  [,Casing          => CASING_SPEC]
2324  [,Dot_Replacement => STRING_LITERAL]);
2326 pragma Source_File_Name (
2327    Body_File_Name  => FILE_NAME_PATTERN
2328  [,Casing          => CASING_SPEC]
2329  [,Dot_Replacement => STRING_LITERAL]);
2331 pragma Source_File_Name (
2332    Subunit_File_Name  => FILE_NAME_PATTERN
2333  [,Casing             => CASING_SPEC]
2334  [,Dot_Replacement    => STRING_LITERAL]);
2336 FILE_NAME_PATTERN ::= STRING_LITERAL
2337 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2338 @end smallexample
2340 @noindent
2341 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2342 It contains a single asterisk character, and the unit name is substituted
2343 systematically for this asterisk. The optional parameter
2344 @code{Casing} indicates
2345 whether the unit name is to be all upper-case letters, all lower-case letters,
2346 or mixed-case. If no
2347 @code{Casing} parameter is used, then the default is all
2348 ^lower-case^upper-case^.
2350 The optional @code{Dot_Replacement} string is used to replace any periods
2351 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2352 argument is used then separating dots appear unchanged in the resulting
2353 file name.
2354 Although the above syntax indicates that the
2355 @code{Casing} argument must appear
2356 before the @code{Dot_Replacement} argument, but it
2357 is also permissible to write these arguments in the opposite order.
2359 As indicated, it is possible to specify different naming schemes for
2360 bodies, specs, and subunits. Quite often the rule for subunits is the
2361 same as the rule for bodies, in which case, there is no need to give
2362 a separate @code{Subunit_File_Name} rule, and in this case the
2363 @code{Body_File_name} rule is used for subunits as well.
2365 The separate rule for subunits can also be used to implement the rather
2366 unusual case of a compilation environment (e.g. a single directory) which
2367 contains a subunit and a child unit with the same unit name. Although
2368 both units cannot appear in the same partition, the Ada Reference Manual
2369 allows (but does not require) the possibility of the two units coexisting
2370 in the same environment.
2372 The file name translation works in the following steps:
2374 @itemize @bullet
2376 @item
2377 If there is a specific @code{Source_File_Name} pragma for the given unit,
2378 then this is always used, and any general pattern rules are ignored.
2380 @item
2381 If there is a pattern type @code{Source_File_Name} pragma that applies to
2382 the unit, then the resulting file name will be used if the file exists. If
2383 more than one pattern matches, the latest one will be tried first, and the
2384 first attempt resulting in a reference to a file that exists will be used.
2386 @item
2387 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2388 for which the corresponding file exists, then the standard GNAT default
2389 naming rules are used.
2391 @end itemize
2393 @noindent
2394 As an example of the use of this mechanism, consider a commonly used scheme
2395 in which file names are all lower case, with separating periods copied
2396 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2397 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2398 two pragmas appear:
2400 @smallexample @c ada
2401 pragma Source_File_Name
2402   (Spec_File_Name => "*.1.ada");
2403 pragma Source_File_Name
2404   (Body_File_Name => "*.2.ada");
2405 @end smallexample
2407 @noindent
2408 The default GNAT scheme is actually implemented by providing the following
2409 default pragmas internally:
2411 @smallexample @c ada
2412 pragma Source_File_Name
2413   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2414 pragma Source_File_Name
2415   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2416 @end smallexample
2418 @noindent
2419 Our final example implements a scheme typically used with one of the
2420 Ada 83 compilers, where the separator character for subunits was ``__''
2421 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2422 by adding @file{.ADA}, and subunits by
2423 adding @file{.SEP}. All file names were
2424 upper case. Child units were not present of course since this was an
2425 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2426 the same double underscore separator for child units.
2428 @smallexample @c ada
2429 pragma Source_File_Name
2430   (Spec_File_Name => "*_.ADA",
2431    Dot_Replacement => "__",
2432    Casing = Uppercase);
2433 pragma Source_File_Name
2434   (Body_File_Name => "*.ADA",
2435    Dot_Replacement => "__",
2436    Casing = Uppercase);
2437 pragma Source_File_Name
2438   (Subunit_File_Name => "*.SEP",
2439    Dot_Replacement => "__",
2440    Casing = Uppercase);
2441 @end smallexample
2443 @node Generating Object Files
2444 @section Generating Object Files
2446 @noindent
2447 An Ada program consists of a set of source files, and the first step in
2448 compiling the program is to generate the corresponding object files.
2449 These are generated by compiling a subset of these source files.
2450 The files you need to compile are the following:
2452 @itemize @bullet
2453 @item
2454 If a package spec has no body, compile the package spec to produce the
2455 object file for the package.
2457 @item
2458 If a package has both a spec and a body, compile the body to produce the
2459 object file for the package. The source file for the package spec need
2460 not be compiled in this case because there is only one object file, which
2461 contains the code for both the spec and body of the package.
2463 @item
2464 For a subprogram, compile the subprogram body to produce the object file
2465 for the subprogram. The spec, if one is present, is as usual in a
2466 separate file, and need not be compiled.
2468 @item
2469 @cindex Subunits
2470 In the case of subunits, only compile the parent unit. A single object
2471 file is generated for the entire subunit tree, which includes all the
2472 subunits.
2474 @item
2475 Compile child units independently of their parent units
2476 (though, of course, the spec of all the ancestor unit must be present in order
2477 to compile a child unit).
2479 @item
2480 @cindex Generics
2481 Compile generic units in the same manner as any other units. The object
2482 files in this case are small dummy files that contain at most the
2483 flag used for elaboration checking. This is because GNAT always handles generic
2484 instantiation by means of macro expansion. However, it is still necessary to
2485 compile generic units, for dependency checking and elaboration purposes.
2486 @end itemize
2488 @noindent
2489 The preceding rules describe the set of files that must be compiled to
2490 generate the object files for a program. Each object file has the same
2491 name as the corresponding source file, except that the extension is
2492 @file{.o} as usual.
2494 You may wish to compile other files for the purpose of checking their
2495 syntactic and semantic correctness. For example, in the case where a
2496 package has a separate spec and body, you would not normally compile the
2497 spec. However, it is convenient in practice to compile the spec to make
2498 sure it is error-free before compiling clients of this spec, because such
2499 compilations will fail if there is an error in the spec.
2501 GNAT provides an option for compiling such files purely for the
2502 purposes of checking correctness; such compilations are not required as
2503 part of the process of building a program. To compile a file in this
2504 checking mode, use the @option{-gnatc} switch.
2506 @node Source Dependencies
2507 @section Source Dependencies
2509 @noindent
2510 A given object file clearly depends on the source file which is compiled
2511 to produce it. Here we are using @dfn{depends} in the sense of a typical
2512 @code{make} utility; in other words, an object file depends on a source
2513 file if changes to the source file require the object file to be
2514 recompiled.
2515 In addition to this basic dependency, a given object may depend on
2516 additional source files as follows:
2518 @itemize @bullet
2519 @item
2520 If a file being compiled @code{with}'s a unit @var{X}, the object file
2521 depends on the file containing the spec of unit @var{X}. This includes
2522 files that are @code{with}'ed implicitly either because they are parents
2523 of @code{with}'ed child units or they are run-time units required by the
2524 language constructs used in a particular unit.
2526 @item
2527 If a file being compiled instantiates a library level generic unit, the
2528 object file depends on both the spec and body files for this generic
2529 unit.
2531 @item
2532 If a file being compiled instantiates a generic unit defined within a
2533 package, the object file depends on the body file for the package as
2534 well as the spec file.
2536 @item
2537 @findex Inline
2538 @cindex @option{-gnatn} switch
2539 If a file being compiled contains a call to a subprogram for which
2540 pragma @code{Inline} applies and inlining is activated with the
2541 @option{-gnatn} switch, the object file depends on the file containing the
2542 body of this subprogram as well as on the file containing the spec. Note
2543 that for inlining to actually occur as a result of the use of this switch,
2544 it is necessary to compile in optimizing mode.
2546 @cindex @option{-gnatN} switch
2547 The use of @option{-gnatN} activates a more extensive inlining optimization
2548 that is performed by the front end of the compiler. This inlining does
2549 not require that the code generation be optimized. Like @option{-gnatn},
2550 the use of this switch generates additional dependencies.
2551 Note that
2552 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2553 to specify both options.
2555 @item
2556 If an object file O  depends on the proper body of a subunit through inlining
2557 or instantiation, it depends on the parent unit of the subunit. This means that
2558 any modification of the parent unit or one of its subunits affects the
2559 compilation of O.
2561 @item
2562 The object file for a parent unit depends on all its subunit body files.
2564 @item
2565 The previous two rules meant that for purposes of computing dependencies and
2566 recompilation, a body and all its subunits are treated as an indivisible whole.
2568 @noindent
2569 These rules are applied transitively: if unit @code{A} @code{with}'s
2570 unit @code{B}, whose elaboration calls an inlined procedure in package
2571 @code{C}, the object file for unit @code{A} will depend on the body of
2572 @code{C}, in file @file{c.adb}.
2574 The set of dependent files described by these rules includes all the
2575 files on which the unit is semantically dependent, as described in the
2576 Ada 95 Language Reference Manual. However, it is a superset of what the
2577 ARM describes, because it includes generic, inline, and subunit dependencies.
2579 An object file must be recreated by recompiling the corresponding source
2580 file if any of the source files on which it depends are modified. For
2581 example, if the @code{make} utility is used to control compilation,
2582 the rule for an Ada object file must mention all the source files on
2583 which the object file depends, according to the above definition.
2584 The determination of the necessary
2585 recompilations is done automatically when one uses @code{gnatmake}.
2586 @end itemize
2588 @node The Ada Library Information Files
2589 @section The Ada Library Information Files
2590 @cindex Ada Library Information files
2591 @cindex @file{ALI} files
2593 @noindent
2594 Each compilation actually generates two output files. The first of these
2595 is the normal object file that has a @file{.o} extension. The second is a
2596 text file containing full dependency information. It has the same
2597 name as the source file, but an @file{.ali} extension.
2598 This file is known as the Ada Library Information (@file{ALI}) file.
2599 The following information is contained in the @file{ALI} file.
2601 @itemize @bullet
2602 @item
2603 Version information (indicates which version of GNAT was used to compile
2604 the unit(s) in question)
2606 @item
2607 Main program information (including priority and time slice settings,
2608 as well as the wide character encoding used during compilation).
2610 @item
2611 List of arguments used in the @code{gcc} command for the compilation
2613 @item
2614 Attributes of the unit, including configuration pragmas used, an indication
2615 of whether the compilation was successful, exception model used etc.
2617 @item
2618 A list of relevant restrictions applying to the unit (used for consistency)
2619 checking.
2621 @item
2622 Categorization information (e.g. use of pragma @code{Pure}).
2624 @item
2625 Information on all @code{with}'ed units, including presence of
2626 @code{Elaborate} or @code{Elaborate_All} pragmas.
2628 @item
2629 Information from any @code{Linker_Options} pragmas used in the unit
2631 @item
2632 Information on the use of @code{Body_Version} or @code{Version}
2633 attributes in the unit.
2635 @item
2636 Dependency information. This is a list of files, together with
2637 time stamp and checksum information. These are files on which
2638 the unit depends in the sense that recompilation is required
2639 if any of these units are modified.
2641 @item
2642 Cross-reference data. Contains information on all entities referenced
2643 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2644 provide cross-reference information.
2646 @end itemize
2648 @noindent
2649 For a full detailed description of the format of the @file{ALI} file,
2650 see the source of the body of unit @code{Lib.Writ}, contained in file
2651 @file{lib-writ.adb} in the GNAT compiler sources.
2653 @node Binding an Ada Program
2654 @section Binding an Ada Program
2656 @noindent
2657 When using languages such as C and C++, once the source files have been
2658 compiled the only remaining step in building an executable program
2659 is linking the object modules together. This means that it is possible to
2660 link an inconsistent version of a program, in which two units have
2661 included different versions of the same header.
2663 The rules of Ada do not permit such an inconsistent program to be built.
2664 For example, if two clients have different versions of the same package,
2665 it is illegal to build a program containing these two clients.
2666 These rules are enforced by the GNAT binder, which also determines an
2667 elaboration order consistent with the Ada rules.
2669 The GNAT binder is run after all the object files for a program have
2670 been created. It is given the name of the main program unit, and from
2671 this it determines the set of units required by the program, by reading the
2672 corresponding ALI files. It generates error messages if the program is
2673 inconsistent or if no valid order of elaboration exists.
2675 If no errors are detected, the binder produces a main program, in Ada by
2676 default, that contains calls to the elaboration procedures of those
2677 compilation unit that require them, followed by
2678 a call to the main program. This Ada program is compiled to generate the
2679 object file for the main program. The name of
2680 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2681 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2682 main program unit.
2684 Finally, the linker is used to build the resulting executable program,
2685 using the object from the main program from the bind step as well as the
2686 object files for the Ada units of the program.
2688 @node Mixed Language Programming
2689 @section Mixed Language Programming
2690 @cindex Mixed Language Programming
2692 @noindent
2693 This section describes how to develop a mixed-language program,
2694 specifically one that comprises units in both Ada and C.
2696 @menu
2697 * Interfacing to C::
2698 * Calling Conventions::
2699 @end menu
2701 @node Interfacing to C
2702 @subsection Interfacing to C
2703 @noindent
2704 Interfacing Ada with a foreign language such as C involves using
2705 compiler directives to import and/or export entity definitions in each
2706 language---using @code{extern} statements in C, for instance, and the
2707 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2708 a full treatment of these topics, read Appendix B, section 1 of the Ada
2709 95 Language Reference Manual.
2711 There are two ways to build a program using GNAT that contains some Ada
2712 sources and some foreign language sources, depending on whether or not
2713 the main subprogram is written in Ada.  Here is a source example with
2714 the main subprogram in Ada:
2716 @smallexample
2717 /* file1.c */
2718 #include <stdio.h>
2720 void print_num (int num)
2722   printf ("num is %d.\n", num);
2723   return;
2726 /* file2.c */
2728 /* num_from_Ada is declared in my_main.adb */
2729 extern int num_from_Ada;
2731 int get_num (void)
2733   return num_from_Ada;
2735 @end smallexample
2737 @smallexample @c ada
2738 --  my_main.adb
2739 procedure My_Main is
2741    --  Declare then export an Integer entity called num_from_Ada
2742    My_Num : Integer := 10;
2743    pragma Export (C, My_Num, "num_from_Ada");
2745    --  Declare an Ada function spec for Get_Num, then use
2746    --  C function get_num for the implementation.
2747    function Get_Num return Integer;
2748    pragma Import (C, Get_Num, "get_num");
2750    --  Declare an Ada procedure spec for Print_Num, then use
2751    --  C function print_num for the implementation.
2752    procedure Print_Num (Num : Integer);
2753    pragma Import (C, Print_Num, "print_num");
2755 begin
2756    Print_Num (Get_Num);
2757 end My_Main;
2758 @end smallexample
2760 @enumerate
2761 @item
2762 To build this example, first compile the foreign language files to
2763 generate object files:
2764 @smallexample
2765 gcc -c file1.c
2766 gcc -c file2.c
2767 @end smallexample
2769 @item
2770 Then, compile the Ada units to produce a set of object files and ALI
2771 files:
2772 @smallexample
2773 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2774 @end smallexample
2776 @item
2777 Run the Ada binder on the Ada main program:
2778 @smallexample
2779 gnatbind my_main.ali
2780 @end smallexample
2782 @item
2783 Link the Ada main program, the Ada objects and the other language
2784 objects:
2785 @smallexample
2786 gnatlink my_main.ali file1.o file2.o
2787 @end smallexample
2788 @end enumerate
2790 The last three steps can be grouped in a single command:
2791 @smallexample
2792 gnatmake my_main.adb -largs file1.o file2.o
2793 @end smallexample
2795 @cindex Binder output file
2796 @noindent
2797 If the main program is in a language other than Ada, then you may have
2798 more than one entry point into the Ada subsystem. You must use a special
2799 binder option to generate callable routines that initialize and
2800 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2801 Calls to the initialization and finalization routines must be inserted
2802 in the main program, or some other appropriate point in the code. The
2803 call to initialize the Ada units must occur before the first Ada
2804 subprogram is called, and the call to finalize the Ada units must occur
2805 after the last Ada subprogram returns. The binder will place the
2806 initialization and finalization subprograms into the
2807 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2808 sources.  To illustrate, we have the following example:
2810 @smallexample
2811 /* main.c */
2812 extern void adainit (void);
2813 extern void adafinal (void);
2814 extern int add (int, int);
2815 extern int sub (int, int);
2817 int main (int argc, char *argv[])
2819   int a = 21, b = 7;
2821   adainit();
2823   /* Should print "21 + 7 = 28" */
2824   printf ("%d + %d = %d\n", a, b, add (a, b));
2825   /* Should print "21 - 7 = 14" */
2826   printf ("%d - %d = %d\n", a, b, sub (a, b));
2828   adafinal();
2830 @end smallexample
2832 @smallexample @c ada
2833 --  unit1.ads
2834 package Unit1 is
2835    function Add (A, B : Integer) return Integer;
2836    pragma Export (C, Add, "add");
2837 end Unit1;
2839 --  unit1.adb
2840 package body Unit1 is
2841    function Add (A, B : Integer) return Integer is
2842    begin
2843       return A + B;
2844    end Add;
2845 end Unit1;
2847 --  unit2.ads
2848 package Unit2 is
2849    function Sub (A, B : Integer) return Integer;
2850    pragma Export (C, Sub, "sub");
2851 end Unit2;
2853 --  unit2.adb
2854 package body Unit2 is
2855    function Sub (A, B : Integer) return Integer is
2856    begin
2857       return A - B;
2858    end Sub;
2859 end Unit2;
2860 @end smallexample
2862 @enumerate
2863 @item
2864 The build procedure for this application is similar to the last
2865 example's.  First, compile the foreign language files to generate object
2866 files:
2867 @smallexample
2868 gcc -c main.c
2869 @end smallexample
2871 @item
2872 Next, compile the Ada units to produce a set of object files and ALI
2873 files:
2874 @smallexample
2875 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2876 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2877 @end smallexample
2879 @item
2880 Run the Ada binder on every generated ALI file.  Make sure to use the
2881 @option{-n} option to specify a foreign main program:
2882 @smallexample
2883 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2884 @end smallexample
2886 @item
2887 Link the Ada main program, the Ada objects and the foreign language
2888 objects. You need only list the last ALI file here:
2889 @smallexample
2890 gnatlink unit2.ali main.o -o exec_file
2891 @end smallexample
2893 This procedure yields a binary executable called @file{exec_file}.
2894 @end enumerate
2896 @node Calling Conventions
2897 @subsection Calling Conventions
2898 @cindex Foreign Languages
2899 @cindex Calling Conventions
2900 GNAT follows standard calling sequence conventions and will thus interface
2901 to any other language that also follows these conventions. The following
2902 Convention identifiers are recognized by GNAT:
2904 @table @code
2905 @cindex Interfacing to Ada
2906 @cindex Other Ada compilers
2907 @cindex Convention Ada
2908 @item Ada
2909 This indicates that the standard Ada calling sequence will be
2910 used and all Ada data items may be passed without any limitations in the
2911 case where GNAT is used to generate both the caller and callee. It is also
2912 possible to mix GNAT generated code and code generated by another Ada
2913 compiler. In this case, the data types should be restricted to simple
2914 cases, including primitive types. Whether complex data types can be passed
2915 depends on the situation. Probably it is safe to pass simple arrays, such
2916 as arrays of integers or floats. Records may or may not work, depending
2917 on whether both compilers lay them out identically. Complex structures
2918 involving variant records, access parameters, tasks, or protected types,
2919 are unlikely to be able to be passed.
2921 Note that in the case of GNAT running
2922 on a platform that supports DEC Ada 83, a higher degree of compatibility
2923 can be guaranteed, and in particular records are layed out in an identical
2924 manner in the two compilers. Note also that if output from two different
2925 compilers is mixed, the program is responsible for dealing with elaboration
2926 issues. Probably the safest approach is to write the main program in the
2927 version of Ada other than GNAT, so that it takes care of its own elaboration
2928 requirements, and then call the GNAT-generated adainit procedure to ensure
2929 elaboration of the GNAT components. Consult the documentation of the other
2930 Ada compiler for further details on elaboration.
2932 However, it is not possible to mix the tasking run time of GNAT and
2933 DEC Ada 83, All the tasking operations must either be entirely within
2934 GNAT compiled sections of the program, or entirely within DEC Ada 83
2935 compiled sections of the program.
2937 @cindex Interfacing to Assembly
2938 @cindex Convention Assembler
2939 @item Assembler
2940 Specifies assembler as the convention. In practice this has the
2941 same effect as convention Ada (but is not equivalent in the sense of being
2942 considered the same convention).
2944 @cindex Convention Asm
2945 @findex Asm
2946 @item Asm
2947 Equivalent to Assembler.
2949 @cindex Interfacing to COBOL
2950 @cindex Convention COBOL
2951 @findex COBOL
2952 @item COBOL
2953 Data will be passed according to the conventions described
2954 in section B.4 of the Ada 95 Reference Manual.
2956 @findex C
2957 @cindex Interfacing to C
2958 @cindex Convention C
2959 @item C
2960 Data will be passed according to the conventions described
2961 in section B.3 of the Ada 95 Reference Manual.
2963 @findex C varargs function
2964 @cindex Intefacing to C varargs function
2965 @cindex varargs function intefacs
2966 @item C varargs function
2967 In C, @code{varargs} allows a function to take a variable number of
2968 arguments. There is no direct equivalent in this to Ada. One
2969 approach that can be used is to create a C wrapper for each
2970 different profile and then interface to this C wrapper. For
2971 example, to print an @code{int} value using @code{printf},
2972 create a C function @code{printfi} that takes two arguments, a
2973 pointer to a string and an int, and calls @code{printf}.
2974 Then in the Ada program, use pragma @code{Import} to
2975 interface to printfi.
2977 It may work on some platforms to directly interface to
2978 a @code{varargs} function by providing a specific Ada profile
2979 for a a particular call. However, this does not work on
2980 all platforms, since there is no guarantee that the
2981 calling sequence for a two argument normal C function
2982 is the same as for calling a @code{varargs} C function with
2983 the same two arguments.
2985 @cindex Convention Default
2986 @findex Default
2987 @item Default
2988 Equivalent to C.
2990 @cindex Convention External
2991 @findex External
2992 @item External
2993 Equivalent to C.
2995 @findex C++
2996 @cindex Interfacing to C++
2997 @cindex Convention C++
2998 @item CPP
2999 This stands for C++. For most purposes this is identical to C.
3000 See the separate description of the specialized GNAT pragmas relating to
3001 C++ interfacing for further details.
3003 @findex Fortran
3004 @cindex Interfacing to Fortran
3005 @cindex Convention Fortran
3006 @item Fortran
3007 Data will be passed according to the conventions described
3008 in section B.5 of the Ada 95 Reference Manual.
3010 @item Intrinsic
3011 This applies to an intrinsic operation, as defined in the Ada 95
3012 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3013 this means that the body of the subprogram is provided by the compiler itself,
3014 usually by means of an efficient code sequence, and that the user does not
3015 supply an explicit body for it. In an application program, the pragma can
3016 only be applied to the following two sets of names, which the GNAT compiler
3017 recognizes.
3019 @itemize @bullet
3020 @item
3021 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3022 Arithmetic.  The corresponding subprogram declaration must have
3023 two formal parameters. The
3024 first one must be a signed integer type or a modular type with a binary
3025 modulus, and the second parameter must be of type Natural.
3026 The return type must be the same as the type of the first argument. The size
3027 of this type can only be 8, 16, 32, or 64.
3028 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3029 The corresponding operator declaration must have parameters and result type
3030 that have the same root numeric type (for example, all three are long_float
3031 types). This simplifies the definition of operations that use type checking
3032 to perform dimensional checks:
3034 @smallexample @c ada
3035 type Distance is new Long_Float;
3036 type Time     is new Long_Float;
3037 type Velocity is new Long_Float;
3038 function "/" (D : Distance; T : Time)
3039   return Velocity;
3040 pragma Import (Intrinsic, "/");
3041 @end smallexample
3043 @noindent
3044 This common idiom is often programmed with a generic definition and an
3045 explicit body. The pragma makes it simpler to introduce such declarations.
3046 It incurs no overhead in compilation time or code size, because it is
3047 implemented as a single machine instruction.
3048 @end itemize
3049 @noindent
3051 @ifset unw
3052 @findex Stdcall
3053 @cindex Convention Stdcall
3054 @item Stdcall
3055 This is relevant only to NT/Win95 implementations of GNAT,
3056 and specifies that the Stdcall calling sequence will be used, as defined
3057 by the NT API.
3059 @findex DLL
3060 @cindex Convention DLL
3061 @item DLL
3062 This is equivalent to Stdcall.
3064 @findex Win32
3065 @cindex Convention Win32
3066 @item Win32
3067 This is equivalent to Stdcall.
3068 @end ifset
3070 @findex Stubbed
3071 @cindex Convention Stubbed
3072 @item Stubbed
3073 This is a special convention that indicates that the compiler
3074 should provide a stub body that raises @code{Program_Error}.
3075 @end table
3077 @noindent
3078 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3079 that can be used to parametrize conventions and allow additional synonyms
3080 to be specified. For example if you have legacy code in which the convention
3081 identifier Fortran77 was used for Fortran, you can use the configuration
3082 pragma:
3084 @smallexample @c ada
3085 pragma Convention_Identifier (Fortran77, Fortran);
3086 @end smallexample
3088 @noindent
3089 And from now on the identifier Fortran77 may be used as a convention
3090 identifier (for example in an @code{Import} pragma) with the same
3091 meaning as Fortran.
3093 @node Building Mixed Ada & C++ Programs
3094 @section Building Mixed Ada & C++ Programs
3096 @noindent
3097 A programmer inexperienced with mixed-language development may find that
3098 building an application containing both Ada and C++ code can be a
3099 challenge. As a matter of fact, interfacing with C++ has not been
3100 standardized in the Ada 95 Reference Manual due to the immaturity of --
3101 and lack of standards for -- C++ at the time. This section gives a few
3102 hints that should make this task easier. The first section addresses
3103 the differences regarding interfacing with C. The second section
3104 looks into the delicate problem of linking the complete application from
3105 its Ada and C++ parts. The last section gives some hints on how the GNAT
3106 run time can be adapted in order to allow inter-language dispatching
3107 with a new C++ compiler.
3109 @menu
3110 * Interfacing to C++::
3111 * Linking a Mixed C++ & Ada Program::
3112 * A Simple Example::
3113 * Adapting the Run Time to a New C++ Compiler::
3114 @end menu
3116 @node Interfacing to C++
3117 @subsection Interfacing to C++
3119 @noindent
3120 GNAT supports interfacing with C++ compilers generating code that is
3121 compatible with the standard Application Binary Interface of the given
3122 platform.
3124 @noindent
3125 Interfacing can be done at 3 levels: simple data, subprograms, and
3126 classes. In the first two cases, GNAT offers a specific @var{Convention
3127 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3128 the names of subprograms, and currently, GNAT does not provide any help
3129 to solve the demangling problem. This problem can be addressed in two
3130 ways:
3131 @itemize @bullet
3132 @item
3133 by modifying the C++ code in order to force a C convention using
3134 the @code{extern "C"} syntax.
3136 @item
3137 by figuring out the mangled name and use it as the Link_Name argument of
3138 the pragma import.
3139 @end itemize
3141 @noindent
3142 Interfacing at the class level can be achieved by using the GNAT specific
3143 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3144 Reference Manual for additional information.
3146 @node Linking a Mixed C++ & Ada Program
3147 @subsection Linking a Mixed C++ & Ada Program
3149 @noindent
3150 Usually the linker of the C++ development system must be used to link
3151 mixed applications because most C++ systems will resolve elaboration
3152 issues (such as calling constructors on global class instances)
3153 transparently during the link phase. GNAT has been adapted to ease the
3154 use of a foreign linker for the last phase. Three cases can be
3155 considered:
3156 @enumerate
3158 @item
3159 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3160 The C++ linker can simply be called by using the C++ specific driver
3161 called @code{c++}. Note that this setup is not very common because it
3162 may involve recompiling the whole GCC tree from sources, which makes it
3163 harder to upgrade the compilation system for one language without
3164 destabilizing the other.
3166 @smallexample
3167 $ c++ -c file1.C
3168 $ c++ -c file2.C
3169 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3170 @end smallexample
3172 @item
3173 Using GNAT and G++ from two different GCC installations: If both
3174 compilers are on the PATH, the previous method may be used. It is
3175 important to note that environment variables such as C_INCLUDE_PATH,
3176 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3177 at the same time and may make one of the two compilers operate
3178 improperly if set during invocation of the wrong compiler.  It is also
3179 very important that the linker uses the proper @file{libgcc.a} GCC
3180 library -- that is, the one from the C++ compiler installation. The
3181 implicit link command as suggested in the gnatmake command from the
3182 former example can be replaced by an explicit link command with the
3183 full-verbosity option in order to verify which library is used:
3184 @smallexample
3185 $ gnatbind ada_unit
3186 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3187 @end smallexample
3188 If there is a problem due to interfering environment variables, it can
3189 be worked around by using an intermediate script. The following example
3190 shows the proper script to use when GNAT has not been installed at its
3191 default location and g++ has been installed at its default location:
3193 @smallexample
3194 $ cat ./my_script
3195 #!/bin/sh
3196 unset BINUTILS_ROOT
3197 unset GCC_ROOT
3198 c++ $*
3199 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3200 @end smallexample
3202 @item
3203 Using a non-GNU C++ compiler: The commands previously described can be
3204 used to insure that the C++ linker is used. Nonetheless, you need to add
3205 the path to libgcc explicitly, since some libraries needed by GNAT are
3206 located in this directory:
3208 @smallexample
3209 $ cat ./my_script
3210 #!/bin/sh
3211 CC $* `gcc -print-libgcc-file-name`
3212 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3213 @end smallexample
3215 Where CC is the name of the non-GNU C++ compiler.
3217 @end enumerate
3219 @node A Simple Example
3220 @subsection  A Simple Example
3221 @noindent
3222 The following example, provided as part of the GNAT examples, shows how
3223 to achieve procedural interfacing between Ada and C++ in both
3224 directions. The C++ class A has two methods. The first method is exported
3225 to Ada by the means of an extern C wrapper function. The second method
3226 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3227 a limited record with a layout comparable to the C++ class. The Ada
3228 subprogram, in turn, calls the C++ method. So, starting from the C++
3229 main program, the process passes back and forth between the two
3230 languages.
3232 @noindent
3233 Here are the compilation commands:
3234 @smallexample
3235 $ gnatmake -c simple_cpp_interface
3236 $ c++ -c cpp_main.C
3237 $ c++ -c ex7.C
3238 $ gnatbind -n simple_cpp_interface
3239 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3240       -lstdc++ ex7.o cpp_main.o
3241 @end smallexample
3243 @noindent
3244 Here are the corresponding sources:
3245 @smallexample
3247 //cpp_main.C
3249 #include "ex7.h"
3251 extern "C" @{
3252   void adainit (void);
3253   void adafinal (void);
3254   void method1 (A *t);
3257 void method1 (A *t)
3259   t->method1 ();
3262 int main ()
3264   A obj;
3265   adainit ();
3266   obj.method2 (3030);
3267   adafinal ();
3270 //ex7.h
3272 class Origin @{
3273  public:
3274   int o_value;
3276 class A : public Origin @{
3277  public:
3278   void method1 (void);
3279   virtual void method2 (int v);
3280   A();
3281   int   a_value;
3284 //ex7.C
3286 #include "ex7.h"
3287 #include <stdio.h>
3289 extern "C" @{ void ada_method2 (A *t, int v);@}
3291 void A::method1 (void)
3293   a_value = 2020;
3294   printf ("in A::method1, a_value = %d \n",a_value);
3298 void A::method2 (int v)
3300    ada_method2 (this, v);
3301    printf ("in A::method2, a_value = %d \n",a_value);
3305 A::A(void)
3307    a_value = 1010;
3308   printf ("in A::A, a_value = %d \n",a_value);
3311 -- Ada sources
3312 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3314    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3315    @b{begin}
3316       Method1 (This);
3317       This.A_Value := V;
3318    @b{end} Ada_Method2;
3320 @b{end} Simple_Cpp_Interface;
3322 @b{package} Simple_Cpp_Interface @b{is}
3323    @b{type} A @b{is} @b{limited}
3324       @b{record}
3325          O_Value : Integer;
3326          A_Value : Integer;
3327       @b{end} @b{record};
3328    @b{pragma} Convention (C, A);
3330    @b{procedure} Method1 (This : @b{in} @b{out} A);
3331    @b{pragma} Import (C, Method1);
3333    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3334    @b{pragma} Export (C, Ada_Method2);
3336 @b{end} Simple_Cpp_Interface;
3337 @end smallexample
3339 @node Adapting the Run Time to a New C++ Compiler
3340 @subsection Adapting the Run Time to a New C++ Compiler
3341 @noindent
3342 GNAT offers the capability to derive Ada 95 tagged types directly from
3343 preexisting C++ classes and . See ``Interfacing with C++'' in the
3344 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3345 such a goal
3346 has been made user configurable through a GNAT library unit
3347 @code{Interfaces.CPP}. The default version of this file is adapted to
3348 the GNU C++ compiler. Internal knowledge of the virtual
3349 table layout used by the new C++ compiler is needed to configure
3350 properly this unit. The Interface of this unit is known by the compiler
3351 and cannot be changed except for the value of the constants defining the
3352 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3353 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3354 of this unit for more details.
3356 @node Comparison between GNAT and C/C++ Compilation Models
3357 @section Comparison between GNAT and C/C++ Compilation Models
3359 @noindent
3360 The GNAT model of compilation is close to the C and C++ models. You can
3361 think of Ada specs as corresponding to header files in C. As in C, you
3362 don't need to compile specs; they are compiled when they are used. The
3363 Ada @code{with} is similar in effect to the @code{#include} of a C
3364 header.
3366 One notable difference is that, in Ada, you may compile specs separately
3367 to check them for semantic and syntactic accuracy. This is not always
3368 possible with C headers because they are fragments of programs that have
3369 less specific syntactic or semantic rules.
3371 The other major difference is the requirement for running the binder,
3372 which performs two important functions. First, it checks for
3373 consistency. In C or C++, the only defense against assembling
3374 inconsistent programs lies outside the compiler, in a makefile, for
3375 example. The binder satisfies the Ada requirement that it be impossible
3376 to construct an inconsistent program when the compiler is used in normal
3377 mode.
3379 @cindex Elaboration order control
3380 The other important function of the binder is to deal with elaboration
3381 issues. There are also elaboration issues in C++ that are handled
3382 automatically. This automatic handling has the advantage of being
3383 simpler to use, but the C++ programmer has no control over elaboration.
3384 Where @code{gnatbind} might complain there was no valid order of
3385 elaboration, a C++ compiler would simply construct a program that
3386 malfunctioned at run time.
3388 @node Comparison between GNAT and Conventional Ada Library Models
3389 @section Comparison between GNAT and Conventional Ada Library Models
3391 @noindent
3392 This section is intended to be useful to Ada programmers who have
3393 previously used an Ada compiler implementing the traditional Ada library
3394 model, as described in the Ada 95 Language Reference Manual. If you
3395 have not used such a system, please go on to the next section.
3397 @cindex GNAT library
3398 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3399 source files themselves acts as the library. Compiling Ada programs does
3400 not generate any centralized information, but rather an object file and
3401 a ALI file, which are of interest only to the binder and linker.
3402 In a traditional system, the compiler reads information not only from
3403 the source file being compiled, but also from the centralized library.
3404 This means that the effect of a compilation depends on what has been
3405 previously compiled. In particular:
3407 @itemize @bullet
3408 @item
3409 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3410 to the version of the unit most recently compiled into the library.
3412 @item
3413 Inlining is effective only if the necessary body has already been
3414 compiled into the library.
3416 @item
3417 Compiling a unit may obsolete other units in the library.
3418 @end itemize
3420 @noindent
3421 In GNAT, compiling one unit never affects the compilation of any other
3422 units because the compiler reads only source files. Only changes to source
3423 files can affect the results of a compilation. In particular:
3425 @itemize @bullet
3426 @item
3427 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3428 to the source version of the unit that is currently accessible to the
3429 compiler.
3431 @item
3432 @cindex Inlining
3433 Inlining requires the appropriate source files for the package or
3434 subprogram bodies to be available to the compiler. Inlining is always
3435 effective, independent of the order in which units are complied.
3437 @item
3438 Compiling a unit never affects any other compilations. The editing of
3439 sources may cause previous compilations to be out of date if they
3440 depended on the source file being modified.
3441 @end itemize
3443 @noindent
3444 The most important result of these differences is that order of compilation
3445 is never significant in GNAT. There is no situation in which one is
3446 required to do one compilation before another. What shows up as order of
3447 compilation requirements in the traditional Ada library becomes, in
3448 GNAT, simple source dependencies; in other words, there is only a set
3449 of rules saying what source files must be present when a file is
3450 compiled.
3452 @ifset vms
3453 @node Placement of temporary files
3454 @section Placement of temporary files
3455 @cindex Temporary files (user control over placement)
3457 @noindent
3458 GNAT creates temporary files in the directory designated by the environment
3459 variable @env{TMPDIR}.
3460 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3461 for detailed information on how environment variables are resolved.
3462 For most users the easiest way to make use of this feature is to simply
3463 define @env{TMPDIR} as a job level logical name).
3464 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3465 for compiler temporary files, then you can include something like the
3466 following command in your @file{LOGIN.COM} file:
3468 @smallexample
3469 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3470 @end smallexample
3472 @noindent
3473 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3474 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3475 designated by @env{TEMP}.
3476 If none of these environment variables are defined then GNAT uses the
3477 directory designated by the logical name @code{SYS$SCRATCH:}
3478 (by default the user's home directory). If all else fails
3479 GNAT uses the current directory for temporary files.
3480 @end ifset
3483 @c *************************
3484 @node Compiling Using gcc
3485 @chapter Compiling Using @code{gcc}
3487 @noindent
3488 This chapter discusses how to compile Ada programs using the @code{gcc}
3489 command. It also describes the set of switches
3490 that can be used to control the behavior of the compiler.
3491 @menu
3492 * Compiling Programs::
3493 * Switches for gcc::
3494 * Search Paths and the Run-Time Library (RTL)::
3495 * Order of Compilation Issues::
3496 * Examples::
3497 @end menu
3499 @node Compiling Programs
3500 @section Compiling Programs
3502 @noindent
3503 The first step in creating an executable program is to compile the units
3504 of the program using the @code{gcc} command. You must compile the
3505 following files:
3507 @itemize @bullet
3508 @item
3509 the body file (@file{.adb}) for a library level subprogram or generic
3510 subprogram
3512 @item
3513 the spec file (@file{.ads}) for a library level package or generic
3514 package that has no body
3516 @item
3517 the body file (@file{.adb}) for a library level package
3518 or generic package that has a body
3520 @end itemize
3522 @noindent
3523 You need @emph{not} compile the following files
3525 @itemize @bullet
3527 @item
3528 the spec of a library unit which has a body
3530 @item
3531 subunits
3532 @end itemize
3534 @noindent
3535 because they are compiled as part of compiling related units. GNAT
3536 package specs
3537 when the corresponding body is compiled, and subunits when the parent is
3538 compiled.
3540 @cindex cannot generate code
3541 If you attempt to compile any of these files, you will get one of the
3542 following error messages (where fff is the name of the file you compiled):
3544 @smallexample
3545 cannot generate code for file @var{fff} (package spec)
3546 to check package spec, use -gnatc
3548 cannot generate code for file @var{fff} (missing subunits)
3549 to check parent unit, use -gnatc
3551 cannot generate code for file @var{fff} (subprogram spec)
3552 to check subprogram spec, use -gnatc
3554 cannot generate code for file @var{fff} (subunit)
3555 to check subunit, use -gnatc
3556 @end smallexample
3558 @noindent
3559 As indicated by the above error messages, if you want to submit
3560 one of these files to the compiler to check for correct semantics
3561 without generating code, then use the @option{-gnatc} switch.
3563 The basic command for compiling a file containing an Ada unit is
3565 @smallexample
3566 $ gcc -c [@var{switches}] @file{file name}
3567 @end smallexample
3569 @noindent
3570 where @var{file name} is the name of the Ada file (usually
3571 having an extension
3572 @file{.ads} for a spec or @file{.adb} for a body).
3573 @ifclear vms
3574 You specify the
3575 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3576 @end ifclear
3577 The result of a successful compilation is an object file, which has the
3578 same name as the source file but an extension of @file{.o} and an Ada
3579 Library Information (ALI) file, which also has the same name as the
3580 source file, but with @file{.ali} as the extension. GNAT creates these
3581 two output files in the current directory, but you may specify a source
3582 file in any directory using an absolute or relative path specification
3583 containing the directory information.
3585 @findex gnat1
3586 @code{gcc} is actually a driver program that looks at the extensions of
3587 the file arguments and loads the appropriate compiler. For example, the
3588 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3589 These programs are in directories known to the driver program (in some
3590 configurations via environment variables you set), but need not be in
3591 your path. The @code{gcc} driver also calls the assembler and any other
3592 utilities needed to complete the generation of the required object
3593 files.
3595 It is possible to supply several file names on the same @code{gcc}
3596 command. This causes @code{gcc} to call the appropriate compiler for
3597 each file. For example, the following command lists three separate
3598 files to be compiled:
3600 @smallexample
3601 $ gcc -c x.adb y.adb z.c
3602 @end smallexample
3604 @noindent
3605 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3606 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3607 The compiler generates three object files @file{x.o}, @file{y.o} and
3608 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3609 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3610 @ifclear vms
3611 except for
3612 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3613 @end ifclear
3615 @node Switches for gcc
3616 @section Switches for @code{gcc}
3618 @noindent
3619 The @code{gcc} command accepts switches that control the
3620 compilation process. These switches are fully described in this section.
3621 First we briefly list all the switches, in alphabetical order, then we
3622 describe the switches in more detail in functionally grouped sections.
3624 @menu
3625 * Output and Error Message Control::
3626 * Warning Message Control::
3627 * Debugging and Assertion Control::
3628 * Run-Time Checks::
3629 * Stack Overflow Checking::
3630 * Validity Checking::
3631 * Style Checking::
3632 * Using gcc for Syntax Checking::
3633 * Using gcc for Semantic Checking::
3634 * Compiling Ada 83 Programs::
3635 * Character Set Control::
3636 * File Naming Control::
3637 * Subprogram Inlining Control::
3638 * Auxiliary Output Control::
3639 * Debugging Control::
3640 * Exception Handling Control::
3641 * Units to Sources Mapping Files::
3642 * Integrated Preprocessing::
3643 @ifset vms
3644 * Return Codes::
3645 @end ifset
3646 @end menu
3648 @table @option
3649 @c !sort!
3650 @ifclear vms
3651 @cindex @option{-b} (@code{gcc})
3652 @item -b @var{target}
3653 Compile your program to run on @var{target}, which is the name of a
3654 system configuration. You must have a GNAT cross-compiler built if
3655 @var{target} is not the same as your host system.
3657 @item -B@var{dir}
3658 @cindex @option{-B} (@code{gcc})
3659 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3660 from @var{dir} instead of the default location. Only use this switch
3661 when multiple versions of the GNAT compiler are available. See the
3662 @code{gcc} manual page for further details. You would normally use the
3663 @option{-b} or @option{-V} switch instead.
3665 @item -c
3666 @cindex @option{-c} (@code{gcc})
3667 Compile. Always use this switch when compiling Ada programs.
3669 Note: for some other languages when using @code{gcc}, notably in
3670 the case of C and C++, it is possible to use
3671 use @code{gcc} without a @option{-c} switch to
3672 compile and link in one step. In the case of GNAT, you
3673 cannot use this approach, because the binder must be run
3674 and @code{gcc} cannot be used to run the GNAT binder.
3675 @end ifclear
3677 @item -fno-inline
3678 @cindex @option{-fno-inline} (@code{gcc})
3679 Suppresses all back-end inlining, even if other optimization or inlining
3680 switches are set.
3681 This includes suppression of inlining that results
3682 from the use of the pragma @code{Inline_Always}.
3683 See also @option{-gnatn} and @option{-gnatN}.
3685 @item -fno-strict-aliasing
3686 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3687 Causes the compiler to avoid assumptions regarding non-aliasing
3688 of objects of different types. See section
3689 @pxref{Optimization and Strict Aliasing} for details.
3691 @item -fstack-check
3692 @cindex @option{-fstack-check} (@code{gcc})
3693 Activates stack checking.
3694 See @ref{Stack Overflow Checking} for details of the use of this option.
3696 @item ^-g^/DEBUG^
3697 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3698 Generate debugging information. This information is stored in the object
3699 file and copied from there to the final executable file by the linker,
3700 where it can be read by the debugger. You must use the
3701 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3703 @item -gnat83
3704 @cindex @option{-gnat83} (@code{gcc})
3705 Enforce Ada 83 restrictions.
3707 @item -gnata
3708 @cindex @option{-gnata} (@code{gcc})
3709 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3710 activated.
3712 @item -gnatA
3713 @cindex @option{-gnatA} (@code{gcc})
3714 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3715 it will be ignored.
3717 @item -gnatb
3718 @cindex @option{-gnatb} (@code{gcc})
3719 Generate brief messages to @file{stderr} even if verbose mode set.
3721 @item -gnatc
3722 @cindex @option{-gnatc} (@code{gcc})
3723 Check syntax and semantics only (no code generation attempted).
3725 @item -gnatd
3726 @cindex @option{-gnatd} (@code{gcc})
3727 Specify debug options for the compiler. The string of characters after
3728 the @option{-gnatd} specify the specific debug options. The possible
3729 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3730 compiler source file @file{debug.adb} for details of the implemented
3731 debug options. Certain debug options are relevant to applications
3732 programmers, and these are documented at appropriate points in this
3733 users guide.
3735 @item -gnatD
3736 @cindex @option{-gnatD} (@code{gcc})
3737 Create expanded source files for source level debugging. This switch
3738 also suppress generation of cross-reference information
3739 (see @option{-gnatx}).
3741 @item -gnatec=@var{path}
3742 @cindex @option{-gnatec} (@code{gcc})
3743 Specify a configuration pragma file
3744 @ifclear vms
3745 (the equal sign is optional)
3746 @end ifclear
3747 (see @ref{The Configuration Pragmas Files}).
3749 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3750 @cindex @option{-gnateD} (@code{gcc})
3751 Defines a symbol, associated with value, for preprocessing.
3752 (see @ref{Integrated Preprocessing})
3754 @item -gnatef
3755 @cindex @option{-gnatef} (@code{gcc})
3756 Display full source path name in brief error messages.
3758 @item -gnatem=@var{path}
3759 @cindex @option{-gnatem} (@code{gcc})
3760 Specify a mapping file
3761 @ifclear vms
3762 (the equal sign is optional)
3763 @end ifclear
3764 (see @ref{Units to Sources Mapping Files}).
3766 @item -gnatep=@var{file}
3767 @cindex @option{-gnatep} (@code{gcc})
3768 Specify a preprocessing data file
3769 @ifclear vms
3770 (the equal sign is optional)
3771 @end ifclear
3772 (see @ref{Integrated Preprocessing}).
3774 @item -gnatE
3775 @cindex @option{-gnatE} (@code{gcc})
3776 Full dynamic elaboration checks.
3778 @item -gnatf
3779 @cindex @option{-gnatf} (@code{gcc})
3780 Full errors. Multiple errors per line, all undefined references, do not
3781 attempt to suppress cascaded errors.
3783 @item -gnatF
3784 @cindex @option{-gnatF} (@code{gcc})
3785 Externals names are folded to all uppercase.
3787 @item -gnatg
3788 @cindex @option{-gnatg} (@code{gcc})
3789 Internal GNAT implementation mode. This should not be used for
3790 applications programs, it is intended only for use by the compiler
3791 and its run-time library. For documentation, see the GNAT sources.
3792 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3793 are generated on unreferenced entities, and all warnings are treated
3794 as errors.
3796 @item -gnatG
3797 @cindex @option{-gnatG} (@code{gcc})
3798 List generated expanded code in source form.
3800 @item ^-gnath^/HELP^
3801 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3802 Output usage information. The output is written to @file{stdout}.
3804 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3805 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3806 Identifier character set
3807 @ifclear vms
3808 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3809 @end ifclear
3810 @ifset vms
3811 For details of the possible selections for @var{c},
3812 see @xref{Character Set Control}.
3813 @end ifset
3815 @item -gnatk=@var{n}
3816 @cindex @option{-gnatk} (@code{gcc})
3817 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3819 @item -gnatl
3820 @cindex @option{-gnatl} (@code{gcc})
3821 Output full source listing with embedded error messages.
3823 @item -gnatL
3824 @cindex @option{-gnatL} (@code{gcc})
3825 Use the longjmp/setjmp method for exception handling
3827 @item -gnatm=@var{n}
3828 @cindex @option{-gnatm} (@code{gcc})
3829 Limit number of detected error or warning messages to @var{n}
3830 where @var{n} is in the range 1..999_999. The default setting if
3831 no switch is given is 9999. Compilation is terminated if this
3832 limit is exceeded.
3834 @item -gnatn
3835 @cindex @option{-gnatn} (@code{gcc})
3836 Activate inlining for subprograms for which
3837 pragma @code{inline} is specified. This inlining is performed
3838 by the GCC back-end.
3840 @item -gnatN
3841 @cindex @option{-gnatN} (@code{gcc})
3842 Activate front end inlining for subprograms for which
3843 pragma @code{Inline} is specified. This inlining is performed
3844 by the front end and will be visible in the
3845 @option{-gnatG} output.
3846 In some cases, this has proved more effective than the back end
3847 inlining resulting from the use of
3848 @option{-gnatn}.
3849 Note that
3850 @option{-gnatN} automatically implies
3851 @option{-gnatn} so it is not necessary
3852 to specify both options. There are a few cases that the back-end inlining
3853 catches that cannot be dealt with in the front-end.
3855 @item -gnato
3856 @cindex @option{-gnato} (@code{gcc})
3857 Enable numeric overflow checking (which is not normally enabled by
3858 default). Not that division by zero is a separate check that is not
3859 controlled by this switch (division by zero checking is on by default).
3861 @item -gnatp
3862 @cindex @option{-gnatp} (@code{gcc})
3863 Suppress all checks.
3865 @item -gnatP
3866 @cindex @option{-gnatP} (@code{gcc})
3867 Enable polling. This is required on some systems (notably Windows NT) to
3868 obtain asynchronous abort and asynchronous transfer of control capability.
3869 See the description of pragma Polling in the GNAT Reference Manual for
3870 full details.
3872 @item -gnatq
3873 @cindex @option{-gnatq} (@code{gcc})
3874 Don't quit; try semantics, even if parse errors.
3876 @item -gnatQ
3877 @cindex @option{-gnatQ} (@code{gcc})
3878 Don't quit; generate @file{ALI} and tree files even if illegalities.
3880 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3881 @cindex @option{-gnatR} (@code{gcc})
3882 Output representation information for declared types and objects.
3884 @item -gnats
3885 @cindex @option{-gnats} (@code{gcc})
3886 Syntax check only.
3888 @item -gnatS
3889 @cindex @option{-gnatS} (@code{gcc})
3890 Print package Standard.
3892 @item -gnatt
3893 @cindex @option{-gnatt} (@code{gcc})
3894 Generate tree output file.
3896 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3897 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3898 All compiler tables start at @var{nnn} times usual starting size.
3900 @item -gnatu
3901 @cindex @option{-gnatu} (@code{gcc})
3902 List units for this compilation.
3904 @item -gnatU
3905 @cindex @option{-gnatU} (@code{gcc})
3906 Tag all error messages with the unique string ``error:''
3908 @item -gnatv
3909 @cindex @option{-gnatv} (@code{gcc})
3910 Verbose mode. Full error output with source lines to @file{stdout}.
3912 @item -gnatV
3913 @cindex @option{-gnatV} (@code{gcc})
3914 Control level of validity checking. See separate section describing
3915 this feature.
3917 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3918 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3919 Warning mode where
3920 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3921 the exact warnings that
3922 are enabled or disabled. (see @ref{Warning Message Control})
3924 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3925 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3926 Wide character encoding method
3927 @ifclear vms
3928 (@var{e}=n/h/u/s/e/8).
3929 @end ifclear
3930 @ifset vms
3931 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3932 @end ifset
3934 @item -gnatx
3935 @cindex @option{-gnatx} (@code{gcc})
3936 Suppress generation of cross-reference information.
3938 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3939 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3940 Enable built-in style checks. (see @ref{Style Checking})
3942 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3943 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3944 Distribution stub generation and compilation
3945 @ifclear vms
3946 (@var{m}=r/c for receiver/caller stubs).
3947 @end ifclear
3948 @ifset vms
3949 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3950 to be generated and compiled).
3951 @end ifset
3953 @item -gnatZ
3954 Use the zero cost method for exception handling
3956 @item ^-I^/SEARCH=^@var{dir}
3957 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3958 @cindex RTL
3959 Direct GNAT to search the @var{dir} directory for source files needed by
3960 the current compilation
3961 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3963 @item ^-I-^/NOCURRENT_DIRECTORY^
3964 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3965 @cindex RTL
3966 Except for the source file named in the command line, do not look for source
3967 files in the directory containing the source file named in the command line
3968 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3970 @ifclear vms
3971 @item -mbig-switch
3972 @cindex @option{-mbig-switch} (@command{gcc})
3973 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3974 This standard gcc switch causes the compiler to use larger offsets in its
3975 jump table representation for @code{case} statements.
3976 This may result in less efficient code, but is sometimes necessary
3977 (for example on HP-UX targets)
3978 @cindex HP-UX and @option{-mbig-switch} option
3979 in order to compile large and/or nested @code{case} statements.
3981 @item -o @var{file}
3982 @cindex @option{-o} (@code{gcc})
3983 This switch is used in @code{gcc} to redirect the generated object file
3984 and its associated ALI file. Beware of this switch with GNAT, because it may
3985 cause the object file and ALI file to have different names which in turn
3986 may confuse the binder and the linker.
3987 @end ifclear
3989 @item -nostdinc
3990 @cindex @option{-nostdinc} (@command{gcc})
3991 Inhibit the search of the default location for the GNAT Run Time
3992 Library (RTL) source files.
3994 @item -nostdlib
3995 @cindex @option{-nostdlib} (@command{gcc})
3996 Inhibit the search of the default location for the GNAT Run Time
3997 Library (RTL) ALI files.
3999 @ifclear vms
4000 @item -O[@var{n}]
4001 @cindex @option{-O} (@code{gcc})
4002 @var{n} controls the optimization level.
4004 @table @asis
4005 @item n = 0
4006 No optimization, the default setting if no @option{-O} appears
4008 @item n = 1
4009 Normal optimization, the default if you specify @option{-O} without
4010 an operand.
4012 @item n = 2
4013 Extensive optimization
4015 @item n = 3
4016 Extensive optimization with automatic inlining of subprograms not
4017 specified by pragma @code{Inline}. This applies only to
4018 inlining within a unit. For details on control of inlining
4019 see @xref{Subprogram Inlining Control}.
4020 @end table
4021 @end ifclear
4023 @ifset vms
4024 @item  /NOOPTIMIZE
4025 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4026 Equivalent to @option{/OPTIMIZE=NONE}.
4027 This is the default behavior in the absence of an @option{/OPTMIZE}
4028 qualifier.
4030 @item /OPTIMIZE[=(keyword[,...])]
4031 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4032 Selects the level of optimization for your program. The supported
4033 keywords are as follows:
4034 @table @code
4035 @item   ALL
4036 Perform most optimizations, including those that
4037 are expensive.
4038 This is the default if the @option{/OPTMIZE} qualifier is supplied
4039 without keyword options.
4041 @item   NONE
4042 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4044 @item SOME
4045 Perform some optimizations, but omit ones that are costly.
4047 @item   DEVELOPMENT
4048 Same as @code{SOME}.
4050 @item   INLINING
4051 Full optimization, and also attempt automatic inlining of small
4052 subprograms within a unit even when pragma @code{Inline}
4053 is not specified (@pxref{Inlining of Subprograms}).
4055 @item   UNROLL_LOOPS
4056 Try to unroll loops. This keyword may be specified together with
4057 any keyword above other than @code{NONE}. Loop unrolling
4058 usually, but not always, improves the performance of programs.
4059 @end table
4060 @end ifset
4062 @ifclear vms
4063 @item -pass-exit-codes
4064 @cindex @option{-pass-exit-codes} (@code{gcc})
4065 Catch exit codes from the compiler and use the most meaningful as
4066 exit status.
4067 @end ifclear
4069 @item --RTS=@var{rts-path}
4070 @cindex @option{--RTS} (@code{gcc})
4071 Specifies the default location of the runtime library. Same meaning as the
4072 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4074 @item ^-S^/ASM^
4075 @cindex @option{^-S^/ASM^} (@code{gcc})
4076 ^Used in place of @option{-c} to^Used to^
4077 cause the assembler source file to be
4078 generated, using @file{^.s^.S^} as the extension,
4079 instead of the object file.
4080 This may be useful if you need to examine the generated assembly code.
4082 @item ^-v^/VERBOSE^
4083 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4084 Show commands generated by the @code{gcc} driver. Normally used only for
4085 debugging purposes or if you need to be sure what version of the
4086 compiler you are executing.
4088 @ifclear vms
4089 @item -V @var{ver}
4090 @cindex @option{-V} (@code{gcc})
4091 Execute @var{ver} version of the compiler. This is the @code{gcc}
4092 version, not the GNAT version.
4093 @end ifclear
4095 @end table
4097 @ifclear vms
4098 You may combine a sequence of GNAT switches into a single switch. For
4099 example, the combined switch
4101 @cindex Combining GNAT switches
4102 @smallexample
4103 -gnatofi3
4104 @end smallexample
4106 @noindent
4107 is equivalent to specifying the following sequence of switches:
4109 @smallexample
4110 -gnato -gnatf -gnati3
4111 @end smallexample
4112 @end ifclear
4115 @c NEED TO CHECK THIS FOR VMS
4117 @noindent
4118 The following restrictions apply to the combination of switches
4119 in this manner:
4121 @itemize @bullet
4122 @item
4123 The switch @option{-gnatc} if combined with other switches must come
4124 first in the string.
4126 @item
4127 The switch @option{-gnats} if combined with other switches must come
4128 first in the string.
4130 @item
4131 The switches
4132 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4133 may not be combined with any other switches.
4135 @ifclear vms
4136 @item
4137 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4138 switch), then all further characters in the switch are interpreted
4139 as style modifiers (see description of @option{-gnaty}).
4141 @item
4142 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4143 switch), then all further characters in the switch are interpreted
4144 as debug flags (see description of @option{-gnatd}).
4146 @item
4147 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4148 switch), then all further characters in the switch are interpreted
4149 as warning mode modifiers (see description of @option{-gnatw}).
4151 @item
4152 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4153 switch), then all further characters in the switch are interpreted
4154 as validity checking options (see description of @option{-gnatV}).
4155 @end ifclear
4156 @end itemize
4159 @node Output and Error Message Control
4160 @subsection Output and Error Message Control
4161 @findex stderr
4163 @noindent
4164 The standard default format for error messages is called ``brief format''.
4165 Brief format messages are written to @file{stderr} (the standard error
4166 file) and have the following form:
4168 @smallexample
4169 e.adb:3:04: Incorrect spelling of keyword "function"
4170 e.adb:4:20: ";" should be "is"
4171 @end smallexample
4173 @noindent
4174 The first integer after the file name is the line number in the file,
4175 and the second integer is the column number within the line.
4176 @code{glide} can parse the error messages
4177 and point to the referenced character.
4178 The following switches provide control over the error message
4179 format:
4181 @table @option
4182 @c !sort!
4183 @item -gnatv
4184 @cindex @option{-gnatv} (@code{gcc})
4185 @findex stdout
4186 @ifclear vms
4187 The v stands for verbose.
4188 @end ifclear
4189 The effect of this setting is to write long-format error
4190 messages to @file{stdout} (the standard output file.
4191 The same program compiled with the
4192 @option{-gnatv} switch would generate:
4194 @smallexample
4195 @cartouche
4196 3. funcion X (Q : Integer)
4197    |
4198 >>> Incorrect spelling of keyword "function"
4199 4. return Integer;
4200                  |
4201 >>> ";" should be "is"
4202 @end cartouche
4203 @end smallexample
4205 @noindent
4206 The vertical bar indicates the location of the error, and the @samp{>>>}
4207 prefix can be used to search for error messages. When this switch is
4208 used the only source lines output are those with errors.
4210 @item -gnatl
4211 @cindex @option{-gnatl} (@code{gcc})
4212 @ifclear vms
4213 The @code{l} stands for list.
4214 @end ifclear
4215 This switch causes a full listing of
4216 the file to be generated. The output might look as follows:
4218 @smallexample
4219 @cartouche
4220  1. procedure E is
4221  2.    V : Integer;
4222  3.    funcion X (Q : Integer)
4223        |
4224     >>> Incorrect spelling of keyword "function"
4225  4.     return Integer;
4226                       |
4227     >>> ";" should be "is"
4228  5.    begin
4229  6.       return Q + Q;
4230  7.    end;
4231  8. begin
4232  9.    V := X + X;
4233 10.end E;
4234 @end cartouche
4235 @end smallexample
4237 @noindent
4238 @findex stderr
4239 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4240 standard output is redirected, a brief summary is written to
4241 @file{stderr} (standard error) giving the number of error messages and
4242 warning messages generated.
4244 @item -gnatU
4245 @cindex @option{-gnatU} (@code{gcc})
4246 This switch forces all error messages to be preceded by the unique
4247 string ``error:''. This means that error messages take a few more
4248 characters in space, but allows easy searching for and identification
4249 of error messages.
4251 @item -gnatb
4252 @cindex @option{-gnatb} (@code{gcc})
4253 @ifclear vms
4254 The @code{b} stands for brief.
4255 @end ifclear
4256 This switch causes GNAT to generate the
4257 brief format error messages to @file{stderr} (the standard error
4258 file) as well as the verbose
4259 format message or full listing (which as usual is written to
4260 @file{stdout} (the standard output file).
4262 @item -gnatm^^=^@var{n}
4263 @cindex @option{-gnatm} (@code{gcc})
4264 @ifclear vms
4265 The @code{m} stands for maximum.
4266 @end ifclear
4267 @var{n} is a decimal integer in the
4268 range of 1 to 999 and limits the number of error messages to be
4269 generated. For example, using @option{-gnatm2} might yield
4271 @smallexample
4272 e.adb:3:04: Incorrect spelling of keyword "function"
4273 e.adb:5:35: missing ".."
4274 fatal error: maximum errors reached
4275 compilation abandoned
4276 @end smallexample
4278 @item -gnatf
4279 @cindex @option{-gnatf} (@code{gcc})
4280 @cindex Error messages, suppressing
4281 @ifclear vms
4282 The @code{f} stands for full.
4283 @end ifclear
4284 Normally, the compiler suppresses error messages that are likely to be
4285 redundant. This switch causes all error
4286 messages to be generated. In particular, in the case of
4287 references to undefined variables. If a given variable is referenced
4288 several times, the normal format of messages is
4289 @smallexample
4290 e.adb:7:07: "V" is undefined (more references follow)
4291 @end smallexample
4293 @noindent
4294 where the parenthetical comment warns that there are additional
4295 references to the variable @code{V}. Compiling the same program with the
4296 @option{-gnatf} switch yields
4298 @smallexample
4299 e.adb:7:07: "V" is undefined
4300 e.adb:8:07: "V" is undefined
4301 e.adb:8:12: "V" is undefined
4302 e.adb:8:16: "V" is undefined
4303 e.adb:9:07: "V" is undefined
4304 e.adb:9:12: "V" is undefined
4305 @end smallexample
4307 @noindent
4308 The @option{-gnatf} switch also generates additional information for
4309 some error messages.  Some examples are:
4311 @itemize @bullet
4312 @item
4313 Full details on entities not available in high integrity mode
4314 @item
4315 Details on possibly non-portable unchecked conversion
4316 @item
4317 List possible interpretations for ambiguous calls
4318 @item
4319 Additional details on incorrect parameters
4320 @end itemize
4323 @item -gnatq
4324 @cindex @option{-gnatq} (@code{gcc})
4325 @ifclear vms
4326 The @code{q} stands for quit (really ``don't quit'').
4327 @end ifclear
4328 In normal operation mode, the compiler first parses the program and
4329 determines if there are any syntax errors. If there are, appropriate
4330 error messages are generated and compilation is immediately terminated.
4331 This switch tells
4332 GNAT to continue with semantic analysis even if syntax errors have been
4333 found. This may enable the detection of more errors in a single run. On
4334 the other hand, the semantic analyzer is more likely to encounter some
4335 internal fatal error when given a syntactically invalid tree.
4337 @item -gnatQ
4338 @cindex @option{-gnatQ} (@code{gcc})
4339 In normal operation mode, the @file{ALI} file is not generated if any
4340 illegalities are detected in the program. The use of @option{-gnatQ} forces
4341 generation of the @file{ALI} file. This file is marked as being in
4342 error, so it cannot be used for binding purposes, but it does contain
4343 reasonably complete cross-reference information, and thus may be useful
4344 for use by tools (e.g. semantic browsing tools or integrated development
4345 environments) that are driven from the @file{ALI} file. This switch
4346 implies @option{-gnatq}, since the semantic phase must be run to get a
4347 meaningful ALI file.
4349 In addition, if @option{-gnatt} is also specified, then the tree file is
4350 generated even if there are illegalities. It may be useful in this case
4351 to also specify @option{-gnatq} to ensure that full semantic processing
4352 occurs. The resulting tree file can be processed by ASIS, for the purpose
4353 of providing partial information about illegal units, but if the error
4354 causes the tree to be badly malformed, then ASIS may crash during the
4355 analysis.
4357 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4358 being in error, @code{gnatmake} will attempt to recompile the source when it
4359 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4361 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4362 since ALI files are never generated if @option{-gnats} is set.
4364 @end table
4367 @node Warning Message Control
4368 @subsection Warning Message Control
4369 @cindex Warning messages
4370 @noindent
4371 In addition to error messages, which correspond to illegalities as defined
4372 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4373 situations.
4375 First, the compiler considers some constructs suspicious and generates a
4376 warning message to alert you to a possible error. Second, if the
4377 compiler detects a situation that is sure to raise an exception at
4378 run time, it generates a warning message. The following shows an example
4379 of warning messages:
4380 @smallexample
4381 e.adb:4:24: warning: creation of object may raise Storage_Error
4382 e.adb:10:17: warning: static value out of range
4383 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4384 @end smallexample
4386 @noindent
4387 GNAT considers a large number of situations as appropriate
4388 for the generation of warning messages. As always, warnings are not
4389 definite indications of errors. For example, if you do an out-of-range
4390 assignment with the deliberate intention of raising a
4391 @code{Constraint_Error} exception, then the warning that may be
4392 issued does not indicate an error. Some of the situations for which GNAT
4393 issues warnings (at least some of the time) are given in the following
4394 list. This list is not complete, and new warnings are often added to
4395 subsequent versions of GNAT. The list is intended to give a general idea
4396 of the kinds of warnings that are generated.
4398 @itemize @bullet
4399 @item
4400 Possible infinitely recursive calls
4402 @item
4403 Out-of-range values being assigned
4405 @item
4406 Possible order of elaboration problems
4408 @item
4409 Unreachable code
4411 @item
4412 Fixed-point type declarations with a null range
4414 @item
4415 Variables that are never assigned a value
4417 @item
4418 Variables that are referenced before being initialized
4420 @item
4421 Task entries with no corresponding @code{accept} statement
4423 @item
4424 Duplicate accepts for the same task entry in a @code{select}
4426 @item
4427 Objects that take too much storage
4429 @item
4430 Unchecked conversion between types of differing sizes
4432 @item
4433 Missing @code{return} statement along some execution path in a function
4435 @item
4436 Incorrect (unrecognized) pragmas
4438 @item
4439 Incorrect external names
4441 @item
4442 Allocation from empty storage pool
4444 @item
4445 Potentially blocking operation in protected type
4447 @item
4448 Suspicious parenthesization of expressions
4450 @item
4451 Mismatching bounds in an aggregate
4453 @item
4454 Attempt to return local value by reference
4457 @item
4458 Premature instantiation of a generic body
4460 @item
4461 Attempt to pack aliased components
4463 @item
4464 Out of bounds array subscripts
4466 @item
4467 Wrong length on string assignment
4469 @item
4470 Violations of style rules if style checking is enabled
4472 @item
4473 Unused @code{with} clauses
4475 @item
4476 @code{Bit_Order} usage that does not have any effect
4478 @item
4479 @code{Standard.Duration} used to resolve universal fixed expression
4481 @item
4482 Dereference of possibly null value
4484 @item
4485 Declaration that is likely to cause storage error
4487 @item
4488 Internal GNAT unit @code{with}'ed by application unit
4490 @item
4491 Values known to be out of range at compile time
4493 @item
4494 Unreferenced labels and variables
4496 @item
4497 Address overlays that could clobber memory
4499 @item
4500 Unexpected initialization when address clause present
4502 @item
4503 Bad alignment for address clause
4505 @item
4506 Useless type conversions
4508 @item
4509 Redundant assignment statements and other redundant constructs
4511 @item
4512 Useless exception handlers
4514 @item
4515 Accidental hiding of name by child unit
4518 @item
4519 Access before elaboration detected at compile time
4521 @item
4522 A range in a @code{for} loop that is known to be null or might be null
4524 @end itemize
4526 @noindent
4527 The following switches are available to control the handling of
4528 warning messages:
4530 @table @option
4531 @c !sort!
4532 @item -gnatwa
4533 @emph{Activate all optional errors.}
4534 @cindex @option{-gnatwa} (@code{gcc})
4535 This switch activates most optional warning messages, see remaining list
4536 in this section for details on optional warning messages that can be
4537 individually controlled.  The warnings that are not turned on by this
4538 switch are
4539 @option{-gnatwd} (implicit dereferencing),
4540 @option{-gnatwh} (hiding),
4541 and @option{-gnatwl} (elaboration warnings).
4542 All other optional warnings are turned on.
4544 @item -gnatwA
4545 @emph{Suppress all optional errors.}
4546 @cindex @option{-gnatwA} (@code{gcc})
4547 This switch suppresses all optional warning messages, see remaining list
4548 in this section for details on optional warning messages that can be
4549 individually controlled.
4551 @item -gnatwc
4552 @emph{Activate warnings on conditionals.}
4553 @cindex @option{-gnatwc} (@code{gcc})
4554 @cindex Conditionals, constant
4555 This switch activates warnings for conditional expressions used in
4556 tests that are known to be True or False at compile time. The default
4557 is that such warnings are not generated.
4558 Note that this warning does
4559 not get issued for the use of boolean variables or constants whose
4560 values are known at compile time, since this is a standard technique
4561 for conditional compilation in Ada, and this would generate too many
4562 ``false positive'' warnings.
4563 This warning can also be turned on using @option{-gnatwa}.
4565 @item -gnatwC
4566 @emph{Suppress warnings on conditionals.}
4567 @cindex @option{-gnatwC} (@code{gcc})
4568 This switch suppresses warnings for conditional expressions used in
4569 tests that are known to be True or False at compile time.
4571 @item -gnatwd
4572 @emph{Activate warnings on implicit dereferencing.}
4573 @cindex @option{-gnatwd} (@code{gcc})
4574 If this switch is set, then the use of a prefix of an access type
4575 in an indexed component, slice, or selected component without an
4576 explicit @code{.all} will generate a warning. With this warning
4577 enabled, access checks occur only at points where an explicit
4578 @code{.all} appears in the source code (assuming no warnings are
4579 generated as a result of this switch). The default is that such
4580 warnings are not generated.
4581 Note that @option{-gnatwa} does not affect the setting of
4582 this warning option.
4584 @item -gnatwD
4585 @emph{Suppress warnings on implicit dereferencing.}
4586 @cindex @option{-gnatwD} (@code{gcc})
4587 @cindex Implicit dereferencing
4588 @cindex Dereferencing, implicit
4589 This switch suppresses warnings for implicit dereferences in
4590 indexed components, slices, and selected components.
4592 @item -gnatwe
4593 @emph{Treat warnings as errors.}
4594 @cindex @option{-gnatwe} (@code{gcc})
4595 @cindex Warnings, treat as error
4596 This switch causes warning messages to be treated as errors.
4597 The warning string still appears, but the warning messages are counted
4598 as errors, and prevent the generation of an object file.
4600 @item -gnatwf
4601 @emph{Activate warnings on unreferenced formals.}
4602 @cindex @option{-gnatwf} (@code{gcc})
4603 @cindex Formals, unreferenced
4604 This switch causes a warning to be generated if a formal parameter
4605 is not referenced in the body of the subprogram. This warning can
4606 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4608 @item -gnatwF
4609 @emph{Suppress warnings on unreferenced formals.}
4610 @cindex @option{-gnatwF} (@code{gcc})
4611 This switch suppresses warnings for unreferenced formal
4612 parameters. Note that the
4613 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4614 effect of warning on unreferenced entities other than subprogram
4615 formals.
4617 @item -gnatwg
4618 @emph{Activate warnings on unrecognized pragmas.}
4619 @cindex @option{-gnatwg} (@code{gcc})
4620 @cindex Pragmas, unrecognized
4621 This switch causes a warning to be generated if an unrecognized
4622 pragma is encountered. Apart from issuing this warning, the
4623 pragma is ignored and has no effect. This warning can
4624 also be turned on using @option{-gnatwa}. The default
4625 is that such warnings are issued (satisfying the Ada Reference
4626 Manual requirement that such warnings appear).
4628 @item -gnatwG
4629 @emph{Suppress warnings on unrecognized pragmas.}
4630 @cindex @option{-gnatwG} (@code{gcc})
4631 This switch suppresses warnings for unrecognized pragmas.
4633 @item -gnatwh
4634 @emph{Activate warnings on hiding.}
4635 @cindex @option{-gnatwh} (@code{gcc})
4636 @cindex Hiding of Declarations
4637 This switch activates warnings on hiding declarations.
4638 A declaration is considered hiding
4639 if it is for a non-overloadable entity, and it declares an entity with the
4640 same name as some other entity that is directly or use-visible. The default
4641 is that such warnings are not generated.
4642 Note that @option{-gnatwa} does not affect the setting of this warning option.
4644 @item -gnatwH
4645 @emph{Suppress warnings on hiding.}
4646 @cindex @option{-gnatwH} (@code{gcc})
4647 This switch suppresses warnings on hiding declarations.
4649 @item -gnatwi
4650 @emph{Activate warnings on implementation units.}
4651 @cindex @option{-gnatwi} (@code{gcc})
4652 This switch activates warnings for a @code{with} of an internal GNAT
4653 implementation unit, defined as any unit from the @code{Ada},
4654 @code{Interfaces}, @code{GNAT},
4655 ^^@code{DEC},^ or @code{System}
4656 hierarchies that is not
4657 documented in either the Ada Reference Manual or the GNAT
4658 Programmer's Reference Manual. Such units are intended only
4659 for internal implementation purposes and should not be @code{with}'ed
4660 by user programs. The default is that such warnings are generated
4661 This warning can also be turned on using @option{-gnatwa}.
4663 @item -gnatwI
4664 @emph{Disable warnings on implementation units.}
4665 @cindex @option{-gnatwI} (@code{gcc})
4666 This switch disables warnings for a @code{with} of an internal GNAT
4667 implementation unit.
4669 @item -gnatwj
4670 @emph{Activate warnings on obsolescent features (Annex J).}
4671 @cindex @option{-gnatwj} (@code{gcc})
4672 @cindex Features, obsolescent
4673 @cindex Obsolescent features
4674 If this warning option is activated, then warnings are generated for
4675 calls to subprograms marked with @code{pragma Obsolescent} and
4676 for use of features in Annex J of the Ada Reference Manual. In the
4677 case of Annex J, not all features are flagged. In particular use
4678 of the renamed packages (like @code{Text_IO}) and use of package
4679 @code{ASCII} are not flagged, since these are very common and
4680 would generate many annoying positive warnings. The default is that
4681 such warnings are not generated.
4683 @item -gnatwJ
4684 @emph{Suppress warnings on obsolescent features (Annex J).}
4685 @cindex @option{-gnatwJ} (@code{gcc})
4686 This switch disables warnings on use of obsolescent features.
4688 @item -gnatwk
4689 @emph{Activate warnings on variables that could be constants.}
4690 @cindex @option{-gnatwk} (@code{gcc})
4691 This switch activates warnings for variables that are initialized but
4692 never modified, and then could be declared constants.
4694 @item -gnatwK
4695 @emph{Suppress warnings on variables that could be constants.}
4696 @cindex @option{-gnatwK} (@code{gcc})
4697 This switch disables warnings on variables that could be declared constants.
4699 @item -gnatwl
4700 @emph{Activate warnings for missing elaboration pragmas.}
4701 @cindex @option{-gnatwl} (@code{gcc})
4702 @cindex Elaboration, warnings
4703 This switch activates warnings on missing
4704 @code{pragma Elaborate_All} statements.
4705 See the section in this guide on elaboration checking for details on
4706 when such pragma should be used. Warnings are also generated if you
4707 are using the static mode of elaboration, and a @code{pragma Elaborate}
4708 is encountered. The default is that such warnings
4709 are not generated.
4710 This warning is not automatically turned on by the use of @option{-gnatwa}.
4712 @item -gnatwL
4713 @emph{Suppress warnings for missing elaboration pragmas.}
4714 @cindex @option{-gnatwL} (@code{gcc})
4715 This switch suppresses warnings on missing pragma Elaborate_All statements.
4716 See the section in this guide on elaboration checking for details on
4717 when such pragma should be used.
4719 @item -gnatwm
4720 @emph{Activate warnings on modified but unreferenced variables.}
4721 @cindex @option{-gnatwm} (@code{gcc})
4722 This switch activates warnings for variables that are assigned (using
4723 an initialization value or with one or more assignment statements) but
4724 whose value is never read. The warning is suppressed for volatile
4725 variables and also for variables that are renamings of other variables
4726 or for which an address clause is given.
4727 This warning can also be turned on using @option{-gnatwa}.
4729 @item -gnatwM
4730 @emph{Disable warnings on modified but unreferenced variables.}
4731 @cindex @option{-gnatwM} (@code{gcc})
4732 This switch disables warnings for variables that are assigned or
4733 initialized, but never read.
4735 @item -gnatwn
4736 @emph{Set normal warnings mode.}
4737 @cindex @option{-gnatwn} (@code{gcc})
4738 This switch sets normal warning mode, in which enabled warnings are
4739 issued and treated as warnings rather than errors. This is the default
4740 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4741 an explicit @option{-gnatws} or
4742 @option{-gnatwe}. It also cancels the effect of the
4743 implicit @option{-gnatwe} that is activated by the
4744 use of @option{-gnatg}.
4746 @item -gnatwo
4747 @emph{Activate warnings on address clause overlays.}
4748 @cindex @option{-gnatwo} (@code{gcc})
4749 @cindex Address Clauses, warnings
4750 This switch activates warnings for possibly unintended initialization
4751 effects of defining address clauses that cause one variable to overlap
4752 another. The default is that such warnings are generated.
4753 This warning can also be turned on using @option{-gnatwa}.
4755 @item -gnatwO
4756 @emph{Suppress warnings on address clause overlays.}
4757 @cindex @option{-gnatwO} (@code{gcc})
4758 This switch suppresses warnings on possibly unintended initialization
4759 effects of defining address clauses that cause one variable to overlap
4760 another.
4762 @item -gnatwp
4763 @emph{Activate warnings on ineffective pragma Inlines.}
4764 @cindex @option{-gnatwp} (@code{gcc})
4765 @cindex Inlining, warnings
4766 This switch activates warnings for failure of front end inlining
4767 (activated by @option{-gnatN}) to inline a particular call. There are
4768 many reasons for not being able to inline a call, including most
4769 commonly that the call is too complex to inline.
4770 This warning can also be turned on using @option{-gnatwa}.
4772 @item -gnatwP
4773 @emph{Suppress warnings on ineffective pragma Inlines.}
4774 @cindex @option{-gnatwP} (@code{gcc})
4775 This switch suppresses warnings on ineffective pragma Inlines. If the
4776 inlining mechanism cannot inline a call, it will simply ignore the
4777 request silently.
4779 @item -gnatwr
4780 @emph{Activate warnings on redundant constructs.}
4781 @cindex @option{-gnatwr} (@code{gcc})
4782 This switch activates warnings for redundant constructs. The following
4783 is the current list of constructs regarded as redundant:
4784 This warning can also be turned on using @option{-gnatwa}.
4786 @itemize @bullet
4787 @item
4788 Assignment of an item to itself.
4789 @item
4790 Type conversion that converts an expression to its own type.
4791 @item
4792 Use of the attribute @code{Base} where @code{typ'Base} is the same
4793 as @code{typ}.
4794 @item
4795 Use of pragma @code{Pack} when all components are placed by a record
4796 representation clause.
4797 @item
4798 Exception handler containing only a reraise statement (raise with no
4799 operand) which has no effect.
4800 @item
4801 Use of the operator abs on an operand that is known at compile time
4802 to be non-negative
4803 @item
4804 Use of an unnecessary extra level of parentheses (C-style) around conditions
4805 in @code{if} statements, @code{while} statements and @code{exit} statements.
4806 @item
4807 Comparison of boolean expressions to an explicit True value.
4808 @end itemize
4810 @item -gnatwR
4811 @emph{Suppress warnings on redundant constructs.}
4812 @cindex @option{-gnatwR} (@code{gcc})
4813 This switch suppresses warnings for redundant constructs.
4815 @item -gnatws
4816 @emph{Suppress all warnings.}
4817 @cindex @option{-gnatws} (@code{gcc})
4818 This switch completely suppresses the
4819 output of all warning messages from the GNAT front end.
4820 Note that it does not suppress warnings from the @code{gcc} back end.
4821 To suppress these back end warnings as well, use the switch @option{-w}
4822 in addition to @option{-gnatws}.
4824 @item -gnatwu
4825 @emph{Activate warnings on unused entities.}
4826 @cindex @option{-gnatwu} (@code{gcc})
4827 This switch activates warnings to be generated for entities that
4828 are declared but not referenced, and for units that are @code{with}'ed
4829 and not
4830 referenced. In the case of packages, a warning is also generated if
4831 no entities in the package are referenced. This means that if the package
4832 is referenced but the only references are in @code{use}
4833 clauses or @code{renames}
4834 declarations, a warning is still generated. A warning is also generated
4835 for a generic package that is @code{with}'ed but never instantiated.
4836 In the case where a package or subprogram body is compiled, and there
4837 is a @code{with} on the corresponding spec
4838 that is only referenced in the body,
4839 a warning is also generated, noting that the
4840 @code{with} can be moved to the body. The default is that
4841 such warnings are not generated.
4842 This switch also activates warnings on unreferenced formals
4843 (it is includes the effect of @option{-gnatwf}).
4844 This warning can also be turned on using @option{-gnatwa}.
4846 @item -gnatwU
4847 @emph{Suppress warnings on unused entities.}
4848 @cindex @option{-gnatwU} (@code{gcc})
4849 This switch suppresses warnings for unused entities and packages.
4850 It also turns off warnings on unreferenced formals (and thus includes
4851 the effect of @option{-gnatwF}).
4853 @item -gnatwv
4854 @emph{Activate warnings on unassigned variables.}
4855 @cindex @option{-gnatwv} (@code{gcc})
4856 @cindex Unassigned variable warnings
4857 This switch activates warnings for access to variables which
4858 may not be properly initialized. The default is that
4859 such warnings are generated.
4861 @item -gnatwV
4862 @emph{Suppress warnings on unassigned variables.}
4863 @cindex @option{-gnatwV} (@code{gcc})
4864 This switch suppresses warnings for access to variables which
4865 may not be properly initialized.
4867 @item -gnatwx
4868 @emph{Activate warnings on Export/Import pragmas.}
4869 @cindex @option{-gnatwx} (@code{gcc})
4870 @cindex Export/Import pragma warnings
4871 This switch activates warnings on Export/Import pragmas when
4872 the compiler detects a possible conflict between the Ada and
4873 foreign language calling sequences. For example, the use of
4874 default parameters in a convention C procedure is dubious
4875 because the C compiler cannot supply the proper default, so
4876 a warning is issued. The default is that such warnings are
4877 generated.
4879 @item -gnatwX
4880 @emph{Suppress warnings on Export/Import pragmas.}
4881 @cindex @option{-gnatwX} (@code{gcc})
4882 This switch suppresses warnings on Export/Import pragmas.
4883 The sense of this is that you are telling the compiler that
4884 you know what you are doing in writing the pragma, and it
4885 should not complain at you.
4887 @item -gnatwz
4888 @emph{Activate warnings on unchecked conversions.}
4889 @cindex @option{-gnatwz} (@code{gcc})
4890 @cindex Unchecked_Conversion warnings
4891 This switch activates warnings for unchecked conversions
4892 where the types are known at compile time to have different
4893 sizes. The default
4894 is that such warnings are generated.
4896 @item -gnatwZ
4897 @emph{Suppress warnings on unchecked conversions.}
4898 @cindex @option{-gnatwZ} (@code{gcc})
4899 This switch suppresses warnings for unchecked conversions
4900 where the types are known at compile time to have different
4901 sizes.
4903 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4904 @cindex @option{-Wuninitialized}
4905 The warnings controlled by the @option{-gnatw} switch are generated by the
4906 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4907 can provide additional warnings. One such useful warning is provided by
4908 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4909 conjunction with tunrning on optimization mode. This causes the flow
4910 analysis circuits of the back end optimizer to output additional
4911 warnings about uninitialized variables.
4913 @item ^-w^/NO_BACK_END_WARNINGS^
4914 @cindex @option{-w}
4915 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4916 be used in conjunction with @option{-gnatws} to ensure that all warnings
4917 are suppressed during the entire compilation process.
4919 @end table
4921 @noindent
4922 @ifclear vms
4923 A string of warning parameters can be used in the same parameter. For example:
4925 @smallexample
4926 -gnatwaLe
4927 @end smallexample
4929 @noindent
4930 will turn on all optional warnings except for elaboration pragma warnings,
4931 and also specify that warnings should be treated as errors.
4932 @end ifclear
4933 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4935 @table @option
4936 @c !sort!
4937 @item -gnatwC
4938 @item -gnatwD
4939 @item -gnatwF
4940 @item -gnatwg
4941 @item -gnatwH
4942 @item -gnatwi
4943 @item -gnatwJ
4944 @item -gnatwK
4945 @item -gnatwL
4946 @item -gnatwM
4947 @item -gnatwn
4948 @item -gnatwo
4949 @item -gnatwP
4950 @item -gnatwR
4951 @item -gnatwU
4952 @item -gnatwv
4953 @item -gnatwz
4954 @item -gnatwx
4956 @end table
4959 @node Debugging and Assertion Control
4960 @subsection Debugging and Assertion Control
4962 @table @option
4963 @item -gnata
4964 @cindex @option{-gnata} (@code{gcc})
4965 @findex Assert
4966 @findex Debug
4967 @cindex Assertions
4969 @noindent
4970 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4971 are ignored. This switch, where @samp{a} stands for assert, causes
4972 @code{Assert} and @code{Debug} pragmas to be activated.
4974 The pragmas have the form:
4976 @smallexample
4977 @cartouche
4978    @b{pragma} Assert (@var{Boolean-expression} [,
4979                       @var{static-string-expression}])
4980    @b{pragma} Debug (@var{procedure call})
4981 @end cartouche
4982 @end smallexample
4984 @noindent
4985 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4986 If the result is @code{True}, the pragma has no effect (other than
4987 possible side effects from evaluating the expression). If the result is
4988 @code{False}, the exception @code{Assert_Failure} declared in the package
4989 @code{System.Assertions} is
4990 raised (passing @var{static-string-expression}, if present, as the
4991 message associated with the exception). If no string expression is
4992 given the default is a string giving the file name and line number
4993 of the pragma.
4995 The @code{Debug} pragma causes @var{procedure} to be called. Note that
4996 @code{pragma Debug} may appear within a declaration sequence, allowing
4997 debugging procedures to be called between declarations.
4999 @ifset vms
5000 @item /DEBUG[=debug-level]
5001 @itemx  /NODEBUG
5002 Specifies how much debugging information is to be included in
5003 the resulting object file where 'debug-level' is one of the following:
5004 @table @code
5005 @item   TRACEBACK
5006 Include both debugger symbol records and traceback
5007 the object file.
5008 This is the default setting.
5009 @item   ALL
5010 Include both debugger symbol records and traceback in
5011 object file.
5012 @item   NONE
5013 Excludes both debugger symbol records and traceback
5014 the object file. Same as /NODEBUG.
5015 @item   SYMBOLS
5016 Includes only debugger symbol records in the object
5017 file. Note that this doesn't include traceback information.
5018 @end table
5019 @end ifset
5020 @end table
5022 @node Validity Checking
5023 @subsection Validity Checking
5024 @findex Validity Checking
5026 @noindent
5027 The Ada 95 Reference Manual has specific requirements for checking
5028 for invalid values. In particular, RM 13.9.1 requires that the
5029 evaluation of invalid values (for example from unchecked conversions),
5030 not result in erroneous execution. In GNAT, the result of such an
5031 evaluation in normal default mode is to either use the value
5032 unmodified, or to raise Constraint_Error in those cases where use
5033 of the unmodified value would cause erroneous execution. The cases
5034 where unmodified values might lead to erroneous execution are case
5035 statements (where a wild jump might result from an invalid value),
5036 and subscripts on the left hand side (where memory corruption could
5037 occur as a result of an invalid value).
5039 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5040 checking mode.
5041 @ifclear vms
5042 The @code{x} argument is a string of letters that
5043 indicate validity checks that are performed or not performed in addition
5044 to the default checks described above.
5045 @end ifclear
5046 @ifset vms
5047 The options allowed for this qualifier
5048 indicate validity checks that are performed or not performed in addition
5049 to the default checks described above.
5050 @end ifset
5053 @table @option
5054 @c !sort!
5055 @item -gnatVa
5056 @emph{All validity checks.}
5057 @cindex @option{-gnatVa} (@code{gcc})
5058 All validity checks are turned on.
5059 @ifclear vms
5060 That is, @option{-gnatVa} is
5061 equivalent to @option{gnatVcdfimorst}.
5062 @end ifclear
5064 @item -gnatVc
5065 @emph{Validity checks for copies.}
5066 @cindex @option{-gnatVc} (@code{gcc})
5067 The right hand side of assignments, and the initializing values of
5068 object declarations are validity checked.
5070 @item -gnatVd
5071 @emph{Default (RM) validity checks.}
5072 @cindex @option{-gnatVd} (@code{gcc})
5073 Some validity checks are done by default following normal Ada semantics
5074 (RM 13.9.1 (9-11)).
5075 A check is done in case statements that the expression is within the range
5076 of the subtype. If it is not, Constraint_Error is raised.
5077 For assignments to array components, a check is done that the expression used
5078 as index is within the range. If it is not, Constraint_Error is raised.
5079 Both these validity checks may be turned off using switch @option{-gnatVD}.
5080 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5081 switch @option{-gnatVd} will leave the checks turned on.
5082 Switch @option{-gnatVD} should be used only if you are sure that all such
5083 expressions have valid values. If you use this switch and invalid values
5084 are present, then the program is erroneous, and wild jumps or memory
5085 overwriting may occur.
5087 @item -gnatVf
5088 @emph{Validity checks for floating-point values.}
5089 @cindex @option{-gnatVf} (@code{gcc})
5090 In the absence of this switch, validity checking occurs only for discrete
5091 values. If @option{-gnatVf} is specified, then validity checking also applies
5092 for floating-point values, and NaN's and infinities are considered invalid,
5093 as well as out of range values for constrained types. Note that this means
5094 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5095 in which floating-point values are checked depends on the setting of other
5096 options. For example,
5097 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5098 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5099 (the order does not matter) specifies that floating-point parameters of mode
5100 @code{in} should be validity checked.
5102 @item -gnatVi
5103 @emph{Validity checks for @code{in} mode parameters}
5104 @cindex @option{-gnatVi} (@code{gcc})
5105 Arguments for parameters of mode @code{in} are validity checked in function
5106 and procedure calls at the point of call.
5108 @item -gnatVm
5109 @emph{Validity checks for @code{in out} mode parameters.}
5110 @cindex @option{-gnatVm} (@code{gcc})
5111 Arguments for parameters of mode @code{in out} are validity checked in
5112 procedure calls at the point of call. The @code{'m'} here stands for
5113 modify, since this concerns parameters that can be modified by the call.
5114 Note that there is no specific option to test @code{out} parameters,
5115 but any reference within the subprogram will be tested in the usual
5116 manner, and if an invalid value is copied back, any reference to it
5117 will be subject to validity checking.
5119 @item -gnatVn
5120 @emph{No validity checks.}
5121 @cindex @option{-gnatVn} (@code{gcc})
5122 This switch turns off all validity checking, including the default checking
5123 for case statements and left hand side subscripts. Note that the use of
5124 the switch @option{-gnatp} suppresses all run-time checks, including
5125 validity checks, and thus implies @option{-gnatVn}. When this switch
5126 is used, it cancels any other @option{-gnatV} previously issued.
5128 @item -gnatVo
5129 @emph{Validity checks for operator and attribute operands.}
5130 @cindex @option{-gnatVo} (@code{gcc})
5131 Arguments for predefined operators and attributes are validity checked.
5132 This includes all operators in package @code{Standard},
5133 the shift operators defined as intrinsic in package @code{Interfaces}
5134 and operands for attributes such as @code{Pos}. Checks are also made
5135 on individual component values for composite comparisons.
5137 @item -gnatVp
5138 @emph{Validity checks for parameters.}
5139 @cindex @option{-gnatVp} (@code{gcc})
5140 This controls the treatment of parameters within a subprogram (as opposed
5141 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5142 of parameters on a call. If either of these call options is used, then
5143 normally an assumption is made within a subprogram that the input arguments
5144 have been validity checking at the point of call, and do not need checking
5145 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5146 is not made, and parameters are not assumed to be valid, so their validity
5147 will be checked (or rechecked) within the subprogram.
5149 @item -gnatVr
5150 @emph{Validity checks for function returns.}
5151 @cindex @option{-gnatVr} (@code{gcc})
5152 The expression in @code{return} statements in functions is validity
5153 checked.
5155 @item -gnatVs
5156 @emph{Validity checks for subscripts.}
5157 @cindex @option{-gnatVs} (@code{gcc})
5158 All subscripts expressions are checked for validity, whether they appear
5159 on the right side or left side (in default mode only left side subscripts
5160 are validity checked).
5162 @item -gnatVt
5163 @emph{Validity checks for tests.}
5164 @cindex @option{-gnatVt} (@code{gcc})
5165 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5166 statements are checked, as well as guard expressions in entry calls.
5168 @end table
5170 @noindent
5171 The @option{-gnatV} switch may be followed by
5172 ^a string of letters^a list of options^
5173 to turn on a series of validity checking options.
5174 For example,
5175 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5176 specifies that in addition to the default validity checking, copies and
5177 function return expressions are to be validity checked.
5178 In order to make it easier
5179 to specify the desired combination of effects,
5180 @ifclear vms
5181 the upper case letters @code{CDFIMORST} may
5182 be used to turn off the corresponding lower case option.
5183 @end ifclear
5184 @ifset vms
5185 the prefix @code{NO} on an option turns off the corresponding validity
5186 checking:
5187 @itemize @bullet
5188 @item @code{NOCOPIES}
5189 @item @code{NODEFAULT}
5190 @item @code{NOFLOATS}
5191 @item @code{NOIN_PARAMS}
5192 @item @code{NOMOD_PARAMS}
5193 @item @code{NOOPERANDS}
5194 @item @code{NORETURNS}
5195 @item @code{NOSUBSCRIPTS}
5196 @item @code{NOTESTS}
5197 @end itemize
5198 @end ifset
5199 Thus
5200 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5201 turns on all validity checking options except for
5202 checking of @code{@b{in out}} procedure arguments.
5204 The specification of additional validity checking generates extra code (and
5205 in the case of @option{-gnatVa} the code expansion can be substantial.
5206 However, these additional checks can be very useful in detecting
5207 uninitialized variables, incorrect use of unchecked conversion, and other
5208 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5209 is useful in conjunction with the extra validity checking, since this
5210 ensures that wherever possible uninitialized variables have invalid values.
5212 See also the pragma @code{Validity_Checks} which allows modification of
5213 the validity checking mode at the program source level, and also allows for
5214 temporary disabling of validity checks.
5217 @node Style Checking
5218 @subsection Style Checking
5219 @findex Style checking
5221 @noindent
5222 The @option{-gnaty^x^(option,option,...)^} switch
5223 @cindex @option{-gnaty} (@code{gcc})
5224 causes the compiler to
5225 enforce specified style rules. A limited set of style rules has been used
5226 in writing the GNAT sources themselves. This switch allows user programs
5227 to activate all or some of these checks. If the source program fails a
5228 specified style check, an appropriate warning message is given, preceded by
5229 the character sequence ``(style)''.
5230 @ifset vms
5231 @code{(option,option,...)} is a sequence of keywords
5232 @end ifset
5233 @ifclear vms
5234 The string @var{x} is a sequence of letters or digits
5235 @end ifclear
5236 indicating the particular style
5237 checks to be performed. The following checks are defined:
5239 @table @option
5240 @c !sort!
5241 @item 1-9
5242 @emph{Specify indentation level.}
5243 If a digit from 1-9 appears
5244 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5245 then proper indentation is checked, with the digit indicating the
5246 indentation level required.
5247 The general style of required indentation is as specified by
5248 the examples in the Ada Reference Manual. Full line comments must be
5249 aligned with the @code{--} starting on a column that is a multiple of
5250 the alignment level.
5252 @item ^a^ATTRIBUTE^
5253 @emph{Check attribute casing.}
5254 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5255 then attribute names, including the case of keywords such as @code{digits}
5256 used as attributes names, must be written in mixed case, that is, the
5257 initial letter and any letter following an underscore must be uppercase.
5258 All other letters must be lowercase.
5260 @item ^b^BLANKS^
5261 @emph{Blanks not allowed at statement end.}
5262 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5263 trailing blanks are not allowed at the end of statements. The purpose of this
5264 rule, together with h (no horizontal tabs), is to enforce a canonical format
5265 for the use of blanks to separate source tokens.
5267 @item ^c^COMMENTS^
5268 @emph{Check comments.}
5269 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5270 then comments must meet the following set of rules:
5272 @itemize @bullet
5274 @item
5275 The ``@code{--}'' that starts the column must either start in column one,
5276 or else at least one blank must precede this sequence.
5278 @item
5279 Comments that follow other tokens on a line must have at least one blank
5280 following the ``@code{--}'' at the start of the comment.
5282 @item
5283 Full line comments must have two blanks following the ``@code{--}'' that
5284 starts the comment, with the following exceptions.
5286 @item
5287 A line consisting only of the ``@code{--}'' characters, possibly preceded
5288 by blanks is permitted.
5290 @item
5291 A comment starting with ``@code{--x}'' where @code{x} is a special character
5292 is permitted.
5293 This allows proper processing of the output generated by specialized tools
5294 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5295 annotation
5296 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5297 special character is defined as being in one of the ASCII ranges
5298 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5299 Note that this usage is not permitted
5300 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5302 @item
5303 A line consisting entirely of minus signs, possibly preceded by blanks, is
5304 permitted. This allows the construction of box comments where lines of minus
5305 signs are used to form the top and bottom of the box.
5307 @item
5308 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5309 least one blank follows the initial ``@code{--}''. Together with the preceding
5310 rule, this allows the construction of box comments, as shown in the following
5311 example:
5312 @smallexample
5313 ---------------------------
5314 -- This is a box comment --
5315 -- with two text lines.  --
5316 ---------------------------
5317 @end smallexample
5318 @end itemize
5320 @item ^e^END^
5321 @emph{Check end/exit labels.}
5322 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5323 optional labels on @code{end} statements ending subprograms and on
5324 @code{exit} statements exiting named loops, are required to be present.
5326 @item ^f^VTABS^
5327 @emph{No form feeds or vertical tabs.}
5328 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5329 neither form feeds nor vertical tab characters are not permitted
5330 in the source text.
5332 @item ^h^HTABS^
5333 @emph{No horizontal tabs.}
5334 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5335 horizontal tab characters are not permitted in the source text.
5336 Together with the b (no blanks at end of line) check, this
5337 enforces a canonical form for the use of blanks to separate
5338 source tokens.
5340 @item ^i^IF_THEN^
5341 @emph{Check if-then layout.}
5342 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5343 then the keyword @code{then} must appear either on the same
5344 line as corresponding @code{if}, or on a line on its own, lined
5345 up under the @code{if} with at least one non-blank line in between
5346 containing all or part of the condition to be tested.
5348 @item ^k^KEYWORD^
5349 @emph{Check keyword casing.}
5350 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5351 all keywords must be in lower case (with the exception of keywords
5352 such as @code{digits} used as attribute names to which this check
5353 does not apply).
5355 @item ^l^LAYOUT^
5356 @emph{Check layout.}
5357 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5358 layout of statement and declaration constructs must follow the
5359 recommendations in the Ada Reference Manual, as indicated by the
5360 form of the syntax rules. For example an @code{else} keyword must
5361 be lined up with the corresponding @code{if} keyword.
5363 There are two respects in which the style rule enforced by this check
5364 option are more liberal than those in the Ada Reference Manual. First
5365 in the case of record declarations, it is permissible to put the
5366 @code{record} keyword on the same line as the @code{type} keyword, and
5367 then the @code{end} in @code{end record} must line up under @code{type}.
5368 For example, either of the following two layouts is acceptable:
5370 @smallexample @c ada
5371 @cartouche
5372 type q is record
5373    a : integer;
5374    b : integer;
5375 end record;
5377 type q is
5378    record
5379       a : integer;
5380       b : integer;
5381    end record;
5382 @end cartouche
5383 @end smallexample
5385 @noindent
5386 Second, in the case of a block statement, a permitted alternative
5387 is to put the block label on the same line as the @code{declare} or
5388 @code{begin} keyword, and then line the @code{end} keyword up under
5389 the block label. For example both the following are permitted:
5391 @smallexample @c ada
5392 @cartouche
5393 Block : declare
5394    A : Integer := 3;
5395 begin
5396    Proc (A, A);
5397 end Block;
5399 Block :
5400    declare
5401       A : Integer := 3;
5402    begin
5403       Proc (A, A);
5404    end Block;
5405 @end cartouche
5406 @end smallexample
5408 @noindent
5409 The same alternative format is allowed for loops. For example, both of
5410 the following are permitted:
5412 @smallexample @c ada
5413 @cartouche
5414 Clear : while J < 10 loop
5415    A (J) := 0;
5416 end loop Clear;
5418 Clear :
5419    while J < 10 loop
5420       A (J) := 0;
5421    end loop Clear;
5422 @end cartouche
5423 @end smallexample
5425 @item ^m^LINE_LENGTH^
5426 @emph{Check maximum line length.}
5427 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5428 then the length of source lines must not exceed 79 characters, including
5429 any trailing blanks. The value of 79 allows convenient display on an
5430 80 character wide device or window, allowing for possible special
5431 treatment of 80 character lines. Note that this count is of raw
5432 characters in the source text. This means that a tab character counts
5433 as one character in this count and a wide character sequence counts as
5434 several characters (however many are needed in the encoding).
5436 @item ^Mnnn^MAX_LENGTH=nnn^
5437 @emph{Set maximum line length.}
5438 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5439 the string after @option{-gnaty} then the length of lines must not exceed the
5440 given value.
5442 @item ^n^STANDARD_CASING^
5443 @emph{Check casing of entities in Standard.}
5444 If the ^letter n^word STANDARD_CASING^ appears in the string
5445 after @option{-gnaty} then any identifier from Standard must be cased
5446 to match the presentation in the Ada Reference Manual (for example,
5447 @code{Integer} and @code{ASCII.NUL}).
5449 @item ^o^ORDERED_SUBPROGRAMS^
5450 @emph{Check order of subprogram bodies.}
5451 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5452 after @option{-gnaty} then all subprogram bodies in a given scope
5453 (e.g. a package body) must be in alphabetical order. The ordering
5454 rule uses normal Ada rules for comparing strings, ignoring casing
5455 of letters, except that if there is a trailing numeric suffix, then
5456 the value of this suffix is used in the ordering (e.g. Junk2 comes
5457 before Junk10).
5459 @item ^p^PRAGMA^
5460 @emph{Check pragma casing.}
5461 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5462 pragma names must be written in mixed case, that is, the
5463 initial letter and any letter following an underscore must be uppercase.
5464 All other letters must be lowercase.
5466 @item ^r^REFERENCES^
5467 @emph{Check references.}
5468 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5469 then all identifier references must be cased in the same way as the
5470 corresponding declaration. No specific casing style is imposed on
5471 identifiers. The only requirement is for consistency of references
5472 with declarations.
5474 @item ^s^SPECS^
5475 @emph{Check separate specs.}
5476 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5477 separate declarations (``specs'') are required for subprograms (a
5478 body is not allowed to serve as its own declaration). The only
5479 exception is that parameterless library level procedures are
5480 not required to have a separate declaration. This exception covers
5481 the most frequent form of main program procedures.
5483 @item ^t^TOKEN^
5484 @emph{Check token spacing.}
5485 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5486 the following token spacing rules are enforced:
5488 @itemize @bullet
5490 @item
5491 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5493 @item
5494 The token @code{=>} must be surrounded by spaces.
5496 @item
5497 The token @code{<>} must be preceded by a space or a left parenthesis.
5499 @item
5500 Binary operators other than @code{**} must be surrounded by spaces.
5501 There is no restriction on the layout of the @code{**} binary operator.
5503 @item
5504 Colon must be surrounded by spaces.
5506 @item
5507 Colon-equal (assignment, initialization) must be surrounded by spaces.
5509 @item
5510 Comma must be the first non-blank character on the line, or be
5511 immediately preceded by a non-blank character, and must be followed
5512 by a space.
5514 @item
5515 If the token preceding a left parenthesis ends with a letter or digit, then
5516 a space must separate the two tokens.
5518 @item
5519 A right parenthesis must either be the first non-blank character on
5520 a line, or it must be preceded by a non-blank character.
5522 @item
5523 A semicolon must not be preceded by a space, and must not be followed by
5524 a non-blank character.
5526 @item
5527 A unary plus or minus may not be followed by a space.
5529 @item
5530 A vertical bar must be surrounded by spaces.
5531 @end itemize
5533 @noindent
5534 In the above rules, appearing in column one is always permitted, that is,
5535 counts as meeting either a requirement for a required preceding space,
5536 or as meeting a requirement for no preceding space.
5538 Appearing at the end of a line is also always permitted, that is, counts
5539 as meeting either a requirement for a following space, or as meeting
5540 a requirement for no following space.
5542 @end table
5544 @noindent
5545 If any of these style rules is violated, a message is generated giving
5546 details on the violation. The initial characters of such messages are
5547 always ``@code{(style)}''. Note that these messages are treated as warning
5548 messages, so they normally do not prevent the generation of an object
5549 file. The @option{-gnatwe} switch can be used to treat warning messages,
5550 including style messages, as fatal errors.
5552 The switch
5553 @ifclear vms
5554 @option{-gnaty} on its own (that is not
5555 followed by any letters or digits),
5556 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5557 options enabled with the exception of -gnatyo,
5558 @end ifclear
5559 @ifset vms
5560 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5561 the exception of ORDERED_SUBPROGRAMS,
5562 @end ifset
5563 with an indentation level of 3. This is the standard
5564 checking option that is used for the GNAT sources.
5566 The switch
5567 @ifclear vms
5568 @option{-gnatyN}
5569 @end ifclear
5570 @ifset vms
5571 /STYLE_CHECKS=NONE
5572 @end ifset
5573 clears any previously set style checks.
5575 @node Run-Time Checks
5576 @subsection Run-Time Checks
5577 @cindex Division by zero
5578 @cindex Access before elaboration
5579 @cindex Checks, division by zero
5580 @cindex Checks, access before elaboration
5582 @noindent
5583 If you compile with the default options, GNAT will insert many run-time
5584 checks into the compiled code, including code that performs range
5585 checking against constraints, but not arithmetic overflow checking for
5586 integer operations (including division by zero) or checks for access
5587 before elaboration on subprogram calls. All other run-time checks, as
5588 required by the Ada 95 Reference Manual, are generated by default.
5589 The following @code{gcc} switches refine this default behavior:
5591 @table @option
5592 @c !sort!
5593 @item -gnatp
5594 @cindex @option{-gnatp} (@code{gcc})
5595 @cindex Suppressing checks
5596 @cindex Checks, suppressing
5597 @findex Suppress
5598 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5599 had been present in the source. Validity checks are also suppressed (in
5600 other words @option{-gnatp} also implies @option{-gnatVn}.
5601 Use this switch to improve the performance
5602 of the code at the expense of safety in the presence of invalid data or
5603 program bugs.
5605 @item -gnato
5606 @cindex @option{-gnato} (@code{gcc})
5607 @cindex Overflow checks
5608 @cindex Check, overflow
5609 Enables overflow checking for integer operations.
5610 This causes GNAT to generate slower and larger executable
5611 programs by adding code to check for overflow (resulting in raising
5612 @code{Constraint_Error} as required by standard Ada
5613 semantics). These overflow checks correspond to situations in which
5614 the true value of the result of an operation may be outside the base
5615 range of the result type. The following example shows the distinction:
5617 @smallexample @c ada
5618 X1 : Integer := Integer'Last;
5619 X2 : Integer range 1 .. 5 := 5;
5620 X3 : Integer := Integer'Last;
5621 X4 : Integer range 1 .. 5 := 5;
5622 F  : Float := 2.0E+20;
5624 X1 := X1 + 1;
5625 X2 := X2 + 1;
5626 X3 := Integer (F);
5627 X4 := Integer (F);
5628 @end smallexample
5630 @noindent
5631 Here the first addition results in a value that is outside the base range
5632 of Integer, and hence requires an overflow check for detection of the
5633 constraint error. Thus the first assignment to @code{X1} raises a
5634 @code{Constraint_Error} exception only if @option{-gnato} is set.
5636 The second increment operation results in a violation
5637 of the explicit range constraint, and such range checks are always
5638 performed (unless specifically suppressed with a pragma @code{suppress}
5639 or the use of @option{-gnatp}).
5641 The two conversions of @code{F} both result in values that are outside
5642 the base range of type @code{Integer} and thus will raise
5643 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5644 The fact that the result of the second conversion is assigned to
5645 variable @code{X4} with a restricted range is irrelevant, since the problem
5646 is in the conversion, not the assignment.
5648 Basically the rule is that in the default mode (@option{-gnato} not
5649 used), the generated code assures that all integer variables stay
5650 within their declared ranges, or within the base range if there is
5651 no declared range. This prevents any serious problems like indexes
5652 out of range for array operations.
5654 What is not checked in default mode is an overflow that results in
5655 an in-range, but incorrect value. In the above example, the assignments
5656 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5657 range of the target variable, but the result is wrong in the sense that
5658 it is too large to be represented correctly. Typically the assignment
5659 to @code{X1} will result in wrap around to the largest negative number.
5660 The conversions of @code{F} will result in some @code{Integer} value
5661 and if that integer value is out of the @code{X4} range then the
5662 subsequent assignment would generate an exception.
5664 @findex Machine_Overflows
5665 Note that the @option{-gnato} switch does not affect the code generated
5666 for any floating-point operations; it applies only to integer
5667 semantics).
5668 For floating-point, GNAT has the @code{Machine_Overflows}
5669 attribute set to @code{False} and the normal mode of operation is to
5670 generate IEEE NaN and infinite values on overflow or invalid operations
5671 (such as dividing 0.0 by 0.0).
5673 The reason that we distinguish overflow checking from other kinds of
5674 range constraint checking is that a failure of an overflow check can
5675 generate an incorrect value, but cannot cause erroneous behavior. This
5676 is unlike the situation with a constraint check on an array subscript,
5677 where failure to perform the check can result in random memory description,
5678 or the range check on a case statement, where failure to perform the check
5679 can cause a wild jump.
5681 Note again that @option{-gnato} is off by default, so overflow checking is
5682 not performed in default mode. This means that out of the box, with the
5683 default settings, GNAT does not do all the checks expected from the
5684 language description in the Ada Reference Manual. If you want all constraint
5685 checks to be performed, as described in this Manual, then you must
5686 explicitly use the -gnato switch either on the @code{gnatmake} or
5687 @code{gcc} command.
5689 @item -gnatE
5690 @cindex @option{-gnatE} (@code{gcc})
5691 @cindex Elaboration checks
5692 @cindex Check, elaboration
5693 Enables dynamic checks for access-before-elaboration
5694 on subprogram calls and generic instantiations.
5695 For full details of the effect and use of this switch,
5696 @xref{Compiling Using gcc}.
5697 @end table
5699 @findex Unsuppress
5700 @noindent
5701 The setting of these switches only controls the default setting of the
5702 checks. You may modify them using either @code{Suppress} (to remove
5703 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5704 the program source.
5706 @node Stack Overflow Checking
5707 @subsection Stack Overflow Checking
5708 @cindex Stack Overflow Checking
5709 @cindex -fstack-check
5711 @noindent
5712 For most operating systems, @code{gcc} does not perform stack overflow
5713 checking by default. This means that if the main environment task or
5714 some other task exceeds the available stack space, then unpredictable
5715 behavior will occur.
5717 To activate stack checking, compile all units with the gcc option
5718 @option{-fstack-check}. For example:
5720 @smallexample
5721 gcc -c -fstack-check package1.adb
5722 @end smallexample
5724 @noindent
5725 Units compiled with this option will generate extra instructions to check
5726 that any use of the stack (for procedure calls or for declaring local
5727 variables in declare blocks) do not exceed the available stack space.
5728 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5730 For declared tasks, the stack size is always controlled by the size
5731 given in an applicable @code{Storage_Size} pragma (or is set to
5732 the default size if no pragma is used.
5734 For the environment task, the stack size depends on
5735 system defaults and is unknown to the compiler. The stack
5736 may even dynamically grow on some systems, precluding the
5737 normal Ada semantics for stack overflow. In the worst case,
5738 unbounded stack usage, causes unbounded stack expansion
5739 resulting in the system running out of virtual memory.
5741 The stack checking may still work correctly if a fixed
5742 size stack is allocated, but this cannot be guaranteed.
5743 To ensure that a clean exception is signalled for stack
5744 overflow, set the environment variable
5745 @code{GNAT_STACK_LIMIT} to indicate the maximum
5746 stack area that can be used, as in:
5747 @cindex GNAT_STACK_LIMIT
5749 @smallexample
5750 SET GNAT_STACK_LIMIT 1600
5751 @end smallexample
5753 @noindent
5754 The limit is given in kilobytes, so the above declaration would
5755 set the stack limit of the environment task to 1.6 megabytes.
5756 Note that the only purpose of this usage is to limit the amount
5757 of stack used by the environment task. If it is necessary to
5758 increase the amount of stack for the environment task, then this
5759 is an operating systems issue, and must be addressed with the
5760 appropriate operating systems commands.
5763 @node Using gcc for Syntax Checking
5764 @subsection Using @code{gcc} for Syntax Checking
5765 @table @option
5766 @item -gnats
5767 @cindex @option{-gnats} (@code{gcc})
5768 @ifclear vms
5770 @noindent
5771 The @code{s} stands for ``syntax''.
5772 @end ifclear
5774 Run GNAT in syntax checking only mode. For
5775 example, the command
5777 @smallexample
5778 $ gcc -c -gnats x.adb
5779 @end smallexample
5781 @noindent
5782 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5783 series of files in a single command
5784 @ifclear vms
5785 , and can use wild cards to specify such a group of files.
5786 Note that you must specify the @option{-c} (compile
5787 only) flag in addition to the @option{-gnats} flag.
5788 @end ifclear
5790 You may use other switches in conjunction with @option{-gnats}. In
5791 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5792 format of any generated error messages.
5794 When the source file is empty or contains only empty lines and/or comments,
5795 the output is a warning:
5797 @smallexample
5798 $ gcc -c -gnats -x ada toto.txt
5799 toto.txt:1:01: warning: empty file, contains no compilation units
5801 @end smallexample
5803 Otherwise, the output is simply the error messages, if any. No object file or
5804 ALI file is generated by a syntax-only compilation. Also, no units other
5805 than the one specified are accessed. For example, if a unit @code{X}
5806 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5807 check only mode does not access the source file containing unit
5808 @code{Y}.
5810 @cindex Multiple units, syntax checking
5811 Normally, GNAT allows only a single unit in a source file. However, this
5812 restriction does not apply in syntax-check-only mode, and it is possible
5813 to check a file containing multiple compilation units concatenated
5814 together. This is primarily used by the @code{gnatchop} utility
5815 (@pxref{Renaming Files Using gnatchop}).
5816 @end table
5819 @node Using gcc for Semantic Checking
5820 @subsection Using @code{gcc} for Semantic Checking
5821 @table @option
5822 @item -gnatc
5823 @cindex @option{-gnatc} (@code{gcc})
5825 @ifclear vms
5826 @noindent
5827 The @code{c} stands for ``check''.
5828 @end ifclear
5829 Causes the compiler to operate in semantic check mode,
5830 with full checking for all illegalities specified in the
5831 Ada 95 Reference Manual, but without generation of any object code
5832 (no object file is generated).
5834 Because dependent files must be accessed, you must follow the GNAT
5835 semantic restrictions on file structuring to operate in this mode:
5837 @itemize @bullet
5838 @item
5839 The needed source files must be accessible
5840 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5842 @item
5843 Each file must contain only one compilation unit.
5845 @item
5846 The file name and unit name must match (@pxref{File Naming Rules}).
5847 @end itemize
5849 The output consists of error messages as appropriate. No object file is
5850 generated. An @file{ALI} file is generated for use in the context of
5851 cross-reference tools, but this file is marked as not being suitable
5852 for binding (since no object file is generated).
5853 The checking corresponds exactly to the notion of
5854 legality in the Ada 95 Reference Manual.
5856 Any unit can be compiled in semantics-checking-only mode, including
5857 units that would not normally be compiled (subunits,
5858 and specifications where a separate body is present).
5859 @end table
5861 @node Compiling Ada 83 Programs
5862 @subsection Compiling Ada 83 Programs
5863 @table @option
5864 @cindex Ada 83 compatibility
5865 @item -gnat83
5866 @cindex @option{-gnat83} (@code{gcc})
5867 @cindex ACVC, Ada 83 tests
5869 @noindent
5870 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5871 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5872 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5873 where this can be done easily.
5874 It is not possible to guarantee this switch does a perfect
5875 job; for example, some subtle tests, such as are
5876 found in earlier ACVC tests (and that have been removed from the ACATS suite
5877 for Ada 95), might not compile correctly.
5878 Nevertheless, this switch may be useful in some circumstances, for example
5879 where, due to contractual reasons, legacy code needs to be maintained
5880 using only Ada 83 features.
5882 With few exceptions (most notably the need to use @code{<>} on
5883 @cindex Generic formal parameters
5884 unconstrained generic formal parameters, the use of the new Ada 95
5885 reserved words, and the use of packages
5886 with optional bodies), it is not necessary to use the
5887 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5888 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5889 means that a correct Ada 83 program is usually also a correct Ada 95
5890 program.
5891 For further information, please refer to @ref{Compatibility and Porting Guide}.
5893 @end table
5895 @node Character Set Control
5896 @subsection Character Set Control
5897 @table @option
5898 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5899 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5901 @noindent
5902 Normally GNAT recognizes the Latin-1 character set in source program
5903 identifiers, as described in the Ada 95 Reference Manual.
5904 This switch causes
5905 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5906 single character ^^or word^ indicating the character set, as follows:
5908 @table @code
5909 @item 1
5910 ISO 8859-1 (Latin-1) identifiers
5912 @item 2
5913 ISO 8859-2 (Latin-2) letters allowed in identifiers
5915 @item 3
5916 ISO 8859-3 (Latin-3) letters allowed in identifiers
5918 @item 4
5919 ISO 8859-4 (Latin-4) letters allowed in identifiers
5921 @item 5
5922 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5924 @item 9
5925 ISO 8859-15 (Latin-9) letters allowed in identifiers
5927 @item ^p^PC^
5928 IBM PC letters (code page 437) allowed in identifiers
5930 @item ^8^PC850^
5931 IBM PC letters (code page 850) allowed in identifiers
5933 @item ^f^FULL_UPPER^
5934 Full upper-half codes allowed in identifiers
5936 @item ^n^NO_UPPER^
5937 No upper-half codes allowed in identifiers
5939 @item ^w^WIDE^
5940 Wide-character codes (that is, codes greater than 255)
5941 allowed in identifiers
5942 @end table
5944 @xref{Foreign Language Representation}, for full details on the
5945 implementation of these character sets.
5947 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5948 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5949 Specify the method of encoding for wide characters.
5950 @var{e} is one of the following:
5952 @table @code
5954 @item ^h^HEX^
5955 Hex encoding (brackets coding also recognized)
5957 @item ^u^UPPER^
5958 Upper half encoding (brackets encoding also recognized)
5960 @item ^s^SHIFT_JIS^
5961 Shift/JIS encoding (brackets encoding also recognized)
5963 @item ^e^EUC^
5964 EUC encoding (brackets encoding also recognized)
5966 @item ^8^UTF8^
5967 UTF-8 encoding (brackets encoding also recognized)
5969 @item ^b^BRACKETS^
5970 Brackets encoding only (default value)
5971 @end table
5972 For full details on the these encoding
5973 methods see @xref{Wide Character Encodings}.
5974 Note that brackets coding is always accepted, even if one of the other
5975 options is specified, so for example @option{-gnatW8} specifies that both
5976 brackets and @code{UTF-8} encodings will be recognized. The units that are
5977 with'ed directly or indirectly will be scanned using the specified
5978 representation scheme, and so if one of the non-brackets scheme is
5979 used, it must be used consistently throughout the program. However,
5980 since brackets encoding is always recognized, it may be conveniently
5981 used in standard libraries, allowing these libraries to be used with
5982 any of the available coding schemes.
5983 scheme. If no @option{-gnatW?} parameter is present, then the default
5984 representation is Brackets encoding only.
5986 Note that the wide character representation that is specified (explicitly
5987 or by default) for the main program also acts as the default encoding used
5988 for Wide_Text_IO files if not specifically overridden by a WCEM form
5989 parameter.
5991 @end table
5992 @node File Naming Control
5993 @subsection File Naming Control
5995 @table @option
5996 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
5997 @cindex @option{-gnatk} (@code{gcc})
5998 Activates file name ``krunching''. @var{n}, a decimal integer in the range
5999 1-999, indicates the maximum allowable length of a file name (not
6000 including the @file{.ads} or @file{.adb} extension). The default is not
6001 to enable file name krunching.
6003 For the source file naming rules, @xref{File Naming Rules}.
6004 @end table
6007 @node Subprogram Inlining Control
6008 @subsection Subprogram Inlining Control
6010 @table @option
6011 @c !sort!
6012 @item -gnatn
6013 @cindex @option{-gnatn} (@code{gcc})
6014 @ifclear vms
6015 The @code{n} here is intended to suggest the first syllable of the
6016 word ``inline''.
6017 @end ifclear
6018 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6019 inlining to actually occur, optimization must be enabled. To enable
6020 inlining of subprograms specified by pragma @code{Inline},
6021 you must also specify this switch.
6022 In the absence of this switch, GNAT does not attempt
6023 inlining and does not need to access the bodies of
6024 subprograms for which @code{pragma Inline} is specified if they are not
6025 in the current unit.
6027 If you specify this switch the compiler will access these bodies,
6028 creating an extra source dependency for the resulting object file, and
6029 where possible, the call will be inlined.
6030 For further details on when inlining is possible
6031 see @xref{Inlining of Subprograms}.
6033 @item -gnatN
6034 @cindex @option{-gnatN} (@code{gcc})
6035 The front end inlining activated by this switch is generally more extensive,
6036 and quite often more effective than the standard @option{-gnatn} inlining mode.
6037 It will also generate additional dependencies.
6038 Note that
6039 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6040 to specify both options.
6041 @end table
6043 @node Auxiliary Output Control
6044 @subsection Auxiliary Output Control
6046 @table @option
6047 @item -gnatt
6048 @cindex @option{-gnatt} (@code{gcc})
6049 @cindex Writing internal trees
6050 @cindex Internal trees, writing to file
6051 Causes GNAT to write the internal tree for a unit to a file (with the
6052 extension @file{.adt}.
6053 This not normally required, but is used by separate analysis tools.
6054 Typically
6055 these tools do the necessary compilations automatically, so you should
6056 not have to specify this switch in normal operation.
6058 @item -gnatu
6059 @cindex @option{-gnatu} (@code{gcc})
6060 Print a list of units required by this compilation on @file{stdout}.
6061 The listing includes all units on which the unit being compiled depends
6062 either directly or indirectly.
6064 @ifclear vms
6065 @item -pass-exit-codes
6066 @cindex @option{-pass-exit-codes} (@code{gcc})
6067 If this switch is not used, the exit code returned by @code{gcc} when
6068 compiling multiple files indicates whether all source files have
6069 been successfully used to generate object files or not.
6071 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6072 exit status and allows an integrated development environment to better
6073 react to a compilation failure. Those exit status are:
6075 @table @asis
6076 @item 5
6077 There was an error in at least one source file.
6078 @item 3
6079 At least one source file did not generate an object file.
6080 @item 2
6081 The compiler died unexpectedly (internal error for example).
6082 @item 0
6083 An object file has been generated for every source file.
6084 @end table
6085 @end ifclear
6086 @end table
6088 @node Debugging Control
6089 @subsection Debugging Control
6091 @table @option
6092 @c !sort!
6093 @cindex Debugging options
6094 @ifclear vms
6095 @item -gnatd@var{x}
6096 @cindex @option{-gnatd} (@code{gcc})
6097 Activate internal debugging switches. @var{x} is a letter or digit, or
6098 string of letters or digits, which specifies the type of debugging
6099 outputs desired. Normally these are used only for internal development
6100 or system debugging purposes. You can find full documentation for these
6101 switches in the body of the @code{Debug} unit in the compiler source
6102 file @file{debug.adb}.
6103 @end ifclear
6105 @item -gnatG
6106 @cindex @option{-gnatG} (@code{gcc})
6107 This switch causes the compiler to generate auxiliary output containing
6108 a pseudo-source listing of the generated expanded code. Like most Ada
6109 compilers, GNAT works by first transforming the high level Ada code into
6110 lower level constructs. For example, tasking operations are transformed
6111 into calls to the tasking run-time routines. A unique capability of GNAT
6112 is to list this expanded code in a form very close to normal Ada source.
6113 This is very useful in understanding the implications of various Ada
6114 usage on the efficiency of the generated code. There are many cases in
6115 Ada (e.g. the use of controlled types), where simple Ada statements can
6116 generate a lot of run-time code. By using @option{-gnatG} you can identify
6117 these cases, and consider whether it may be desirable to modify the coding
6118 approach to improve efficiency.
6120 The format of the output is very similar to standard Ada source, and is
6121 easily understood by an Ada programmer. The following special syntactic
6122 additions correspond to low level features used in the generated code that
6123 do not have any exact analogies in pure Ada source form. The following
6124 is a partial list of these special constructions. See the specification
6125 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6127 @table @code
6128 @item new @var{xxx} [storage_pool = @var{yyy}]
6129 Shows the storage pool being used for an allocator.
6131 @item at end @var{procedure-name};
6132 Shows the finalization (cleanup) procedure for a scope.
6134 @item (if @var{expr} then @var{expr} else @var{expr})
6135 Conditional expression equivalent to the @code{x?y:z} construction in C.
6137 @item @var{target}^^^(@var{source})
6138 A conversion with floating-point truncation instead of rounding.
6140 @item @var{target}?(@var{source})
6141 A conversion that bypasses normal Ada semantic checking. In particular
6142 enumeration types and fixed-point types are treated simply as integers.
6144 @item @var{target}?^^^(@var{source})
6145 Combines the above two cases.
6147 @item @var{x} #/ @var{y}
6148 @itemx @var{x} #mod @var{y}
6149 @itemx @var{x} #* @var{y}
6150 @itemx @var{x} #rem @var{y}
6151 A division or multiplication of fixed-point values which are treated as
6152 integers without any kind of scaling.
6154 @item free @var{expr} [storage_pool = @var{xxx}]
6155 Shows the storage pool associated with a @code{free} statement.
6157 @item freeze @var{typename} [@var{actions}]
6158 Shows the point at which @var{typename} is frozen, with possible
6159 associated actions to be performed at the freeze point.
6161 @item reference @var{itype}
6162 Reference (and hence definition) to internal type @var{itype}.
6164 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6165 Intrinsic function call.
6167 @item @var{labelname} : label
6168 Declaration of label @var{labelname}.
6170 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6171 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6172 @var{expr}, but handled more efficiently).
6174 @item [constraint_error]
6175 Raise the @code{Constraint_Error} exception.
6177 @item @var{expression}'reference
6178 A pointer to the result of evaluating @var{expression}.
6180 @item @var{target-type}!(@var{source-expression})
6181 An unchecked conversion of @var{source-expression} to @var{target-type}.
6183 @item [@var{numerator}/@var{denominator}]
6184 Used to represent internal real literals (that) have no exact
6185 representation in base 2-16 (for example, the result of compile time
6186 evaluation of the expression 1.0/27.0).
6187 @end table
6189 @item -gnatD
6190 @cindex @option{-gnatD} (@code{gcc})
6191 When used in conjunction with @option{-gnatG}, this switch causes
6192 the expanded source, as described above for
6193 @option{-gnatG} to be written to files with names
6194 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6195 instead of to the standard ooutput file. For
6196 example, if the source file name is @file{hello.adb}, then a file
6197 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6198 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6199 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6200 you to do source level debugging using the generated code which is
6201 sometimes useful for complex code, for example to find out exactly
6202 which part of a complex construction raised an exception. This switch
6203 also suppress generation of cross-reference information (see
6204 @option{-gnatx}) since otherwise the cross-reference information
6205 would refer to the @file{^.dg^.DG^} file, which would cause
6206 confusion since this is not the original source file.
6208 Note that @option{-gnatD} actually implies @option{-gnatG}
6209 automatically, so it is not necessary to give both options.
6210 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6212 @ifclear vms
6213 @item -gnatR[0|1|2|3[s]]
6214 @cindex @option{-gnatR} (@code{gcc})
6215 This switch controls output from the compiler of a listing showing
6216 representation information for declared types and objects. For
6217 @option{-gnatR0}, no information is output (equivalent to omitting
6218 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6219 so @option{-gnatR} with no parameter has the same effect), size and alignment
6220 information is listed for declared array and record types. For
6221 @option{-gnatR2}, size and alignment information is listed for all
6222 expression information for values that are computed at run time for
6223 variant records. These symbolic expressions have a mostly obvious
6224 format with #n being used to represent the value of the n'th
6225 discriminant. See source files @file{repinfo.ads/adb} in the
6226 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6227 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6228 the output is to a file with the name @file{^file.rep^file_REP^} where
6229 file is the name of the corresponding source file.
6230 @end ifclear
6231 @ifset vms
6232 @item /REPRESENTATION_INFO
6233 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6234 This qualifier controls output from the compiler of a listing showing
6235 representation information for declared types and objects. For
6236 @option{/REPRESENTATION_INFO=NONE}, no information is output
6237 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6238 @option{/REPRESENTATION_INFO} without option is equivalent to
6239 @option{/REPRESENTATION_INFO=ARRAYS}.
6240 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6241 information is listed for declared array and record types. For
6242 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6243 is listed for all expression information for values that are computed
6244 at run time for variant records. These symbolic expressions have a mostly
6245 obvious format with #n being used to represent the value of the n'th
6246 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6247 @code{GNAT} sources for full details on the format of
6248 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6249 If _FILE is added at the end of an option
6250 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6251 then the output is to a file with the name @file{file_REP} where
6252 file is the name of the corresponding source file.
6253 @end ifset
6255 @item -gnatS
6256 @cindex @option{-gnatS} (@code{gcc})
6257 The use of the switch @option{-gnatS} for an
6258 Ada compilation will cause the compiler to output a
6259 representation of package Standard in a form very
6260 close to standard Ada. It is not quite possible to
6261 do this and remain entirely Standard (since new
6262 numeric base types cannot be created in standard
6263 Ada), but the output is easily
6264 readable to any Ada programmer, and is useful to
6265 determine the characteristics of target dependent
6266 types in package Standard.
6268 @item -gnatx
6269 @cindex @option{-gnatx} (@code{gcc})
6270 Normally the compiler generates full cross-referencing information in
6271 the @file{ALI} file. This information is used by a number of tools,
6272 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6273 suppresses this information. This saves some space and may slightly
6274 speed up compilation, but means that these tools cannot be used.
6275 @end table
6277 @node Exception Handling Control
6278 @subsection Exception Handling Control
6280 @noindent
6281 GNAT uses two methods for handling exceptions at run-time. The
6282 @code{longjmp/setjmp} method saves the context when entering
6283 a frame with an exception handler. Then when an exception is
6284 raised, the context can be restored immediately, without the
6285 need for tracing stack frames. This method provides very fast
6286 exception propagation, but introduces significant overhead for
6287 the use of exception handlers, even if no exception is raised.
6289 The other approach is called ``zero cost'' exception handling.
6290 With this method, the compiler builds static tables to describe
6291 the exception ranges. No dynamic code is required when entering
6292 a frame containing an exception handler. When an exception is
6293 raised, the tables are used to control a back trace of the
6294 subprogram invocation stack to locate the required exception
6295 handler. This method has considerably poorer performance for
6296 the propagation of exceptions, but there is no overhead for
6297 exception handlers if no exception is raised.
6299 The following switches can be used to control which of the
6300 two exception handling methods is used.
6302 @table @option
6303 @c !sort!
6305 @item -gnatL
6306 @cindex @option{-gnatL} (@code{gcc})
6307 This switch causes the longjmp/setjmp approach to be used
6308 for exception handling. If this is the default mechanism for the
6309 target (see below), then this has no effect. If the default
6310 mechanism for the target is zero cost exceptions, then
6311 this switch can be used to modify this default, but it must be
6312 used for all units in the partition, including all run-time
6313 library units. One way to achieve this is to use the
6314 @option{-a} and @option{-f} switches for @code{gnatmake}.
6315 This option is rarely used. One case in which it may be
6316 advantageous is if you have an application where exception
6317 raising is common and the overall performance of the
6318 application is improved by favoring exception propagation.
6320 @item -gnatZ
6321 @cindex @option{-gnatZ} (@code{gcc})
6322 @cindex Zero Cost Exceptions
6323 This switch causes the zero cost approach to be sed
6324 for exception handling. If this is the default mechanism for the
6325 target (see below), then this has no effect. If the default
6326 mechanism for the target is longjmp/setjmp exceptions, then
6327 this switch can be used to modify this default, but it must be
6328 used for all units in the partition, including all run-time
6329 library units. One way to achieve this is to use the
6330 @option{-a} and @option{-f} switches for @code{gnatmake}.
6331 This option can only be used if the zero cost approach
6332 is available for the target in use (see below).
6333 @end table
6335 @noindent
6336 The @code{longjmp/setjmp} approach is available on all targets, but
6337 the @code{zero cost} approach is only available on selected targets.
6338 To determine whether zero cost exceptions can be used for a
6339 particular target, look at the private part of the file system.ads.
6340 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6341 be True to use the zero cost approach. If both of these switches
6342 are set to False, this means that zero cost exception handling
6343 is not yet available for that target. The switch
6344 @code{ZCX_By_Default} indicates the default approach. If this
6345 switch is set to True, then the @code{zero cost} approach is
6346 used by default.
6348 @node Units to Sources Mapping Files
6349 @subsection Units to Sources Mapping Files
6351 @table @option
6353 @item -gnatem^^=^@var{path}
6354 @cindex @option{-gnatem} (@code{gcc})
6355 A mapping file is a way to communicate to the compiler two mappings:
6356 from unit names to file names (without any directory information) and from
6357 file names to path names (with full directory information). These mappings
6358 are used by the compiler to short-circuit the path search.
6360 The use of mapping files is not required for correct operation of the
6361 compiler, but mapping files can improve efficiency, particularly when
6362 sources are read over a slow network connection. In normal operation,
6363 you need not be concerned with the format or use of mapping files,
6364 and the @option{-gnatem} switch is not a switch that you would use
6365 explicitly. it is intended only for use by automatic tools such as
6366 @code{gnatmake} running under the project file facility. The
6367 description here of the format of mapping files is provided
6368 for completeness and for possible use by other tools.
6370 A mapping file is a sequence of sets of three lines. In each set,
6371 the first line is the unit name, in lower case, with ``@code{%s}''
6372 appended for
6373 specifications and ``@code{%b}'' appended for bodies; the second line is the
6374 file name; and the third line is the path name.
6376 Example:
6377 @smallexample
6378    main%b
6379    main.2.ada
6380    /gnat/project1/sources/main.2.ada
6381 @end smallexample
6383 When the switch @option{-gnatem} is specified, the compiler will create
6384 in memory the two mappings from the specified file. If there is any problem
6385 (non existent file, truncated file or duplicate entries), no mapping
6386 will be created.
6388 Several @option{-gnatem} switches may be specified; however, only the last
6389 one on the command line will be taken into account.
6391 When using a project file, @code{gnatmake} create a temporary mapping file
6392 and communicates it to the compiler using this switch.
6394 @end table
6397 @node Integrated Preprocessing
6398 @subsection Integrated Preprocessing
6400 @noindent
6401 GNAT sources may be preprocessed immediately before compilation; the actual
6402 text of the source is not the text of the source file, but is derived from it
6403 through a process called preprocessing. Integrated preprocessing is specified
6404 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6405 indicates, through a text file, the preprocessing data to be used.
6406 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6408 @noindent
6409 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6410 used when Integrated Preprocessing is used. The reason is that preprocessing
6411 with another Preprocessing Data file without changing the sources will
6412 not trigger recompilation without this switch.
6414 @noindent
6415 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6416 always trigger recompilation for sources that are preprocessed,
6417 because @code{gnatmake} cannot compute the checksum of the source after
6418 preprocessing.
6420 @noindent
6421 The actual preprocessing function is described in details in section
6422 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6423 preprocessing is triggered and parameterized.
6425 @table @code
6427 @item -gnatep=@var{file}
6428 @cindex @option{-gnatep} (@code{gcc})
6429 This switch indicates to the compiler the file name (without directory
6430 information) of the preprocessor data file to use. The preprocessor data file
6431 should be found in the source directories.
6433 @noindent
6434 A preprocessing data file is a text file with significant lines indicating
6435 how should be preprocessed either a specific source or all sources not
6436 mentioned in other lines. A significant line is a non empty, non comment line.
6437 Comments are similar to Ada comments.
6439 @noindent
6440 Each significant line starts with either a literal string or the character '*'.
6441 A literal string is the file name (without directory information) of the source
6442 to preprocess. A character '*' indicates the preprocessing for all the sources
6443 that are not specified explicitly on other lines (order of the lines is not
6444 significant). It is an error to have two lines with the same file name or two
6445 lines starting with the character '*'.
6447 @noindent
6448 After the file name or the character '*', another optional literal string
6449 indicating the file name of the definition file to be used for preprocessing.
6450 (see @ref{Form of Definitions File}. The definition files are found by the
6451 compiler in one of the source directories. In some cases, when compiling
6452 a source in a directory other than the current directory, if the definition
6453 file is in the current directory, it may be necessary to add the current
6454 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6455 the compiler would not find the definition file.
6457 @noindent
6458 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6459 be found. Those ^switches^switches^ are:
6461 @table @code
6463 @item -b
6464 Causes both preprocessor lines and the lines deleted by
6465 preprocessing to be replaced by blank lines, preserving the line number.
6466 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6467 it cancels the effect of @option{-c}.
6469 @item -c
6470 Causes both preprocessor lines and the lines deleted
6471 by preprocessing to be retained as comments marked
6472 with the special string ``@code{--! }''.
6474 @item -Dsymbol=value
6475 Define or redefine a symbol, associated with value. A symbol is an Ada
6476 identifier, or an Ada reserved word, with the exception of @code{if},
6477 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6478 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6479 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6480 same name defined in a definition file.
6482 @item -s
6483 Causes a sorted list of symbol names and values to be
6484 listed on the standard output file.
6486 @item -u
6487 Causes undefined symbols to be treated as having the value @code{FALSE}
6488 in the context
6489 of a preprocessor test. In the absence of this option, an undefined symbol in
6490 a @code{#if} or @code{#elsif} test will be treated as an error.
6492 @end table
6494 @noindent
6495 Examples of valid lines in a preprocessor data file:
6497 @smallexample
6498   "toto.adb"  "prep.def" -u
6499   --  preprocess "toto.adb", using definition file "prep.def",
6500   --  undefined symbol are False.
6502   * -c -DVERSION=V101
6503   --  preprocess all other sources without a definition file;
6504   --  suppressed lined are commented; symbol VERSION has the value V101.
6506   "titi.adb" "prep2.def" -s
6507   --  preprocess "titi.adb", using definition file "prep2.def";
6508   --  list all symbols with their values.
6509 @end smallexample
6511 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6512 @cindex @option{-gnateD} (@code{gcc})
6513 Define or redefine a preprocessing symbol, associated with value. If no value
6514 is given on the command line, then the value of the symbol is @code{True}.
6515 A symbol is an identifier, following normal Ada (case-insensitive)
6516 rules for its syntax, and value is any sequence (including an empty sequence)
6517 of characters from the set (letters, digits, period, underline).
6518 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6519 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6521 @noindent
6522 A symbol declared with this ^switch^switch^ on the command line replaces a
6523 symbol with the same name either in a definition file or specified with a
6524 ^switch^switch^ -D in the preprocessor data file.
6526 @noindent
6527 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6529 @end table
6531 @ifset vms
6532 @node Return Codes
6533 @subsection Return Codes
6534 @cindex Return Codes
6535 @cindex @option{/RETURN_CODES=VMS}
6537 @noindent
6538 On VMS, GNAT compiled programs return POSIX-style codes by default,
6539 e.g. @option{/RETURN_CODES=POSIX}.
6541 To enable VMS style return codes, GNAT LINK with the option
6542 @option{/RETURN_CODES=VMS}. For example:
6544 @smallexample
6545 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6546 @end smallexample
6548 @noindent
6549 Programs built with /RETURN_CODES=VMS are suitable to be called in
6550 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6551 are suitable for spawning with appropriate GNAT RTL routines.
6553 @end ifset
6556 @node Search Paths and the Run-Time Library (RTL)
6557 @section Search Paths and the Run-Time Library (RTL)
6559 @noindent
6560 With the GNAT source-based library system, the compiler must be able to
6561 find source files for units that are needed by the unit being compiled.
6562 Search paths are used to guide this process.
6564 The compiler compiles one source file whose name must be given
6565 explicitly on the command line. In other words, no searching is done
6566 for this file. To find all other source files that are needed (the most
6567 common being the specs of units), the compiler examines the following
6568 directories, in the following order:
6570 @enumerate
6571 @item
6572 The directory containing the source file of the main unit being compiled
6573 (the file name on the command line).
6575 @item
6576 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6577 @code{gcc} command line, in the order given.
6579 @item
6580 @findex ADA_INCLUDE_PATH
6581 Each of the directories listed in the value of the
6582 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6583 @ifclear vms
6584 Construct this value
6585 exactly as the @code{PATH} environment variable: a list of directory
6586 names separated by colons (semicolons when working with the NT version).
6587 @end ifclear
6588 @ifset vms
6589 Normally, define this value as a logical name containing a comma separated
6590 list of directory names.
6592 This variable can also be defined by means of an environment string
6593 (an argument to the DEC C exec* set of functions).
6595 Logical Name:
6596 @smallexample
6597 DEFINE ANOTHER_PATH FOO:[BAG]
6598 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6599 @end smallexample
6601 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6602 first, followed by the standard Ada 95
6603 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6604 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6605 (Text_IO, Sequential_IO, etc)
6606 instead of the Ada95 packages. Thus, in order to get the Ada 95
6607 packages by default, ADA_INCLUDE_PATH must be redefined.
6608 @end ifset
6610 @item
6611 @findex ADA_PRJ_INCLUDE_FILE
6612 Each of the directories listed in the text file whose name is given
6613 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6615 @noindent
6616 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6617 driver when project files are used. It should not normally be set
6618 by other means.
6620 @item
6621 The content of the @file{ada_source_path} file which is part of the GNAT
6622 installation tree and is used to store standard libraries such as the
6623 GNAT Run Time Library (RTL) source files.
6624 @ifclear vms
6625 @ref{Installing an Ada Library}
6626 @end ifclear
6627 @end enumerate
6629 @noindent
6630 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6631 inhibits the use of the directory
6632 containing the source file named in the command line. You can still
6633 have this directory on your search path, but in this case it must be
6634 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6636 Specifying the switch @option{-nostdinc}
6637 inhibits the search of the default location for the GNAT Run Time
6638 Library (RTL) source files.
6640 The compiler outputs its object files and ALI files in the current
6641 working directory.
6642 @ifclear vms
6643 Caution: The object file can be redirected with the @option{-o} switch;
6644 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6645 so the @file{ALI} file will not go to the right place. Therefore, you should
6646 avoid using the @option{-o} switch.
6647 @end ifclear
6649 @findex System.IO
6650 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6651 children make up the GNAT RTL, together with the simple @code{System.IO}
6652 package used in the @code{"Hello World"} example. The sources for these units
6653 are needed by the compiler and are kept together in one directory. Not
6654 all of the bodies are needed, but all of the sources are kept together
6655 anyway. In a normal installation, you need not specify these directory
6656 names when compiling or binding. Either the environment variables or
6657 the built-in defaults cause these files to be found.
6659 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6660 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6661 consisting of child units of @code{GNAT}. This is a collection of generally
6662 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6663 further details.
6665 Besides simplifying access to the RTL, a major use of search paths is
6666 in compiling sources from multiple directories. This can make
6667 development environments much more flexible.
6670 @node Order of Compilation Issues
6671 @section Order of Compilation Issues
6673 @noindent
6674 If, in our earlier example, there was a spec for the @code{hello}
6675 procedure, it would be contained in the file @file{hello.ads}; yet this
6676 file would not have to be explicitly compiled. This is the result of the
6677 model we chose to implement library management. Some of the consequences
6678 of this model are as follows:
6680 @itemize @bullet
6681 @item
6682 There is no point in compiling specs (except for package
6683 specs with no bodies) because these are compiled as needed by clients. If
6684 you attempt a useless compilation, you will receive an error message.
6685 It is also useless to compile subunits because they are compiled as needed
6686 by the parent.
6688 @item
6689 There are no order of compilation requirements: performing a
6690 compilation never obsoletes anything. The only way you can obsolete
6691 something and require recompilations is to modify one of the
6692 source files on which it depends.
6694 @item
6695 There is no library as such, apart from the ALI files
6696 (@pxref{The Ada Library Information Files}, for information on the format
6697 of these files). For now we find it convenient to create separate ALI files,
6698 but eventually the information therein may be incorporated into the object
6699 file directly.
6701 @item
6702 When you compile a unit, the source files for the specs of all units
6703 that it @code{with}'s, all its subunits, and the bodies of any generics it
6704 instantiates must be available (reachable by the search-paths mechanism
6705 described above), or you will receive a fatal error message.
6706 @end itemize
6708 @node Examples
6709 @section Examples
6711 @noindent
6712 The following are some typical Ada compilation command line examples:
6714 @table @code
6715 @item $ gcc -c xyz.adb
6716 Compile body in file @file{xyz.adb} with all default options.
6718 @ifclear vms
6719 @item $ gcc -c -O2 -gnata xyz-def.adb
6720 @end ifclear
6721 @ifset vms
6722 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6723 @end ifset
6725 Compile the child unit package in file @file{xyz-def.adb} with extensive
6726 optimizations, and pragma @code{Assert}/@code{Debug} statements
6727 enabled.
6729 @item $ gcc -c -gnatc abc-def.adb
6730 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6731 mode.
6732 @end table
6734 @node Binding Using gnatbind
6735 @chapter Binding Using @code{gnatbind}
6736 @findex gnatbind
6738 @menu
6739 * Running gnatbind::
6740 * Switches for gnatbind::
6741 * Command-Line Access::
6742 * Search Paths for gnatbind::
6743 * Examples of gnatbind Usage::
6744 @end menu
6746 @noindent
6747 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6748 to bind compiled GNAT objects. The @code{gnatbind} program performs
6749 four separate functions:
6751 @enumerate
6752 @item
6753 Checks that a program is consistent, in accordance with the rules in
6754 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6755 messages are generated if a program uses inconsistent versions of a
6756 given unit.
6758 @item
6759 Checks that an acceptable order of elaboration exists for the program
6760 and issues an error message if it cannot find an order of elaboration
6761 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6763 @item
6764 Generates a main program incorporating the given elaboration order.
6765 This program is a small Ada package (body and spec) that
6766 must be subsequently compiled
6767 using the GNAT compiler. The necessary compilation step is usually
6768 performed automatically by @code{gnatlink}. The two most important
6769 functions of this program
6770 are to call the elaboration routines of units in an appropriate order
6771 and to call the main program.
6773 @item
6774 Determines the set of object files required by the given main program.
6775 This information is output in the forms of comments in the generated program,
6776 to be read by the @code{gnatlink} utility used to link the Ada application.
6777 @end enumerate
6780 @node Running gnatbind
6781 @section Running @code{gnatbind}
6783 @noindent
6784 The form of the @code{gnatbind} command is
6786 @smallexample
6787 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6788 @end smallexample
6790 @noindent
6791 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6792 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6793 package in two files whose names are
6794 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6795 For example, if given the
6796 parameter @file{hello.ali}, for a main program contained in file
6797 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6798 and @file{b~hello.adb}.
6800 When doing consistency checking, the binder takes into consideration
6801 any source files it can locate. For example, if the binder determines
6802 that the given main program requires the package @code{Pack}, whose
6803 @file{.ALI}
6804 file is @file{pack.ali} and whose corresponding source spec file is
6805 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6806 (using the same search path conventions as previously described for the
6807 @code{gcc} command). If it can locate this source file, it checks that
6808 the time stamps
6809 or source checksums of the source and its references to in @file{ALI} files
6810 match. In other words, any @file{ALI} files that mentions this spec must have
6811 resulted from compiling this version of the source file (or in the case
6812 where the source checksums match, a version close enough that the
6813 difference does not matter).
6815 @cindex Source files, use by binder
6816 The effect of this consistency checking, which includes source files, is
6817 that the binder ensures that the program is consistent with the latest
6818 version of the source files that can be located at bind time. Editing a
6819 source file without compiling files that depend on the source file cause
6820 error messages to be generated by the binder.
6822 For example, suppose you have a main program @file{hello.adb} and a
6823 package @code{P}, from file @file{p.ads} and you perform the following
6824 steps:
6826 @enumerate
6827 @item
6828 Enter @code{gcc -c hello.adb} to compile the main program.
6830 @item
6831 Enter @code{gcc -c p.ads} to compile package @code{P}.
6833 @item
6834 Edit file @file{p.ads}.
6836 @item
6837 Enter @code{gnatbind hello}.
6838 @end enumerate
6840 @noindent
6841 At this point, the file @file{p.ali} contains an out-of-date time stamp
6842 because the file @file{p.ads} has been edited. The attempt at binding
6843 fails, and the binder generates the following error messages:
6845 @smallexample
6846 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6847 error: "p.ads" has been modified and must be recompiled
6848 @end smallexample
6850 @noindent
6851 Now both files must be recompiled as indicated, and then the bind can
6852 succeed, generating a main program. You need not normally be concerned
6853 with the contents of this file, but for reference purposes a sample
6854 binder output file is given in @ref{Example of Binder Output File}.
6856 In most normal usage, the default mode of @command{gnatbind} which is to
6857 generate the main package in Ada, as described in the previous section.
6858 In particular, this means that any Ada programmer can read and understand
6859 the generated main program. It can also be debugged just like any other
6860 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6861 @command{gnatbind} and @command{gnatlink}.
6863 However for some purposes it may be convenient to generate the main
6864 program in C rather than Ada. This may for example be helpful when you
6865 are generating a mixed language program with the main program in C. The
6866 GNAT compiler itself is an example.
6867 The use of the @option{^-C^/BIND_FILE=C^} switch
6868 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6869 be generated in C (and compiled using the gnu C compiler).
6872 @node Switches for gnatbind
6873 @section Switches for @command{gnatbind}
6875 @noindent
6876 The following switches are available with @code{gnatbind}; details will
6877 be presented in subsequent sections.
6879 @menu
6880 * Consistency-Checking Modes::
6881 * Binder Error Message Control::
6882 * Elaboration Control::
6883 * Output Control::
6884 * Binding with Non-Ada Main Programs::
6885 * Binding Programs with No Main Subprogram::
6886 @end menu
6888 @table @option
6889 @c !sort!
6890 @item ^-aO^/OBJECT_SEARCH^
6891 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6892 Specify directory to be searched for ALI files.
6894 @item ^-aI^/SOURCE_SEARCH^
6895 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6896 Specify directory to be searched for source file.
6898 @item ^-A^/BIND_FILE=ADA^
6899 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6900 Generate binder program in Ada (default)
6902 @item ^-b^/REPORT_ERRORS=BRIEF^
6903 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6904 Generate brief messages to @file{stderr} even if verbose mode set.
6906 @item ^-c^/NOOUTPUT^
6907 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6908 Check only, no generation of binder output file.
6910 @item ^-C^/BIND_FILE=C^
6911 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6912 Generate binder program in C
6914 @item ^-e^/ELABORATION_DEPENDENCIES^
6915 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6916 Output complete list of elaboration-order dependencies.
6918 @item ^-E^/STORE_TRACEBACKS^
6919 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6920 Store tracebacks in exception occurrences when the target supports it.
6921 This is the default with the zero cost exception mechanism.
6922 @ignore
6923 @c The following may get moved to an appendix
6924 This option is currently supported on the following targets:
6925 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6926 @end ignore
6927 See also the packages @code{GNAT.Traceback} and
6928 @code{GNAT.Traceback.Symbolic} for more information.
6929 @ifclear vms
6930 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6931 @code{gcc} option.
6932 @end ifclear vms
6934 @item ^-F^/FORCE_ELABS_FLAGS^
6935 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6936 Force the checks of elaboration flags. @command{gnatbind} does not normally
6937 generate checks of elaboration flags for the main executable, except when
6938 a Stand-Alone Library is used. However, there are cases when this cannot be
6939 detected by gnatbind. An example is importing an interface of a Stand-Alone
6940 Library through a pragma Import and only specifying through a linker switch
6941 this Stand-Alone Library. This switch is used to guarantee that elaboration
6942 flag checks are generated.
6944 @item ^-h^/HELP^
6945 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6946 Output usage (help) information
6948 @item ^-I^/SEARCH^
6949 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6950 Specify directory to be searched for source and ALI files.
6952 @item ^-I-^/NOCURRENT_DIRECTORY^
6953 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
6954 Do not look for sources in the current directory where @code{gnatbind} was
6955 invoked, and do not look for ALI files in the directory containing the
6956 ALI file named in the @code{gnatbind} command line.
6958 @item ^-l^/ORDER_OF_ELABORATION^
6959 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
6960 Output chosen elaboration order.
6962 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
6963 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
6964 Binds the units for library building. In this case the adainit and
6965 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6966 are renamed to ^xxxinit^XXXINIT^ and
6967 ^xxxfinal^XXXFINAL^.
6968 Implies ^-n^/NOCOMPILE^.
6969 @ifclear vms
6970 (@pxref{GNAT and Libraries}, for more details.)
6971 @end ifclear
6972 @ifset vms
6973 On OpenVMS, these init and final procedures are exported in uppercase
6974 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
6975 the init procedure will be "TOTOINIT" and the exported name of the final
6976 procedure will be "TOTOFINAL".
6977 @end ifset
6979 @item ^-Mxyz^/RENAME_MAIN=xyz^
6980 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
6981 Rename generated main program from main to xyz
6983 @item ^-m^/ERROR_LIMIT=^@var{n}
6984 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
6985 Limit number of detected errors to @var{n}, where @var{n} is
6986 in the range 1..999_999. The default value if no switch is
6987 given is 9999. Binding is terminated if the limit is exceeded.
6988 @ifset unw
6989 Furthermore, under Windows, the sources pointed to by the libraries path
6990 set in the registry are not searched for.
6991 @end ifset
6993 @item ^-n^/NOMAIN^
6994 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
6995 No main program.
6997 @item -nostdinc
6998 @cindex @option{-nostdinc} (@command{gnatbind})
6999 Do not look for sources in the system default directory.
7001 @item -nostdlib
7002 @cindex @option{-nostdlib} (@command{gnatbind})
7003 Do not look for library files in the system default directory.
7005 @item --RTS=@var{rts-path}
7006 @cindex @option{--RTS} (@code{gnatbind})
7007 Specifies the default location of the runtime library. Same meaning as the
7008 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7010 @item ^-o ^/OUTPUT=^@var{file}
7011 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7012 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7013 Note that if this option is used, then linking must be done manually,
7014 gnatlink cannot be used.
7016 @item ^-O^/OBJECT_LIST^
7017 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7018 Output object list.
7020 @item ^-p^/PESSIMISTIC_ELABORATION^
7021 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7022 Pessimistic (worst-case) elaboration order
7024 @item ^-s^/READ_SOURCES=ALL^
7025 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7026 Require all source files to be present.
7028 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7029 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7030 Specifies the value to be used when detecting uninitialized scalar
7031 objects with pragma Initialize_Scalars.
7032 The @var{xxx} ^string specified with the switch^option^ may be either
7033 @itemize @bullet
7034 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7035 @item ``@option{^lo^LOW^}'' for the lowest possible value
7036 possible, and the low
7037 @item ``@option{^hi^HIGH^}'' for the highest possible value
7038 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7039 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7040 @end itemize
7042 In addition, you can specify @option{-Sev} to indicate that the value is
7043 to be set at run time. In this case, the program will look for an environment
7044 @cindex GNAT_INIT_SCALARS
7045 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7046 of @option{in/lo/hi/xx} with the same meanings as above.
7047 If no environment variable is found, or if it does not have a valid value,
7048 then the default is @option{in} (invalid values).
7050 @ifclear vms
7051 @item -static
7052 @cindex @option{-static} (@code{gnatbind})
7053 Link against a static GNAT run time.
7055 @item -shared
7056 @cindex @option{-shared} (@code{gnatbind})
7057 Link against a shared GNAT run time when available.
7058 @end ifclear
7060 @item ^-t^/NOTIME_STAMP_CHECK^
7061 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7062 Tolerate time stamp and other consistency errors
7064 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7065 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7066 Set the time slice value to @var{n} milliseconds. If the system supports
7067 the specification of a specific time slice value, then the indicated value
7068 is used. If the system does not support specific time slice values, but
7069 does support some general notion of round-robin scheduling, then any
7070 non-zero value will activate round-robin scheduling.
7072 A value of zero is treated specially. It turns off time
7073 slicing, and in addition, indicates to the tasking run time that the
7074 semantics should match as closely as possible the Annex D
7075 requirements of the Ada RM, and in particular sets the default
7076 scheduling policy to @code{FIFO_Within_Priorities}.
7078 @item ^-v^/REPORT_ERRORS=VERBOSE^
7079 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7080 Verbose mode. Write error messages, header, summary output to
7081 @file{stdout}.
7083 @ifclear vms
7084 @item -w@var{x}
7085 @cindex @option{-w} (@code{gnatbind})
7086 Warning mode (@var{x}=s/e for suppress/treat as error)
7087 @end ifclear
7089 @ifset vms
7090 @item /WARNINGS=NORMAL
7091 @cindex @option{/WARNINGS} (@code{gnatbind})
7092 Normal warnings mode. Warnings are issued but ignored
7094 @item /WARNINGS=SUPPRESS
7095 @cindex @option{/WARNINGS} (@code{gnatbind})
7096 All warning messages are suppressed
7098 @item /WARNINGS=ERROR
7099 @cindex @option{/WARNINGS} (@code{gnatbind})
7100 Warning messages are treated as fatal errors
7101 @end ifset
7103 @item ^-x^/READ_SOURCES=NONE^
7104 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7105 Exclude source files (check object consistency only).
7107 @ifset vms
7108 @item /READ_SOURCES=AVAILABLE
7109 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7110 Default mode, in which sources are checked for consistency only if
7111 they are available.
7112 @end ifset
7114 @item ^-z^/ZERO_MAIN^
7115 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7116 No main subprogram.
7117 @end table
7119 @ifclear vms
7120 @noindent
7121 You may obtain this listing of switches by running @code{gnatbind} with
7122 no arguments.
7123 @end ifclear
7126 @node Consistency-Checking Modes
7127 @subsection Consistency-Checking Modes
7129 @noindent
7130 As described earlier, by default @code{gnatbind} checks
7131 that object files are consistent with one another and are consistent
7132 with any source files it can locate. The following switches control binder
7133 access to sources.
7135 @table @option
7136 @c !sort!
7137 @item ^-s^/READ_SOURCES=ALL^
7138 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7139 Require source files to be present. In this mode, the binder must be
7140 able to locate all source files that are referenced, in order to check
7141 their consistency. In normal mode, if a source file cannot be located it
7142 is simply ignored. If you specify this switch, a missing source
7143 file is an error.
7145 @item ^-x^/READ_SOURCES=NONE^
7146 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7147 Exclude source files. In this mode, the binder only checks that ALI
7148 files are consistent with one another. Source files are not accessed.
7149 The binder runs faster in this mode, and there is still a guarantee that
7150 the resulting program is self-consistent.
7151 If a source file has been edited since it was last compiled, and you
7152 specify this switch, the binder will not detect that the object
7153 file is out of date with respect to the source file. Note that this is the
7154 mode that is automatically used by @code{gnatmake} because in this
7155 case the checking against sources has already been performed by
7156 @code{gnatmake} in the course of compilation (i.e. before binding).
7158 @ifset vms
7159 @item /READ_SOURCES=AVAILABLE
7160 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7161 This is the default mode in which source files are checked if they are
7162 available, and ignored if they are not available.
7163 @end ifset
7164 @end table
7166 @node Binder Error Message Control
7167 @subsection Binder Error Message Control
7169 @noindent
7170 The following switches provide control over the generation of error
7171 messages from the binder:
7173 @table @option
7174 @c !sort!
7175 @item ^-v^/REPORT_ERRORS=VERBOSE^
7176 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7177 Verbose mode. In the normal mode, brief error messages are generated to
7178 @file{stderr}. If this switch is present, a header is written
7179 to @file{stdout} and any error messages are directed to @file{stdout}.
7180 All that is written to @file{stderr} is a brief summary message.
7182 @item ^-b^/REPORT_ERRORS=BRIEF^
7183 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7184 Generate brief error messages to @file{stderr} even if verbose mode is
7185 specified. This is relevant only when used with the
7186 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7188 @ifclear vms
7189 @item -m@var{n}
7190 @cindex @option{-m} (@code{gnatbind})
7191 Limits the number of error messages to @var{n}, a decimal integer in the
7192 range 1-999. The binder terminates immediately if this limit is reached.
7194 @item -M@var{xxx}
7195 @cindex @option{-M} (@code{gnatbind})
7196 Renames the generated main program from @code{main} to @code{xxx}.
7197 This is useful in the case of some cross-building environments, where
7198 the actual main program is separate from the one generated
7199 by @code{gnatbind}.
7200 @end ifclear
7202 @item ^-ws^/WARNINGS=SUPPRESS^
7203 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7204 @cindex Warnings
7205 Suppress all warning messages.
7207 @item ^-we^/WARNINGS=ERROR^
7208 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7209 Treat any warning messages as fatal errors.
7211 @ifset vms
7212 @item /WARNINGS=NORMAL
7213 Standard mode with warnings generated, but warnings do not get treated
7214 as errors.
7215 @end ifset
7217 @item ^-t^/NOTIME_STAMP_CHECK^
7218 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7219 @cindex Time stamp checks, in binder
7220 @cindex Binder consistency checks
7221 @cindex Consistency checks, in binder
7222 The binder performs a number of consistency checks including:
7224 @itemize @bullet
7225 @item
7226 Check that time stamps of a given source unit are consistent
7227 @item
7228 Check that checksums of a given source unit are consistent
7229 @item
7230 Check that consistent versions of @code{GNAT} were used for compilation
7231 @item
7232 Check consistency of configuration pragmas as required
7233 @end itemize
7235 @noindent
7236 Normally failure of such checks, in accordance with the consistency
7237 requirements of the Ada Reference Manual, causes error messages to be
7238 generated which abort the binder and prevent the output of a binder
7239 file and subsequent link to obtain an executable.
7241 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7242 into warnings, so that
7243 binding and linking can continue to completion even in the presence of such
7244 errors. The result may be a failed link (due to missing symbols), or a
7245 non-functional executable which has undefined semantics.
7246 @emph{This means that
7247 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7248 with extreme care.}
7249 @end table
7251 @node Elaboration Control
7252 @subsection Elaboration Control
7254 @noindent
7255 The following switches provide additional control over the elaboration
7256 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7258 @table @option
7259 @item ^-p^/PESSIMISTIC_ELABORATION^
7260 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7261 Normally the binder attempts to choose an elaboration order that is
7262 likely to minimize the likelihood of an elaboration order error resulting
7263 in raising a @code{Program_Error} exception. This switch reverses the
7264 action of the binder, and requests that it deliberately choose an order
7265 that is likely to maximize the likelihood of an elaboration error.
7266 This is useful in ensuring portability and avoiding dependence on
7267 accidental fortuitous elaboration ordering.
7269 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7270 switch if dynamic
7271 elaboration checking is used (@option{-gnatE} switch used for compilation).
7272 This is because in the default static elaboration mode, all necessary
7273 @code{Elaborate_All} pragmas are implicitly inserted.
7274 These implicit pragmas are still respected by the binder in
7275 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7276 safe elaboration order is assured.
7277 @end table
7279 @node Output Control
7280 @subsection Output Control
7282 @noindent
7283 The following switches allow additional control over the output
7284 generated by the binder.
7286 @table @option
7287 @c !sort!
7289 @item ^-A^/BIND_FILE=ADA^
7290 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7291 Generate binder program in Ada (default). The binder program is named
7292 @file{b~@var{mainprog}.adb} by default. This can be changed with
7293 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7295 @item ^-c^/NOOUTPUT^
7296 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7297 Check only. Do not generate the binder output file. In this mode the
7298 binder performs all error checks but does not generate an output file.
7300 @item ^-C^/BIND_FILE=C^
7301 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7302 Generate binder program in C. The binder program is named
7303 @file{b_@var{mainprog}.c}.
7304 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7305 option.
7307 @item ^-e^/ELABORATION_DEPENDENCIES^
7308 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7309 Output complete list of elaboration-order dependencies, showing the
7310 reason for each dependency. This output can be rather extensive but may
7311 be useful in diagnosing problems with elaboration order. The output is
7312 written to @file{stdout}.
7314 @item ^-h^/HELP^
7315 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7316 Output usage information. The output is written to @file{stdout}.
7318 @item ^-K^/LINKER_OPTION_LIST^
7319 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7320 Output linker options to @file{stdout}. Includes library search paths,
7321 contents of pragmas Ident and Linker_Options, and libraries added
7322 by @code{gnatbind}.
7324 @item ^-l^/ORDER_OF_ELABORATION^
7325 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7326 Output chosen elaboration order. The output is written to @file{stdout}.
7328 @item ^-O^/OBJECT_LIST^
7329 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7330 Output full names of all the object files that must be linked to provide
7331 the Ada component of the program. The output is written to @file{stdout}.
7332 This list includes the files explicitly supplied and referenced by the user
7333 as well as implicitly referenced run-time unit files. The latter are
7334 omitted if the corresponding units reside in shared libraries. The
7335 directory names for the run-time units depend on the system configuration.
7337 @item ^-o ^/OUTPUT=^@var{file}
7338 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7339 Set name of output file to @var{file} instead of the normal
7340 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7341 binder generated body filename. In C mode you would normally give
7342 @var{file} an extension of @file{.c} because it will be a C source program.
7343 Note that if this option is used, then linking must be done manually.
7344 It is not possible to use gnatlink in this case, since it cannot locate
7345 the binder file.
7347 @item ^-r^/RESTRICTION_LIST^
7348 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7349 Generate list of @code{pragma Restrictions} that could be applied to
7350 the current unit. This is useful for code audit purposes, and also may
7351 be used to improve code generation in some cases.
7353 @end table
7355 @node Binding with Non-Ada Main Programs
7356 @subsection Binding with Non-Ada Main Programs
7358 @noindent
7359 In our description so far we have assumed that the main
7360 program is in Ada, and that the task of the binder is to generate a
7361 corresponding function @code{main} that invokes this Ada main
7362 program. GNAT also supports the building of executable programs where
7363 the main program is not in Ada, but some of the called routines are
7364 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7365 The following switch is used in this situation:
7367 @table @option
7368 @item ^-n^/NOMAIN^
7369 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7370 No main program. The main program is not in Ada.
7371 @end table
7373 @noindent
7374 In this case, most of the functions of the binder are still required,
7375 but instead of generating a main program, the binder generates a file
7376 containing the following callable routines:
7378 @table @code
7379 @item adainit
7380 @findex adainit
7381 You must call this routine to initialize the Ada part of the program by
7382 calling the necessary elaboration routines. A call to @code{adainit} is
7383 required before the first call to an Ada subprogram.
7385 Note that it is assumed that the basic execution environment must be setup
7386 to be appropriate for Ada execution at the point where the first Ada
7387 subprogram is called. In particular, if the Ada code will do any
7388 floating-point operations, then the FPU must be setup in an appropriate
7389 manner. For the case of the x86, for example, full precision mode is
7390 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7391 that the FPU is in the right state.
7393 @item adafinal
7394 @findex adafinal
7395 You must call this routine to perform any library-level finalization
7396 required by the Ada subprograms. A call to @code{adafinal} is required
7397 after the last call to an Ada subprogram, and before the program
7398 terminates.
7399 @end table
7401 @noindent
7402 If the @option{^-n^/NOMAIN^} switch
7403 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7404 @cindex Binder, multiple input files
7405 is given, more than one ALI file may appear on
7406 the command line for @code{gnatbind}. The normal @dfn{closure}
7407 calculation is performed for each of the specified units. Calculating
7408 the closure means finding out the set of units involved by tracing
7409 @code{with} references. The reason it is necessary to be able to
7410 specify more than one ALI file is that a given program may invoke two or
7411 more quite separate groups of Ada units.
7413 The binder takes the name of its output file from the last specified ALI
7414 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7415 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7416 The output is an Ada unit in source form that can
7417 be compiled with GNAT unless the -C switch is used in which case the
7418 output is a C source file, which must be compiled using the C compiler.
7419 This compilation occurs automatically as part of the @code{gnatlink}
7420 processing.
7422 Currently the GNAT run time requires a FPU using 80 bits mode
7423 precision. Under targets where this is not the default it is required to
7424 call GNAT.Float_Control.Reset before using floating point numbers (this
7425 include float computation, float input and output) in the Ada code. A
7426 side effect is that this could be the wrong mode for the foreign code
7427 where floating point computation could be broken after this call.
7429 @node Binding Programs with No Main Subprogram
7430 @subsection Binding Programs with No Main Subprogram
7432 @noindent
7433 It is possible to have an Ada program which does not have a main
7434 subprogram. This program will call the elaboration routines of all the
7435 packages, then the finalization routines.
7437 The following switch is used to bind programs organized in this manner:
7439 @table @option
7440 @item ^-z^/ZERO_MAIN^
7441 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7442 Normally the binder checks that the unit name given on the command line
7443 corresponds to a suitable main subprogram. When this switch is used,
7444 a list of ALI files can be given, and the execution of the program
7445 consists of elaboration of these units in an appropriate order.
7446 @end table
7449 @node Command-Line Access
7450 @section Command-Line Access
7452 @noindent
7453 The package @code{Ada.Command_Line} provides access to the command-line
7454 arguments and program name. In order for this interface to operate
7455 correctly, the two variables
7457 @smallexample
7458 @group
7459 int gnat_argc;
7460 char **gnat_argv;
7461 @end group
7462 @end smallexample
7464 @noindent
7465 @findex gnat_argv
7466 @findex gnat_argc
7467 are declared in one of the GNAT library routines. These variables must
7468 be set from the actual @code{argc} and @code{argv} values passed to the
7469 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7470 generates the C main program to automatically set these variables.
7471 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7472 set these variables. If they are not set, the procedures in
7473 @code{Ada.Command_Line} will not be available, and any attempt to use
7474 them will raise @code{Constraint_Error}. If command line access is
7475 required, your main program must set @code{gnat_argc} and
7476 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7480 @node Search Paths for gnatbind
7481 @section Search Paths for @code{gnatbind}
7483 @noindent
7484 The binder takes the name of an ALI file as its argument and needs to
7485 locate source files as well as other ALI files to verify object consistency.
7487 For source files, it follows exactly the same search rules as @code{gcc}
7488 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7489 directories searched are:
7491 @enumerate
7492 @item
7493 The directory containing the ALI file named in the command line, unless
7494 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7496 @item
7497 All directories specified by @option{^-I^/SEARCH^}
7498 switches on the @code{gnatbind}
7499 command line, in the order given.
7501 @item
7502 @findex ADA_OBJECTS_PATH
7503 Each of the directories listed in the value of the
7504 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7505 @ifset unw
7506 Construct this value
7507 exactly as the @code{PATH} environment variable: a list of directory
7508 names separated by colons (semicolons when working with the NT version
7509 of GNAT).
7510 @end ifset
7511 @ifset vms
7512 Normally, define this value as a logical name containing a comma separated
7513 list of directory names.
7515 This variable can also be defined by means of an environment string
7516 (an argument to the DEC C exec* set of functions).
7518 Logical Name:
7519 @smallexample
7520 DEFINE ANOTHER_PATH FOO:[BAG]
7521 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7522 @end smallexample
7524 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7525 first, followed by the standard Ada 95
7526 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7527 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7528 (Text_IO, Sequential_IO, etc)
7529 instead of the Ada95 packages. Thus, in order to get the Ada 95
7530 packages by default, ADA_OBJECTS_PATH must be redefined.
7531 @end ifset
7533 @item
7534 @findex ADA_PRJ_OBJECTS_FILE
7535 Each of the directories listed in the text file whose name is given
7536 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7538 @noindent
7539 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7540 driver when project files are used. It should not normally be set
7541 by other means.
7543 @item
7544 The content of the @file{ada_object_path} file which is part of the GNAT
7545 installation tree and is used to store standard libraries such as the
7546 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7547 specified.
7548 @ifclear vms
7549 @ref{Installing an Ada Library}
7550 @end ifclear
7551 @end enumerate
7553 @noindent
7554 In the binder the switch @option{^-I^/SEARCH^}
7555 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7556 is used to specify both source and
7557 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7558 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7559 instead if you want to specify
7560 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7561 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7562 if you want to specify library paths
7563 only. This means that for the binder
7564 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7565 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7566 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7567 The binder generates the bind file (a C language source file) in the
7568 current working directory.
7570 @findex Ada
7571 @findex System
7572 @findex Interfaces
7573 @findex GNAT
7574 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7575 children make up the GNAT Run-Time Library, together with the package
7576 GNAT and its children, which contain a set of useful additional
7577 library functions provided by GNAT. The sources for these units are
7578 needed by the compiler and are kept together in one directory. The ALI
7579 files and object files generated by compiling the RTL are needed by the
7580 binder and the linker and are kept together in one directory, typically
7581 different from the directory containing the sources. In a normal
7582 installation, you need not specify these directory names when compiling
7583 or binding. Either the environment variables or the built-in defaults
7584 cause these files to be found.
7586 Besides simplifying access to the RTL, a major use of search paths is
7587 in compiling sources from multiple directories. This can make
7588 development environments much more flexible.
7590 @node Examples of gnatbind Usage
7591 @section Examples of @code{gnatbind} Usage
7593 @noindent
7594 This section contains a number of examples of using the GNAT binding
7595 utility @code{gnatbind}.
7597 @table @code
7598 @item gnatbind hello
7599 The main program @code{Hello} (source program in @file{hello.adb}) is
7600 bound using the standard switch settings. The generated main program is
7601 @file{b~hello.adb}. This is the normal, default use of the binder.
7603 @ifclear vms
7604 @item gnatbind hello -o mainprog.adb
7605 @end ifclear
7606 @ifset vms
7607 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7608 @end ifset
7609 The main program @code{Hello} (source program in @file{hello.adb}) is
7610 bound using the standard switch settings. The generated main program is
7611 @file{mainprog.adb} with the associated spec in
7612 @file{mainprog.ads}. Note that you must specify the body here not the
7613 spec, in the case where the output is in Ada. Note that if this option
7614 is used, then linking must be done manually, since gnatlink will not
7615 be able to find the generated file.
7617 @ifclear vms
7618 @item gnatbind main -C -o mainprog.c -x
7619 @end ifclear
7620 @ifset vms
7621 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7622 @end ifset
7623 The main program @code{Main} (source program in
7624 @file{main.adb}) is bound, excluding source files from the
7625 consistency checking, generating
7626 the file @file{mainprog.c}.
7628 @ifclear vms
7629 @item gnatbind -x main_program -C -o mainprog.c
7630 This command is exactly the same as the previous example. Switches may
7631 appear anywhere in the command line, and single letter switches may be
7632 combined into a single switch.
7633 @end ifclear
7635 @ifclear vms
7636 @item gnatbind -n math dbase -C -o ada-control.c
7637 @end ifclear
7638 @ifset vms
7639 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7640 @end ifset
7641 The main program is in a language other than Ada, but calls to
7642 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7643 to @code{gnatbind} generates the file @file{ada-control.c} containing
7644 the @code{adainit} and @code{adafinal} routines to be called before and
7645 after accessing the Ada units.
7646 @end table
7649 @c ------------------------------------
7650 @node Linking Using gnatlink
7651 @chapter Linking Using @code{gnatlink}
7652 @c ------------------------------------
7653 @findex gnatlink
7655 @noindent
7656 This chapter discusses @code{gnatlink}, a tool that links
7657 an Ada program and builds an executable file. This utility
7658 invokes the system linker ^(via the @code{gcc} command)^^
7659 with a correct list of object files and library references.
7660 @code{gnatlink} automatically determines the list of files and
7661 references for the Ada part of a program. It uses the binder file
7662 generated by the @command{gnatbind} to determine this list.
7664 @menu
7665 * Running gnatlink::
7666 * Switches for gnatlink::
7667 * Setting Stack Size from gnatlink::
7668 * Setting Heap Size from gnatlink::
7669 @end menu
7671 @node Running gnatlink
7672 @section Running @code{gnatlink}
7674 @noindent
7675 The form of the @code{gnatlink} command is
7677 @smallexample
7678 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7679            [@var{non-Ada objects}] [@var{linker options}]
7680 @end smallexample
7682 @noindent
7683 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7684 non-Ada objects
7685 or linker options) may be in any order, provided that no non-Ada object may
7686 be mistaken for a main @file{ALI} file.
7687 Any file name @file{F} without the @file{.ali}
7688 extension will be taken as the main @file{ALI} file if a file exists
7689 whose name is the concatenation of @file{F} and @file{.ali}.
7691 @noindent
7692 @file{@var{mainprog}.ali} references the ALI file of the main program.
7693 The @file{.ali} extension of this file can be omitted. From this
7694 reference, @code{gnatlink} locates the corresponding binder file
7695 @file{b~@var{mainprog}.adb} and, using the information in this file along
7696 with the list of non-Ada objects and linker options, constructs a
7697 linker command file to create the executable.
7699 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7700 file are passed to the linker uninterpreted.
7701 They typically include the names of
7702 object files for units written in other languages than Ada and any library
7703 references required to resolve references in any of these foreign language
7704 units, or in @code{Import} pragmas in any Ada units.
7706 @var{linker options} is an optional list of linker specific
7707 switches.
7708 The default linker called by gnatlink is @var{gcc} which in
7709 turn calls the appropriate system linker.
7710 Standard options for the linker such as @option{-lmy_lib} or
7711 @option{-Ldir} can be added as is.
7712 For options that are not recognized by
7713 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7714 @option{-Wl,}.
7715 Refer to the GCC documentation for
7716 details. Here is an example showing how to generate a linker map:
7718 @ifclear vms
7719 @smallexample
7720 $ gnatlink my_prog -Wl,-Map,MAPFILE
7721 @end smallexample
7722 @end ifclear
7724 @ifset vms
7725 <<Need example for VMS>>
7726 @end ifset
7728 Using @var{linker options} it is possible to set the program stack and
7729 heap size. See @ref{Setting Stack Size from gnatlink}, and
7730 @ref{Setting Heap Size from gnatlink}.
7732 @code{gnatlink} determines the list of objects required by the Ada
7733 program and prepends them to the list of objects passed to the linker.
7734 @code{gnatlink} also gathers any arguments set by the use of
7735 @code{pragma Linker_Options} and adds them to the list of arguments
7736 presented to the linker.
7738 @ifset vms
7739 @code{gnatlink} accepts the following types of extra files on the command
7740 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7741 options files (.OPT). These are recognized and handled according to their
7742 extension.
7743 @end ifset
7745 @node Switches for gnatlink
7746 @section Switches for @code{gnatlink}
7748 @noindent
7749 The following switches are available with the @code{gnatlink} utility:
7751 @table @option
7752 @c !sort!
7754 @item ^-A^/BIND_FILE=ADA^
7755 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7756 The binder has generated code in Ada. This is the default.
7758 @item ^-C^/BIND_FILE=C^
7759 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7760 If instead of generating a file in Ada, the binder has generated one in
7761 C, then the linker needs to know about it. Use this switch to signal
7762 to @code{gnatlink} that the binder has generated C code rather than
7763 Ada code.
7765 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7766 @cindex Command line length
7767 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7768 On some targets, the command line length is limited, and @code{gnatlink}
7769 will generate a separate file for the linker if the list of object files
7770 is too long.
7771 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7772 to be generated even if
7773 the limit is not exceeded. This is useful in some cases to deal with
7774 special situations where the command line length is exceeded.
7776 @item ^-g^/DEBUG^
7777 @cindex Debugging information, including
7778 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7779 The option to include debugging information causes the Ada bind file (in
7780 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7781 @option{^-g^/DEBUG^}.
7782 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7783 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7784 Without @option{^-g^/DEBUG^}, the binder removes these files by
7785 default. The same procedure apply if a C bind file was generated using
7786 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7787 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7789 @item ^-n^/NOCOMPILE^
7790 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7791 Do not compile the file generated by the binder. This may be used when
7792 a link is rerun with different options, but there is no need to recompile
7793 the binder file.
7795 @item ^-v^/VERBOSE^
7796 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7797 Causes additional information to be output, including a full list of the
7798 included object files. This switch option is most useful when you want
7799 to see what set of object files are being used in the link step.
7801 @item ^-v -v^/VERBOSE/VERBOSE^
7802 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7803 Very verbose mode. Requests that the compiler operate in verbose mode when
7804 it compiles the binder file, and that the system linker run in verbose mode.
7806 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7807 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7808 @var{exec-name} specifies an alternate name for the generated
7809 executable program. If this switch is omitted, the executable has the same
7810 name as the main unit. For example, @code{gnatlink try.ali} creates
7811 an executable called @file{^try^TRY.EXE^}.
7813 @ifclear vms
7814 @item -b @var{target}
7815 @cindex @option{-b} (@code{gnatlink})
7816 Compile your program to run on @var{target}, which is the name of a
7817 system configuration. You must have a GNAT cross-compiler built if
7818 @var{target} is not the same as your host system.
7820 @item -B@var{dir}
7821 @cindex @option{-B} (@code{gnatlink})
7822 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7823 from @var{dir} instead of the default location. Only use this switch
7824 when multiple versions of the GNAT compiler are available. See the
7825 @code{gcc} manual page for further details. You would normally use the
7826 @option{-b} or @option{-V} switch instead.
7828 @item --GCC=@var{compiler_name}
7829 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7830 Program used for compiling the binder file. The default is
7831 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7832 @code{compiler_name} contains spaces or other separator characters. As
7833 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7834 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7835 inserted after your command name. Thus in the above example the compiler
7836 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7837 If several @option{--GCC=compiler_name} are used, only the last
7838 @var{compiler_name} is taken into account. However, all the additional
7839 switches are also taken into account. Thus,
7840 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7841 @option{--GCC="bar -x -y -z -t"}.
7843 @item --LINK=@var{name}
7844 @cindex @option{--LINK=} (@code{gnatlink})
7845 @var{name} is the name of the linker to be invoked. This is especially
7846 useful in mixed language programs since languages such as C++ require
7847 their own linker to be used. When this switch is omitted, the default
7848 name for the linker is (@file{gcc}). When this switch is used, the
7849 specified linker is called instead of (@file{gcc}) with exactly the same
7850 parameters that would have been passed to (@file{gcc}) so if the desired
7851 linker requires different parameters it is necessary to use a wrapper
7852 script that massages the parameters before invoking the real linker. It
7853 may be useful to control the exact invocation by using the verbose
7854 switch.
7856 @end ifclear
7858 @ifset vms
7859 @item /DEBUG=TRACEBACK
7860 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7861 This qualifier causes sufficient information to be included in the
7862 executable file to allow a traceback, but does not include the full
7863 symbol information needed by the debugger.
7865 @item /IDENTIFICATION="<string>"
7866 @code{"<string>"} specifies the string to be stored in the image file
7867 identification field in the image header.
7868 It overrides any pragma @code{Ident} specified string.
7870 @item /NOINHIBIT-EXEC
7871 Generate the executable file even if there are linker warnings.
7873 @item /NOSTART_FILES
7874 Don't link in the object file containing the ``main'' transfer address.
7875 Used when linking with a foreign language main program compiled with a
7876 Digital compiler.
7878 @item /STATIC
7879 Prefer linking with object libraries over sharable images, even without
7880 /DEBUG.
7881 @end ifset
7883 @end table
7885 @node Setting Stack Size from gnatlink
7886 @section Setting Stack Size from @code{gnatlink}
7888 @noindent
7889 Under Windows systems, it is possible to specify the program stack size from
7890 @code{gnatlink} using either:
7892 @itemize @bullet
7894 @item using @option{-Xlinker} linker option
7896 @smallexample
7897 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7898 @end smallexample
7900 This sets the stack reserve size to 0x10000 bytes and the stack commit
7901 size to 0x1000 bytes.
7903 @item using @option{-Wl} linker option
7905 @smallexample
7906 $ gnatlink hello -Wl,--stack=0x1000000
7907 @end smallexample
7909 This sets the stack reserve size to 0x1000000 bytes. Note that with
7910 @option{-Wl} option it is not possible to set the stack commit size
7911 because the coma is a separator for this option.
7913 @end itemize
7915 @node Setting Heap Size from gnatlink
7916 @section Setting Heap Size from @code{gnatlink}
7918 @noindent
7919 Under Windows systems, it is possible to specify the program heap size from
7920 @code{gnatlink} using either:
7922 @itemize @bullet
7924 @item using @option{-Xlinker} linker option
7926 @smallexample
7927 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7928 @end smallexample
7930 This sets the heap reserve size to 0x10000 bytes and the heap commit
7931 size to 0x1000 bytes.
7933 @item using @option{-Wl} linker option
7935 @smallexample
7936 $ gnatlink hello -Wl,--heap=0x1000000
7937 @end smallexample
7939 This sets the heap reserve size to 0x1000000 bytes. Note that with
7940 @option{-Wl} option it is not possible to set the heap commit size
7941 because the coma is a separator for this option.
7943 @end itemize
7945 @node The GNAT Make Program gnatmake
7946 @chapter The GNAT Make Program @code{gnatmake}
7947 @findex gnatmake
7949 @menu
7950 * Running gnatmake::
7951 * Switches for gnatmake::
7952 * Mode Switches for gnatmake::
7953 * Notes on the Command Line::
7954 * How gnatmake Works::
7955 * Examples of gnatmake Usage::
7956 @end menu
7957 @noindent
7958 A typical development cycle when working on an Ada program consists of
7959 the following steps:
7961 @enumerate
7962 @item
7963 Edit some sources to fix bugs.
7965 @item
7966 Add enhancements.
7968 @item
7969 Compile all sources affected.
7971 @item
7972 Rebind and relink.
7974 @item
7975 Test.
7976 @end enumerate
7978 @noindent
7979 The third step can be tricky, because not only do the modified files
7980 @cindex Dependency rules
7981 have to be compiled, but any files depending on these files must also be
7982 recompiled. The dependency rules in Ada can be quite complex, especially
7983 in the presence of overloading, @code{use} clauses, generics and inlined
7984 subprograms.
7986 @code{gnatmake} automatically takes care of the third and fourth steps
7987 of this process. It determines which sources need to be compiled,
7988 compiles them, and binds and links the resulting object files.
7990 Unlike some other Ada make programs, the dependencies are always
7991 accurately recomputed from the new sources. The source based approach of
7992 the GNAT compilation model makes this possible. This means that if
7993 changes to the source program cause corresponding changes in
7994 dependencies, they will always be tracked exactly correctly by
7995 @code{gnatmake}.
7997 @node Running gnatmake
7998 @section Running @code{gnatmake}
8000 @noindent
8001 The usual form of the @code{gnatmake} command is
8003 @smallexample
8004 $ gnatmake [@var{switches}] @var{file_name}
8005       [@var{file_names}] [@var{mode_switches}]
8006 @end smallexample
8008 @noindent
8009 The only required argument is one @var{file_name}, which specifies
8010 a compilation unit that is a main program. Several @var{file_names} can be
8011 specified: this will result in several executables being built.
8012 If @code{switches} are present, they can be placed before the first
8013 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8014 If @var{mode_switches} are present, they must always be placed after
8015 the last @var{file_name} and all @code{switches}.
8017 If you are using standard file extensions (.adb and .ads), then the
8018 extension may be omitted from the @var{file_name} arguments. However, if
8019 you are using non-standard extensions, then it is required that the
8020 extension be given. A relative or absolute directory path can be
8021 specified in a @var{file_name}, in which case, the input source file will
8022 be searched for in the specified directory only. Otherwise, the input
8023 source file will first be searched in the directory where
8024 @code{gnatmake} was invoked and if it is not found, it will be search on
8025 the source path of the compiler as described in
8026 @ref{Search Paths and the Run-Time Library (RTL)}.
8028 All @code{gnatmake} output (except when you specify
8029 @option{^-M^/DEPENDENCIES_LIST^}) is to
8030 @file{stderr}. The output produced by the
8031 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8032 @file{stdout}.
8034 @node Switches for gnatmake
8035 @section Switches for @code{gnatmake}
8037 @noindent
8038 You may specify any of the following switches to @code{gnatmake}:
8040 @table @option
8041 @c !sort!
8042 @ifclear vms
8043 @item --GCC=@var{compiler_name}
8044 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8045 Program used for compiling. The default is `@code{gcc}'. You need to use
8046 quotes around @var{compiler_name} if @code{compiler_name} contains
8047 spaces or other separator characters. As an example @option{--GCC="foo -x
8048 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8049 compiler. Note that switch @option{-c} is always inserted after your
8050 command name. Thus in the above example the compiler command that will
8051 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8052 If several @option{--GCC=compiler_name} are used, only the last
8053 @var{compiler_name} is taken into account. However, all the additional
8054 switches are also taken into account. Thus,
8055 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8056 @option{--GCC="bar -x -y -z -t"}.
8058 @item --GNATBIND=@var{binder_name}
8059 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8060 Program used for binding. The default is `@code{gnatbind}'. You need to
8061 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8062 or other separator characters. As an example @option{--GNATBIND="bar -x
8063 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8064 binder. Binder switches that are normally appended by @code{gnatmake} to
8065 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8067 @item --GNATLINK=@var{linker_name}
8068 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8069 Program used for linking. The default is `@code{gnatlink}'. You need to
8070 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8071 or other separator characters. As an example @option{--GNATLINK="lan -x
8072 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8073 linker. Linker switches that are normally appended by @code{gnatmake} to
8074 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8076 @end ifclear
8078 @item ^-a^/ALL_FILES^
8079 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8080 Consider all files in the make process, even the GNAT internal system
8081 files (for example, the predefined Ada library files), as well as any
8082 locked files. Locked files are files whose ALI file is write-protected.
8083 By default,
8084 @code{gnatmake} does not check these files,
8085 because the assumption is that the GNAT internal files are properly up
8086 to date, and also that any write protected ALI files have been properly
8087 installed. Note that if there is an installation problem, such that one
8088 of these files is not up to date, it will be properly caught by the
8089 binder.
8090 You may have to specify this switch if you are working on GNAT
8091 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8092 in conjunction with @option{^-f^/FORCE_COMPILE^}
8093 if you need to recompile an entire application,
8094 including run-time files, using special configuration pragmas,
8095 such as a @code{Normalize_Scalars} pragma.
8097 By default
8098 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8099 internal files with
8100 @ifclear vms
8101 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8102 @end ifclear
8103 @ifset vms
8104 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8105 @end ifset
8107 @item ^-b^/ACTIONS=BIND^
8108 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8109 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8110 compilation and binding, but no link.
8111 Can be combined with @option{^-l^/ACTIONS=LINK^}
8112 to do binding and linking. When not combined with
8113 @option{^-c^/ACTIONS=COMPILE^}
8114 all the units in the closure of the main program must have been previously
8115 compiled and must be up to date. The root unit specified by @var{file_name}
8116 may be given without extension, with the source extension or, if no GNAT
8117 Project File is specified, with the ALI file extension.
8119 @item ^-c^/ACTIONS=COMPILE^
8120 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8121 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8122 is also specified. Do not perform linking, except if both
8123 @option{^-b^/ACTIONS=BIND^} and
8124  @option{^-l^/ACTIONS=LINK^} are also specified.
8125 If the root unit specified by @var{file_name} is not a main unit, this is the
8126 default. Otherwise @code{gnatmake} will attempt binding and linking
8127 unless all objects are up to date and the executable is more recent than
8128 the objects.
8130 @item ^-C^/MAPPING^
8131 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8132 Use a temporary mapping file. A mapping file is a way to communicate to the
8133 compiler two mappings: from unit names to file names (without any directory
8134 information) and from file names to path names (with full directory
8135 information). These mappings are used by the compiler to short-circuit the path
8136 search. When @code{gnatmake} is invoked with this switch, it will create
8137 a temporary mapping file, initially populated by the project manager,
8138 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8139 Each invocation of the compiler will add the newly accessed sources to the
8140 mapping file. This will improve the source search during the next invocation
8141 of the compiler.
8143 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8144 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8145 Use a specific mapping file. The file, specified as a path name (absolute or
8146 relative) by this switch, should already exist, otherwise the switch is
8147 ineffective. The specified mapping file will be communicated to the compiler.
8148 This switch is not compatible with a project file
8149 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8150 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8152 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8153 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8154 Put all object files and ALI file in directory @var{dir}.
8155 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8156 and ALI files go in the current working directory.
8158 This switch cannot be used when using a project file.
8160 @item ^-f^/FORCE_COMPILE^
8161 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8162 Force recompilations. Recompile all sources, even though some object
8163 files may be up to date, but don't recompile predefined or GNAT internal
8164 files or locked files (files with a write-protected ALI file),
8165 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8167 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8168 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8169 When using project files, if some errors or warnings are detected during
8170 parsing and verbose mode is not in effect (no use of switch
8171 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8172 file, rather than its simple file name.
8174 @item ^-i^/IN_PLACE^
8175 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8176 In normal mode, @code{gnatmake} compiles all object files and ALI files
8177 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8178 then instead object files and ALI files that already exist are overwritten
8179 in place. This means that once a large project is organized into separate
8180 directories in the desired manner, then @code{gnatmake} will automatically
8181 maintain and update this organization. If no ALI files are found on the
8182 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8183 the new object and ALI files are created in the
8184 directory containing the source being compiled. If another organization
8185 is desired, where objects and sources are kept in different directories,
8186 a useful technique is to create dummy ALI files in the desired directories.
8187 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8188 the corresponding source file, and it will be put the resulting object
8189 and ALI files in the directory where it found the dummy file.
8191 @item ^-j^/PROCESSES=^@var{n}
8192 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8193 @cindex Parallel make
8194 Use @var{n} processes to carry out the (re)compilations. On a
8195 multiprocessor machine compilations will occur in parallel. In the
8196 event of compilation errors, messages from various compilations might
8197 get interspersed (but @code{gnatmake} will give you the full ordered
8198 list of failing compiles at the end). If this is problematic, rerun
8199 the make process with n set to 1 to get a clean list of messages.
8201 @item ^-k^/CONTINUE_ON_ERROR^
8202 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8203 Keep going. Continue as much as possible after a compilation error. To
8204 ease the programmer's task in case of compilation errors, the list of
8205 sources for which the compile fails is given when @code{gnatmake}
8206 terminates.
8208 If @code{gnatmake} is invoked with several @file{file_names} and with this
8209 switch, if there are compilation errors when building an executable,
8210 @code{gnatmake} will not attempt to build the following executables.
8212 @item ^-l^/ACTIONS=LINK^
8213 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8214 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8215 and linking. Linking will not be performed if combined with
8216 @option{^-c^/ACTIONS=COMPILE^}
8217 but not with @option{^-b^/ACTIONS=BIND^}.
8218 When not combined with @option{^-b^/ACTIONS=BIND^}
8219 all the units in the closure of the main program must have been previously
8220 compiled and must be up to date, and the main program need to have been bound.
8221 The root unit specified by @var{file_name}
8222 may be given without extension, with the source extension or, if no GNAT
8223 Project File is specified, with the ALI file extension.
8225 @item ^-m^/MINIMAL_RECOMPILATION^
8226 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8227 Specifies that the minimum necessary amount of recompilations
8228 be performed. In this mode @code{gnatmake} ignores time
8229 stamp differences when the only
8230 modifications to a source file consist in adding/removing comments,
8231 empty lines, spaces or tabs. This means that if you have changed the
8232 comments in a source file or have simply reformatted it, using this
8233 switch will tell gnatmake not to recompile files that depend on it
8234 (provided other sources on which these files depend have undergone no
8235 semantic modifications). Note that the debugging information may be
8236 out of date with respect to the sources if the @option{-m} switch causes
8237 a compilation to be switched, so the use of this switch represents a
8238 trade-off between compilation time and accurate debugging information.
8240 @item ^-M^/DEPENDENCIES_LIST^
8241 @cindex Dependencies, producing list
8242 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8243 Check if all objects are up to date. If they are, output the object
8244 dependences to @file{stdout} in a form that can be directly exploited in
8245 a @file{Makefile}. By default, each source file is prefixed with its
8246 (relative or absolute) directory name. This name is whatever you
8247 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8248 and @option{^-I^/SEARCH^} switches. If you use
8249 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8250 @option{^-q^/QUIET^}
8251 (see below), only the source file names,
8252 without relative paths, are output. If you just specify the
8253 @option{^-M^/DEPENDENCIES_LIST^}
8254 switch, dependencies of the GNAT internal system files are omitted. This
8255 is typically what you want. If you also specify
8256 the @option{^-a^/ALL_FILES^} switch,
8257 dependencies of the GNAT internal files are also listed. Note that
8258 dependencies of the objects in external Ada libraries (see switch
8259 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8260 are never reported.
8262 @item ^-n^/DO_OBJECT_CHECK^
8263 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8264 Don't compile, bind, or link. Checks if all objects are up to date.
8265 If they are not, the full name of the first file that needs to be
8266 recompiled is printed.
8267 Repeated use of this option, followed by compiling the indicated source
8268 file, will eventually result in recompiling all required units.
8270 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8271 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8272 Output executable name. The name of the final executable program will be
8273 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8274 name for the executable will be the name of the input file in appropriate form
8275 for an executable file on the host system.
8277 This switch cannot be used when invoking @code{gnatmake} with several
8278 @file{file_names}.
8280 @item ^-P^/PROJECT_FILE=^@var{project}
8281 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8282 Use project file @var{project}. Only one such switch can be used.
8283 See @ref{gnatmake and Project Files}.
8285 @item ^-q^/QUIET^
8286 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8287 Quiet. When this flag is not set, the commands carried out by
8288 @code{gnatmake} are displayed.
8290 @item ^-s^/SWITCH_CHECK/^
8291 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8292 Recompile if compiler switches have changed since last compilation.
8293 All compiler switches but -I and -o are taken into account in the
8294 following way:
8295 orders between different ``first letter'' switches are ignored, but
8296 orders between same switches are taken into account. For example,
8297 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8298 is equivalent to @option{-O -g}.
8300 This switch is recommended when Integrated Preprocessing is used.
8302 @item ^-u^/UNIQUE^
8303 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8304 Unique. Recompile at most the main files. It implies -c. Combined with
8305 -f, it is equivalent to calling the compiler directly. Note that using
8306 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8307 (see @ref{Project Files and Main Subprograms}).
8309 @item ^-U^/ALL_PROJECTS^
8310 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8311 When used without a project file or with one or several mains on the command
8312 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8313 on the command line, all sources of all project files are checked and compiled
8314 if not up to date, and libraries are rebuilt, if necessary.
8316 @item ^-v^/REASONS^
8317 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8318 Verbose. Displays the reason for all recompilations @code{gnatmake}
8319 decides are necessary.
8321 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8322 Indicates the verbosity of the parsing of GNAT project files.
8323 See @ref{Switches Related to Project Files}.
8325 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8326 Indicates that external variable @var{name} has the value @var{value}.
8327 The Project Manager will use this value for occurrences of
8328 @code{external(name)} when parsing the project file.
8329 See @ref{Switches Related to Project Files}.
8331 @item ^-z^/NOMAIN^
8332 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8333 No main subprogram. Bind and link the program even if the unit name
8334 given on the command line is a package name. The resulting executable
8335 will execute the elaboration routines of the package and its closure,
8336 then the finalization routines.
8338 @item ^-g^/DEBUG^
8339 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8340 Enable debugging. This switch is simply passed to the compiler and to the
8341 linker.
8343 @end table
8345 @table @asis
8346 @item @code{gcc} @asis{switches}
8347 @ifclear vms
8348 Any uppercase switch (other than @option{-A},
8349 @option{-L} or
8350 @option{-S}) or any switch that is more than one character is passed to
8351 @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8352 @end ifclear
8353 @ifset vms
8354 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8355 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8356 automatically treated as a compiler switch, and passed on to all
8357 compilations that are carried out.
8358 @end ifset
8359 @end table
8361 @noindent
8362 Source and library search path switches:
8364 @table @option
8365 @c !sort!
8366 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8367 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8368 When looking for source files also look in directory @var{dir}.
8369 The order in which source files search is undertaken is
8370 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8372 @item ^-aL^/SKIP_MISSING=^@var{dir}
8373 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8374 Consider @var{dir} as being an externally provided Ada library.
8375 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8376 files have been located in directory @var{dir}. This allows you to have
8377 missing bodies for the units in @var{dir} and to ignore out of date bodies
8378 for the same units. You still need to specify
8379 the location of the specs for these units by using the switches
8380 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8381 or @option{^-I^/SEARCH=^@var{dir}}.
8382 Note: this switch is provided for compatibility with previous versions
8383 of @code{gnatmake}. The easier method of causing standard libraries
8384 to be excluded from consideration is to write-protect the corresponding
8385 ALI files.
8387 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8388 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8389 When searching for library and object files, look in directory
8390 @var{dir}. The order in which library files are searched is described in
8391 @ref{Search Paths for gnatbind}.
8393 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8394 @cindex Search paths, for @code{gnatmake}
8395 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8396 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8397 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8399 @item ^-I^/SEARCH=^@var{dir}
8400 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8401 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8402 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8404 @item ^-I-^/NOCURRENT_DIRECTORY^
8405 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8406 @cindex Source files, suppressing search
8407 Do not look for source files in the directory containing the source
8408 file named in the command line.
8409 Do not look for ALI or object files in the directory
8410 where @code{gnatmake} was invoked.
8412 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8413 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8414 @cindex Linker libraries
8415 Add directory @var{dir} to the list of directories in which the linker
8416 will search for libraries. This is equivalent to
8417 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8418 @ifclear vms
8419 Furthermore, under Windows, the sources pointed to by the libraries path
8420 set in the registry are not searched for.
8421 @end ifclear
8423 @item -nostdinc
8424 @cindex @option{-nostdinc} (@code{gnatmake})
8425 Do not look for source files in the system default directory.
8427 @item -nostdlib
8428 @cindex @option{-nostdlib} (@code{gnatmake})
8429 Do not look for library files in the system default directory.
8431 @item --RTS=@var{rts-path}
8432 @cindex @option{--RTS} (@code{gnatmake})
8433 Specifies the default location of the runtime library. GNAT looks for the
8434 runtime
8435 in the following directories, and stops as soon as a valid runtime is found
8436 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8437 @file{ada_object_path} present):
8439 @itemize @bullet
8440 @item <current directory>/$rts_path
8442 @item <default-search-dir>/$rts_path
8444 @item <default-search-dir>/rts-$rts_path
8445 @end itemize
8447 @noindent
8448 The selected path is handled like a normal RTS path.
8450 @end table
8452 @node Mode Switches for gnatmake
8453 @section Mode Switches for @code{gnatmake}
8455 @noindent
8456 The mode switches (referred to as @code{mode_switches}) allow the
8457 inclusion of switches that are to be passed to the compiler itself, the
8458 binder or the linker. The effect of a mode switch is to cause all
8459 subsequent switches up to the end of the switch list, or up to the next
8460 mode switch, to be interpreted as switches to be passed on to the
8461 designated component of GNAT.
8463 @table @option
8464 @c !sort!
8465 @item -cargs @var{switches}
8466 @cindex @option{-cargs} (@code{gnatmake})
8467 Compiler switches. Here @var{switches} is a list of switches
8468 that are valid switches for @code{gcc}. They will be passed on to
8469 all compile steps performed by @code{gnatmake}.
8471 @item -bargs @var{switches}
8472 @cindex @option{-bargs} (@code{gnatmake})
8473 Binder switches. Here @var{switches} is a list of switches
8474 that are valid switches for @code{gnatbind}. They will be passed on to
8475 all bind steps performed by @code{gnatmake}.
8477 @item -largs @var{switches}
8478 @cindex @option{-largs} (@code{gnatmake})
8479 Linker switches. Here @var{switches} is a list of switches
8480 that are valid switches for @code{gnatlink}. They will be passed on to
8481 all link steps performed by @code{gnatmake}.
8483 @item -margs @var{switches}
8484 @cindex @option{-margs} (@code{gnatmake})
8485 Make switches. The switches are directly interpreted by @code{gnatmake},
8486 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8487 or @option{-largs}.
8488 @end table
8490 @node Notes on the Command Line
8491 @section Notes on the Command Line
8493 @noindent
8494 This section contains some additional useful notes on the operation
8495 of the @code{gnatmake} command.
8497 @itemize @bullet
8498 @item
8499 @cindex Recompilation, by @code{gnatmake}
8500 If @code{gnatmake} finds no ALI files, it recompiles the main program
8501 and all other units required by the main program.
8502 This means that @code{gnatmake}
8503 can be used for the initial compile, as well as during subsequent steps of
8504 the development cycle.
8506 @item
8507 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8508 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8509 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8510 warning.
8512 @item
8513 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8514 is used to specify both source and
8515 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8516 instead if you just want to specify
8517 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8518 if you want to specify library paths
8519 only.
8521 @item
8522 @code{gnatmake} examines both an ALI file and its corresponding object file
8523 for consistency. If an ALI is more recent than its corresponding object,
8524 or if the object file is missing, the corresponding source will be recompiled.
8525 Note that @code{gnatmake} expects an ALI and the corresponding object file
8526 to be in the same directory.
8528 @item
8529 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8530 This may conveniently be used to exclude standard libraries from
8531 consideration and in particular it means that the use of the
8532 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8533 unless @option{^-a^/ALL_FILES^} is also specified.
8535 @item
8536 @code{gnatmake} has been designed to make the use of Ada libraries
8537 particularly convenient. Assume you have an Ada library organized
8538 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8539 of your Ada compilation units,
8540 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8541 specs of these units, but no bodies. Then to compile a unit
8542 stored in @code{main.adb}, which uses this Ada library you would just type
8544 @smallexample
8545 @ifclear vms
8546 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8547 @end ifclear
8548 @ifset vms
8549 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8550            /SKIP_MISSING=@i{[OBJ_DIR]} main
8551 @end ifset
8552 @end smallexample
8554 @item
8555 Using @code{gnatmake} along with the
8556 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8557 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8558 this switch,
8559 you can update the comments/format of your
8560 source files without having to recompile everything. Note, however, that
8561 adding or deleting lines in a source files may render its debugging
8562 info obsolete. If the file in question is a spec, the impact is rather
8563 limited, as that debugging info will only be useful during the
8564 elaboration phase of your program. For bodies the impact can be more
8565 significant. In all events, your debugger will warn you if a source file
8566 is more recent than the corresponding object, and alert you to the fact
8567 that the debugging information may be out of date.
8568 @end itemize
8570 @node How gnatmake Works
8571 @section How @code{gnatmake} Works
8573 @noindent
8574 Generally @code{gnatmake} automatically performs all necessary
8575 recompilations and you don't need to worry about how it works. However,
8576 it may be useful to have some basic understanding of the @code{gnatmake}
8577 approach and in particular to understand how it uses the results of
8578 previous compilations without incorrectly depending on them.
8580 First a definition: an object file is considered @dfn{up to date} if the
8581 corresponding ALI file exists and its time stamp predates that of the
8582 object file and if all the source files listed in the
8583 dependency section of this ALI file have time stamps matching those in
8584 the ALI file. This means that neither the source file itself nor any
8585 files that it depends on have been modified, and hence there is no need
8586 to recompile this file.
8588 @code{gnatmake} works by first checking if the specified main unit is up
8589 to date. If so, no compilations are required for the main unit. If not,
8590 @code{gnatmake} compiles the main program to build a new ALI file that
8591 reflects the latest sources. Then the ALI file of the main unit is
8592 examined to find all the source files on which the main program depends,
8593 and @code{gnatmake} recursively applies the above procedure on all these files.
8595 This process ensures that @code{gnatmake} only trusts the dependencies
8596 in an existing ALI file if they are known to be correct. Otherwise it
8597 always recompiles to determine a new, guaranteed accurate set of
8598 dependencies. As a result the program is compiled ``upside down'' from what may
8599 be more familiar as the required order of compilation in some other Ada
8600 systems. In particular, clients are compiled before the units on which
8601 they depend. The ability of GNAT to compile in any order is critical in
8602 allowing an order of compilation to be chosen that guarantees that
8603 @code{gnatmake} will recompute a correct set of new dependencies if
8604 necessary.
8606 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8607 imported by several of the executables, it will be recompiled at most once.
8609 Note: when using non-standard naming conventions
8610 (See @ref{Using Other File Names}), changing through a configuration pragmas
8611 file the version of a source and invoking @code{gnatmake} to recompile may
8612 have no effect, if the previous version of the source is still accessible
8613 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8615 @node Examples of gnatmake Usage
8616 @section Examples of @code{gnatmake} Usage
8618 @table @code
8619 @item gnatmake hello.adb
8620 Compile all files necessary to bind and link the main program
8621 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8622 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8624 @item gnatmake main1 main2 main3
8625 Compile all files necessary to bind and link the main programs
8626 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8627 (containing unit @code{Main2}) and @file{main3.adb}
8628 (containing unit @code{Main3}) and bind and link the resulting object files
8629 to generate three executable files @file{^main1^MAIN1.EXE^},
8630 @file{^main2^MAIN2.EXE^}
8631 and @file{^main3^MAIN3.EXE^}.
8633 @ifclear vms
8634 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8635 @end ifclear
8637 @ifset vms
8638 @item gnatmake Main_Unit /QUIET
8639    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8640    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8641 @end ifset
8642 Compile all files necessary to bind and link the main program unit
8643 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8644 be done with optimization level 2 and the order of elaboration will be
8645 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8646 displaying commands it is executing.
8647 @end table
8650 @c *************************
8651 @node Improving Performance
8652 @chapter Improving Performance
8653 @cindex Improving performance
8655 @noindent
8656 This chapter presents several topics related to program performance.
8657 It first describes some of the tradeoffs that need to be considered
8658 and some of the techniques for making your program run faster.
8659 It then documents the @command{gnatelim} tool, which can reduce
8660 the size of program executables.
8662 @ifnottex
8663 @menu
8664 * Performance Considerations::
8665 * Reducing the Size of Ada Executables with gnatelim::
8666 @end menu
8667 @end ifnottex
8670 @c *****************************
8671 @node Performance Considerations
8672 @section Performance Considerations
8674 @noindent
8675 The GNAT system provides a number of options that allow a trade-off
8676 between
8678 @itemize @bullet
8679 @item
8680 performance of the generated code
8682 @item
8683 speed of compilation
8685 @item
8686 minimization of dependences and recompilation
8688 @item
8689 the degree of run-time checking.
8690 @end itemize
8692 @noindent
8693 The defaults (if no options are selected) aim at improving the speed
8694 of compilation and minimizing dependences, at the expense of performance
8695 of the generated code:
8697 @itemize @bullet
8698 @item
8699 no optimization
8701 @item
8702 no inlining of subprogram calls
8704 @item
8705 all run-time checks enabled except overflow and elaboration checks
8706 @end itemize
8708 @noindent
8709 These options are suitable for most program development purposes. This
8710 chapter describes how you can modify these choices, and also provides
8711 some guidelines on debugging optimized code.
8713 @menu
8714 * Controlling Run-Time Checks::
8715 * Use of Restrictions::
8716 * Optimization Levels::
8717 * Debugging Optimized Code::
8718 * Inlining of Subprograms::
8719 * Optimization and Strict Aliasing::
8720 @ifset vms
8721 * Coverage Analysis::
8722 @end ifset
8723 @end menu
8725 @node Controlling Run-Time Checks
8726 @subsection Controlling Run-Time Checks
8728 @noindent
8729 By default, GNAT generates all run-time checks, except arithmetic overflow
8730 checking for integer operations and checks for access before elaboration on
8731 subprogram calls. The latter are not required in default mode, because all
8732 necessary checking is done at compile time.
8733 @cindex @option{-gnatp} (@code{gcc})
8734 @cindex @option{-gnato} (@code{gcc})
8735 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8736 be modified. @xref{Run-Time Checks}.
8738 Our experience is that the default is suitable for most development
8739 purposes.
8741 We treat integer overflow specially because these
8742 are quite expensive and in our experience are not as important as other
8743 run-time checks in the development process. Note that division by zero
8744 is not considered an overflow check, and divide by zero checks are
8745 generated where required by default.
8747 Elaboration checks are off by default, and also not needed by default, since
8748 GNAT uses a static elaboration analysis approach that avoids the need for
8749 run-time checking. This manual contains a full chapter discussing the issue
8750 of elaboration checks, and if the default is not satisfactory for your use,
8751 you should read this chapter.
8753 For validity checks, the minimal checks required by the Ada Reference
8754 Manual (for case statements and assignments to array elements) are on
8755 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8756 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8757 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8758 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8759 are also suppressed entirely if @option{-gnatp} is used.
8761 @cindex Overflow checks
8762 @cindex Checks, overflow
8763 @findex Suppress
8764 @findex Unsuppress
8765 @cindex pragma Suppress
8766 @cindex pragma Unsuppress
8767 Note that the setting of the switches controls the default setting of
8768 the checks. They may be modified using either @code{pragma Suppress} (to
8769 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8770 checks) in the program source.
8772 @node Use of Restrictions
8773 @subsection Use of Restrictions
8775 @noindent
8776 The use of pragma Restrictions allows you to control which features are
8777 permitted in your program. Apart from the obvious point that if you avoid
8778 relatively expensive features like finalization (enforceable by the use
8779 of pragma Restrictions (No_Finalization), the use of this pragma does not
8780 affect the generated code in most cases.
8782 One notable exception to this rule is that the possibility of task abort
8783 results in some distributed overhead, particularly if finalization or
8784 exception handlers are used. The reason is that certain sections of code
8785 have to be marked as non-abortable.
8787 If you use neither the @code{abort} statement, nor asynchronous transfer
8788 of control (@code{select .. then abort}), then this distributed overhead
8789 is removed, which may have a general positive effect in improving
8790 overall performance.  Especially code involving frequent use of tasking
8791 constructs and controlled types will show much improved performance.
8792 The relevant restrictions pragmas are
8794 @smallexample
8795    pragma Restrictions (No_Abort_Statements);
8796    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8797 @end smallexample
8799 @noindent
8800 It is recommended that these restriction pragmas be used if possible. Note
8801 that this also means that you can write code without worrying about the
8802 possibility of an immediate abort at any point.
8804 @node Optimization Levels
8805 @subsection Optimization Levels
8806 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8808 @noindent
8809 The default is optimization off. This results in the fastest compile
8810 times, but GNAT makes absolutely no attempt to optimize, and the
8811 generated programs are considerably larger and slower than when
8812 optimization is enabled. You can use the
8813 @ifclear vms
8814 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8815 @end ifclear
8816 @ifset vms
8817 @code{OPTIMIZE} qualifier
8818 @end ifset
8819 to @code{gcc} to control the optimization level:
8821 @table @option
8822 @item ^-O0^/OPTIMIZE=NONE^
8823 No optimization (the default);
8824 generates unoptimized code but has
8825 the fastest compilation time.
8827 @item ^-O1^/OPTIMIZE=SOME^
8828 Medium level optimization;
8829 optimizes reasonably well but does not
8830 degrade compilation time significantly.
8832 @item ^-O2^/OPTIMIZE=ALL^
8833 @ifset vms
8834 @itemx /OPTIMIZE=DEVELOPMENT
8835 @end ifset
8836 Full optimization;
8837 generates highly optimized code and has
8838 the slowest compilation time.
8840 @item ^-O3^/OPTIMIZE=INLINING^
8841 Full optimization as in @option{-O2},
8842 and also attempts automatic inlining of small
8843 subprograms within a unit (@pxref{Inlining of Subprograms}).
8844 @end table
8846 @noindent
8847 Higher optimization levels perform more global transformations on the
8848 program and apply more expensive analysis algorithms in order to generate
8849 faster and more compact code. The price in compilation time, and the
8850 resulting improvement in execution time,
8851 both depend on the particular application and the hardware environment.
8852 You should experiment to find the best level for your application.
8854 Since the precise set of optimizations done at each level will vary from
8855 release to release (and sometime from target to target), it is best to think
8856 of the optimization settings in general terms.
8857 The @cite{Using GNU GCC} manual contains details about
8858 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8859 individually enable or disable specific optimizations.
8861 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8862 been tested extensively at all optimization levels. There are some bugs
8863 which appear only with optimization turned on, but there have also been
8864 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8865 level of optimization does not improve the reliability of the code
8866 generator, which in practice is highly reliable at all optimization
8867 levels.
8869 Note regarding the use of @option{-O3}: The use of this optimization level
8870 is generally discouraged with GNAT, since it often results in larger
8871 executables which run more slowly. See further discussion of this point
8872 in @pxref{Inlining of Subprograms}.
8875 @node Debugging Optimized Code
8876 @subsection Debugging Optimized Code
8877 @cindex Debugging optimized code
8878 @cindex Optimization and debugging
8880 @noindent
8881 Although it is possible to do a reasonable amount of debugging at
8882 @ifclear vms
8883 non-zero optimization levels,
8884 the higher the level the more likely that
8885 @end ifclear
8886 @ifset vms
8887 @option{/OPTIMIZE} settings other than @code{NONE},
8888 such settings will make it more likely that
8889 @end ifset
8890 source-level constructs will have been eliminated by optimization.
8891 For example, if a loop is strength-reduced, the loop
8892 control variable may be completely eliminated and thus cannot be
8893 displayed in the debugger.
8894 This can only happen at @option{-O2} or @option{-O3}.
8895 Explicit temporary variables that you code might be eliminated at
8896 ^level^setting^ @option{-O1} or higher.
8898 The use of the @option{^-g^/DEBUG^} switch,
8899 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8900 which is needed for source-level debugging,
8901 affects the size of the program executable on disk,
8902 and indeed the debugging information can be quite large.
8903 However, it has no effect on the generated code (and thus does not
8904 degrade performance)
8906 Since the compiler generates debugging tables for a compilation unit before
8907 it performs optimizations, the optimizing transformations may invalidate some
8908 of the debugging data.  You therefore need to anticipate certain
8909 anomalous situations that may arise while debugging optimized code.
8910 These are the most common cases:
8912 @enumerate
8913 @item
8914 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8915 commands show
8916 the PC bouncing back and forth in the code.  This may result from any of
8917 the following optimizations:
8919 @itemize @bullet
8920 @item
8921 @i{Common subexpression elimination:} using a single instance of code for a
8922 quantity that the source computes several times.  As a result you
8923 may not be able to stop on what looks like a statement.
8925 @item
8926 @i{Invariant code motion:} moving an expression that does not change within a
8927 loop, to the beginning of the loop.
8929 @item
8930 @i{Instruction scheduling:} moving instructions so as to
8931 overlap loads and stores (typically) with other code, or in
8932 general to move computations of values closer to their uses. Often
8933 this causes you to pass an assignment statement without the assignment
8934 happening and then later bounce back to the statement when the
8935 value is actually needed.  Placing a breakpoint on a line of code
8936 and then stepping over it may, therefore, not always cause all the
8937 expected side-effects.
8938 @end itemize
8940 @item
8941 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8942 two identical pieces of code are merged and the program counter suddenly
8943 jumps to a statement that is not supposed to be executed, simply because
8944 it (and the code following) translates to the same thing as the code
8945 that @emph{was} supposed to be executed.  This effect is typically seen in
8946 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
8947 a @code{break} in a C @code{^switch^switch^} statement.
8949 @item
8950 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
8951 There are various reasons for this effect:
8953 @itemize @bullet
8954 @item
8955 In a subprogram prologue, a parameter may not yet have been moved to its
8956 ``home''.
8958 @item
8959 A variable may be dead, and its register re-used.  This is
8960 probably the most common cause.
8962 @item
8963 As mentioned above, the assignment of a value to a variable may
8964 have been moved.
8966 @item
8967 A variable may be eliminated entirely by value propagation or
8968 other means.  In this case, GCC may incorrectly generate debugging
8969 information for the variable
8970 @end itemize
8972 @noindent
8973 In general, when an unexpected value appears for a local variable or parameter
8974 you should first ascertain if that value was actually computed by
8975 your program, as opposed to being incorrectly reported by the debugger.
8976 Record fields or
8977 array elements in an object designated by an access value
8978 are generally less of a problem, once you have ascertained that the access
8979 value is sensible.
8980 Typically, this means checking variables in the preceding code and in the
8981 calling subprogram to verify that the value observed is explainable from other
8982 values (one must apply the procedure recursively to those
8983 other values); or re-running the code and stopping a little earlier
8984 (perhaps before the call) and stepping to better see how the variable obtained
8985 the value in question; or continuing to step @emph{from} the point of the
8986 strange value to see if code motion had simply moved the variable's
8987 assignments later.
8988 @end enumerate
8990 @noindent
8991 In light of such anomalies, a recommended technique is to use @option{-O0}
8992 early in the software development cycle, when extensive debugging capabilities
8993 are most needed, and then move to @option{-O1} and later @option{-O2} as
8994 the debugger becomes less critical.
8995 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
8996 a release management issue.
8997 @ifclear vms
8998 Note that if you use @option{-g} you can then use the @command{strip} program
8999 on the resulting executable,
9000 which removes both debugging information and global symbols.
9001 @end ifclear
9004 @node Inlining of Subprograms
9005 @subsection Inlining of Subprograms
9007 @noindent
9008 A call to a subprogram in the current unit is inlined if all the
9009 following conditions are met:
9011 @itemize @bullet
9012 @item
9013 The optimization level is at least @option{-O1}.
9015 @item
9016 The called subprogram is suitable for inlining: It must be small enough
9017 and not contain nested subprograms or anything else that @code{gcc}
9018 cannot support in inlined subprograms.
9020 @item
9021 The call occurs after the definition of the body of the subprogram.
9023 @item
9024 @cindex pragma Inline
9025 @findex Inline
9026 Either @code{pragma Inline} applies to the subprogram or it is
9027 small and automatic inlining (optimization level @option{-O3}) is
9028 specified.
9029 @end itemize
9031 @noindent
9032 Calls to subprograms in @code{with}'ed units are normally not inlined.
9033 To achieve this level of inlining, the following conditions must all be
9034 true:
9036 @itemize @bullet
9037 @item
9038 The optimization level is at least @option{-O1}.
9040 @item
9041 The called subprogram is suitable for inlining: It must be small enough
9042 and not contain nested subprograms or anything else @code{gcc} cannot
9043 support in inlined subprograms.
9045 @item
9046 The call appears in a body (not in a package spec).
9048 @item
9049 There is a @code{pragma Inline} for the subprogram.
9051 @item
9052 @cindex @option{-gnatn} (@code{gcc})
9053 The @option{^-gnatn^/INLINE^} switch
9054 is used in the @code{gcc} command line
9055 @end itemize
9057 Note that specifying the @option{-gnatn} switch causes additional
9058 compilation dependencies. Consider the following:
9060 @smallexample @c ada
9061 @cartouche
9062 package R is
9063    procedure Q;
9064    pragma Inline (Q);
9065 end R;
9066 package body R is
9067    ...
9068 end R;
9070 with R;
9071 procedure Main is
9072 begin
9073    ...
9074    R.Q;
9075 end Main;
9076 @end cartouche
9077 @end smallexample
9079 @noindent
9080 With the default behavior (no @option{-gnatn} switch specified), the
9081 compilation of the @code{Main} procedure depends only on its own source,
9082 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9083 means that editing the body of @code{R} does not require recompiling
9084 @code{Main}.
9086 On the other hand, the call @code{R.Q} is not inlined under these
9087 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9088 is compiled, the call will be inlined if the body of @code{Q} is small
9089 enough, but now @code{Main} depends on the body of @code{R} in
9090 @file{r.adb} as well as on the spec. This means that if this body is edited,
9091 the main program must be recompiled. Note that this extra dependency
9092 occurs whether or not the call is in fact inlined by @code{gcc}.
9094 The use of front end inlining with @option{-gnatN} generates similar
9095 additional dependencies.
9097 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9098 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9099 can be used to prevent
9100 all inlining. This switch overrides all other conditions and ensures
9101 that no inlining occurs. The extra dependences resulting from
9102 @option{-gnatn} will still be active, even if
9103 this switch is used to suppress the resulting inlining actions.
9105 Note regarding the use of @option{-O3}: There is no difference in inlining
9106 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9107 pragma @code{Inline} assuming the use of @option{-gnatn}
9108 or @option{-gnatN} (the switches that activate inlining). If you have used
9109 pragma @code{Inline} in appropriate cases, then it is usually much better
9110 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9111 in this case only has the effect of inlining subprograms you did not
9112 think should be inlined. We often find that the use of @option{-O3} slows
9113 down code by performing excessive inlining, leading to increased instruction
9114 cache pressure from the increased code size. So the bottom line here is
9115 that you should not automatically assume that @option{-O3} is better than
9116 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9117 it actually improves performance.
9119 @node Optimization and Strict Aliasing
9120 @subsection Optimization and Strict Aliasing
9121 @cindex Aliasing
9122 @cindex Strict Aliasing
9123 @cindex No_Strict_Aliasing
9125 @noindent
9126 The strong typing capabilities of Ada allow an optimizer to generate
9127 efficient code in situations where other languages would be forced to
9128 make worst case assumptions preventing such optimizations. Consider
9129 the following example:
9131 @smallexample @c ada
9132 @cartouche
9133 procedure R is
9134    type Int1 is new Integer;
9135    type Int2 is new Integer;
9136    type Int1A is access Int1;
9137    type Int2A is access Int2;
9138    Int1V : Int1A;
9139    Int2V : Int2A;
9140    ...
9142 begin
9143    ...
9144    for J in Data'Range loop
9145       if Data (J) = Int1V.all then
9146          Int2V.all := Int2V.all + 1;
9147       end if;
9148    end loop;
9149    ...
9150 end R;
9151 @end cartouche
9152 @end smallexample
9154 @noindent
9155 In this example, since the variable @code{Int1V} can only access objects
9156 of type @code{Int1}, and @code{Int2V} can only access objects of type
9157 @code{Int2}, there is no possibility that the assignment to
9158 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9159 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9160 for all iterations of the loop and avoid the extra memory reference
9161 required to dereference it each time through the loop.
9163 This kind of optimziation, called strict aliasing analysis, is
9164 triggered by specifying an optimization level of @option{-O2} or
9165 higher and allows @code{GNAT} to generate more efficient code
9166 when access values are involved.
9168 However, although this optimization is always correct in terms of
9169 the formal semantics of the Ada Reference Manual, difficulties can
9170 arise if features like @code{Unchecked_Conversion} are used to break
9171 the typing system. Consider the following complete program example:
9173 @smallexample @c ada
9174 @cartouche
9175 package p1 is
9176    type int1 is new integer;
9177    type int2 is new integer;
9178    type a1 is access int1;
9179    type a2 is access int2;
9180 end p1;
9182 with p1; use p1;
9183 package p2 is
9184    function to_a2 (Input : a1) return a2;
9185 end p2;
9187 with Unchecked_Conversion;
9188 package body p2 is
9189    function to_a2 (Input : a1) return a2 is
9190       function to_a2u is
9191         new Unchecked_Conversion (a1, a2);
9192    begin
9193       return to_a2u (Input);
9194    end to_a2;
9195 end p2;
9197 with p2; use p2;
9198 with p1; use p1;
9199 with Text_IO; use Text_IO;
9200 procedure m is
9201    v1 : a1 := new int1;
9202    v2 : a2 := to_a2 (v1);
9203 begin
9204    v1.all := 1;
9205    v2.all := 0;
9206    put_line (int1'image (v1.all));
9207 end;
9208 @end cartouche
9209 @end smallexample
9211 @noindent
9212 This program prints out 0 in @code{-O0} or @code{-O1}
9213 mode, but it prints out 1 in @code{-O2} mode. That's
9214 because in strict aliasing mode, the compiler can and
9215 does assume that the assignment to @code{v2.all} could not
9216 affect the value of @code{v1.all}, since different types
9217 are involved.
9219 This behavior is not a case of non-conformance with the standard, since
9220 the Ada RM specifies that an unchecked conversion where the resulting
9221 bit pattern is not a correct value of the target type can result in an
9222 abnormal value and attempting to reference an abnormal value makes the
9223 execution of a program erroneous.  That's the case here since the result
9224 does not point to an object of type @code{int2}.  This means that the
9225 effect is entirely unpredictable.
9227 However, although that explanation may satisfy a language
9228 lawyer, in practice an applications programmer expects an
9229 unchecked conversion involving pointers to create true
9230 aliases and the behavior of printing 1 seems plain wrong.
9231 In this case, the strict aliasing optimization is unwelcome.
9233 Indeed the compiler recognizes this possibility, and the
9234 unchecked conversion generates a warning:
9236 @smallexample
9237 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9238 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9239 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9240 @end smallexample
9242 @noindent
9243 Unfortunately the problem is recognized when compiling the body of
9244 package @code{p2}, but the actual "bad" code is generated while
9245 compiling the body of @code{m} and this latter compilation does not see
9246 the suspicious @code{Unchecked_Conversion}.
9248 As implied by the warning message, there are approaches you can use to
9249 avoid the unwanted strict aliasing optimization in a case like this.
9251 One possibility is to simply avoid the use of @code{-O2}, but
9252 that is a bit drastic, since it throws away a number of useful
9253 optimizations that do not involve strict aliasing assumptions.
9255 A less drastic approach is to compile the program using the
9256 option @code{-fno-strict-aliasing}. Actually it is only the
9257 unit containing the dereferencing of the suspicious pointer
9258 that needs to be compiled. So in this case, if we compile
9259 unit @code{m} with this switch, then we get the expected
9260 value of zero printed. Analyzing which units might need
9261 the switch can be painful, so a more reasonable approach
9262 is to compile the entire program with options @code{-O2}
9263 and @code{-fno-strict-aliasing}. If the performance is
9264 satisfactory with this combination of options, then the
9265 advantage is that the entire issue of possible "wrong"
9266 optimization due to strict aliasing is avoided.
9268 To avoid the use of compiler switches, the configuration
9269 pragma @code{No_Strict_Aliasing} with no parameters may be
9270 used to specify that for all access types, the strict
9271 aliasing optimization should be suppressed.
9273 However, these approaches are still overkill, in that they causes
9274 all manipulations of all access values to be deoptimized. A more
9275 refined approach is to concentrate attention on the specific
9276 access type identified as problematic.
9278 First, if a careful analysis of uses of the pointer shows
9279 that there are no possible problematic references, then
9280 the warning can be suppressed by bracketing the
9281 instantiation of @code{Unchecked_Conversion} to turn
9282 the warning off:
9284 @smallexample @c ada
9285    pragma Warnings (Off);
9286    function to_a2u is
9287      new Unchecked_Conversion (a1, a2);
9288    pragma Warnings (On);
9289 @end smallexample
9291 @noindent
9292 Of course that approach is not appropriate for this particular
9293 example, since indeed there is a problematic reference. In this
9294 case we can take one of two other approaches.
9296 The first possibility is to move the instantiation of unchecked
9297 conversion to the unit in which the type is declared. In
9298 this example, we would move the instantiation of
9299 @code{Unchecked_Conversion} from the body of package
9300 @code{p2} to the spec of package @code{p1}. Now the
9301 warning disappears. That's because any use of the
9302 access type knows there is a suspicious unchecked
9303 conversion, and the strict aliasing optimization
9304 is automatically suppressed for the type.
9306 If it is not practical to move the unchecked conversion to the same unit
9307 in which the destination access type is declared (perhaps because the
9308 source type is not visible in that unit), you may use pragma
9309 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9310 same declarative sequence as the declaration of the access type:
9312 @smallexample @c ada
9313    type a2 is access int2;
9314    pragma No_Strict_Aliasing (a2);
9315 @end smallexample
9317 @noindent
9318 Here again, the compiler now knows that the strict aliasing optimization
9319 should be suppressed for any reference to type @code{a2} and the
9320 expected behavior is obtained.
9322 Finally, note that although the compiler can generate warnings for
9323 simple cases of unchecked conversions, there are tricker and more
9324 indirect ways of creating type incorrect aliases which the compiler
9325 cannot detect. Examples are the use of address overlays and unchecked
9326 conversions involving composite types containing access types as
9327 components. In such cases, no warnings are generated, but there can
9328 still be aliasing problems. One safe coding practice is to forbid the
9329 use of address clauses for type overlaying, and to allow unchecked
9330 conversion only for primitive types. This is not really a significant
9331 restriction since any possible desired effect can be achieved by
9332 unchecked conversion of access values.
9334 @ifset vms
9335 @node Coverage Analysis
9336 @subsection Coverage Analysis
9338 @noindent
9339 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9340 the user to determine the distribution of execution time across a program,
9341 @pxref{Profiling} for details of usage.
9342 @end ifset
9344 @node Reducing the Size of Ada Executables with gnatelim
9345 @section Reducing the Size of Ada Executables with @code{gnatelim}
9346 @findex gnatelim
9348 @noindent
9349 This section describes @command{gnatelim}, a tool which detects unused
9350 subprograms and helps the compiler to create a smaller executable for your
9351 program.
9353 @menu
9354 * About gnatelim::
9355 * Running gnatelim::
9356 * Correcting the List of Eliminate Pragmas::
9357 * Making Your Executables Smaller::
9358 * Summary of the gnatelim Usage Cycle::
9359 @end menu
9361 @node About gnatelim
9362 @subsection About @code{gnatelim}
9364 @noindent
9365 When a program shares a set of Ada
9366 packages with other programs, it may happen that this program uses
9367 only a fraction of the subprograms defined in these packages. The code
9368 created for these unused subprograms increases the size of the executable.
9370 @code{gnatelim} tracks unused subprograms in an Ada program and
9371 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9372 subprograms that are declared but never called. By placing the list of
9373 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9374 recompiling your program, you may decrease the size of its executable,
9375 because the compiler will not generate the code for 'eliminated' subprograms.
9376 See GNAT Reference Manual for more information about this pragma.
9378 @code{gnatelim} needs as its input data the name of the main subprogram
9379 and a bind file for a main subprogram.
9381 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9382 the main subprogram. @code{gnatelim} can work with both Ada and C
9383 bind files; when both are present, it uses the Ada bind file.
9384 The following commands will build the program and create the bind file:
9386 @smallexample
9387 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9388 $ gnatbind main_prog
9389 @end smallexample
9391 Note that @code{gnatelim} needs neither object nor ALI files.
9393 @node Running gnatelim
9394 @subsection Running @code{gnatelim}
9396 @noindent
9397 @code{gnatelim} has the following command-line interface:
9399 @smallexample
9400 $ gnatelim [options] name
9401 @end smallexample
9403 @noindent
9404 @code{name} should be a name of a source file that contains the main subprogram
9405 of a program (partition).
9407 @code{gnatelim} has the following switches:
9409 @table @option
9410 @c !sort!
9411 @item ^-q^/QUIET^
9412 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9413 Quiet mode: by default @code{gnatelim} outputs to the standard error
9414 stream the number of program units left to be processed. This option turns
9415 this trace off.
9417 @item ^-v^/VERBOSE^
9418 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9419 Verbose mode: @code{gnatelim} version information is printed as Ada
9420 comments to the standard output stream. Also, in addition to the number of
9421 program units left @code{gnatelim} will output the name of the current unit
9422 being processed.
9424 @item ^-a^/ALL^
9425 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9426 Also look for subprograms from the GNAT run time that can be eliminated. Note
9427 that when @file{gnat.adc} is produced using this switch, the entire program
9428 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9430 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9431 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9432 When looking for source files also look in directory @var{dir}. Specifying
9433 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9434 sources in the current directory.
9436 @item ^-b^/BIND_FILE=^@var{bind_file}
9437 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9438 Specifies @var{bind_file} as the bind file to process. If not set, the name
9439 of the bind file is computed from the full expanded Ada name
9440 of a main subprogram.
9442 @item ^-C^/CONFIG_FILE=^@var{config_file}
9443 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9444 Specifies a file @var{config_file} that contains configuration pragmas. The
9445 file must be specified with full path.
9447 @item ^--GCC^/COMPILER^=@var{compiler_name}
9448 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9449 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9450 available on the path.
9452 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9453 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9454 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9455 available on the path.
9457 @item -d@var{x}
9458 @cindex @option{-d@var{x}} (@command{gnatelim})
9459 Activate internal debugging switches. @var{x} is a letter or digit, or
9460 string of letters or digits, which specifies the type of debugging
9461 mode desired.  Normally these are used only for internal development
9462 or system debugging purposes. You can find full documentation for these
9463 switches in the spec of the @code{Gnatelim} unit in the compiler
9464 source file @file{gnatelim.ads}.
9465 @end table
9467 @noindent
9468 @code{gnatelim} sends its output to the standard output stream, and all the
9469 tracing and debug information is sent to the standard error stream.
9470 In order to produce a proper GNAT configuration file
9471 @file{gnat.adc}, redirection must be used:
9473 @smallexample
9474 @ifset vms
9475 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9476 @end ifset
9477 @ifclear vms
9478 $ gnatelim main_prog.adb > gnat.adc
9479 @end ifclear
9480 @end smallexample
9482 @ifclear vms
9483 @noindent
9486 @smallexample
9487 $ gnatelim main_prog.adb >> gnat.adc
9488 @end smallexample
9490 @noindent
9491 in order to append the @code{gnatelim} output to the existing contents of
9492 @file{gnat.adc}.
9493 @end ifclear
9495 @node Correcting the List of Eliminate Pragmas
9496 @subsection Correcting the List of Eliminate Pragmas
9498 @noindent
9499 In some rare cases @code{gnatelim} may try to eliminate
9500 subprograms that are actually called in the program. In this case, the
9501 compiler will generate an error message of the form:
9503 @smallexample
9504 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9505 @end smallexample
9507 @noindent
9508 You will need to manually remove the wrong @code{Eliminate} pragmas from
9509 the @file{gnat.adc} file. You should recompile your program
9510 from scratch after that, because you need a consistent @file{gnat.adc} file
9511 during the entire compilation.
9514 @node Making Your Executables Smaller
9515 @subsection Making Your Executables Smaller
9517 @noindent
9518 In order to get a smaller executable for your program you now have to
9519 recompile the program completely with the new @file{gnat.adc} file
9520 created by @code{gnatelim} in your current directory:
9522 @smallexample
9523 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9524 @end smallexample
9526 @noindent
9527 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9528 recompile everything
9529 with the set of pragmas @code{Eliminate} that you have obtained with
9530 @command{gnatelim}).
9532 Be aware that the set of @code{Eliminate} pragmas is specific to each
9533 program. It is not recommended to merge sets of @code{Eliminate}
9534 pragmas created for different programs in one @file{gnat.adc} file.
9536 @node Summary of the gnatelim Usage Cycle
9537 @subsection Summary of the gnatelim Usage Cycle
9539 @noindent
9540 Here is a quick summary of the steps to be taken in order to reduce
9541 the size of your executables with @code{gnatelim}. You may use
9542 other GNAT options to control the optimization level,
9543 to produce the debugging information, to set search path, etc.
9545 @enumerate
9546 @item
9547 Produce a bind file
9549 @smallexample
9550 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9551 $ gnatbind main_prog
9552 @end smallexample
9554 @item
9555 Generate a list of @code{Eliminate} pragmas
9556 @smallexample
9557 @ifset vms
9558 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9559 @end ifset
9560 @ifclear vms
9561 $ gnatelim main_prog >[>] gnat.adc
9562 @end ifclear
9563 @end smallexample
9565 @item
9566 Recompile the application
9568 @smallexample
9569 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9570 @end smallexample
9572 @end enumerate
9577 @c ********************************
9578 @node Renaming Files Using gnatchop
9579 @chapter Renaming Files Using @code{gnatchop}
9580 @findex gnatchop
9582 @noindent
9583 This chapter discusses how to handle files with multiple units by using
9584 the @code{gnatchop} utility. This utility is also useful in renaming
9585 files to meet the standard GNAT default file naming conventions.
9587 @menu
9588 * Handling Files with Multiple Units::
9589 * Operating gnatchop in Compilation Mode::
9590 * Command Line for gnatchop::
9591 * Switches for gnatchop::
9592 * Examples of gnatchop Usage::
9593 @end menu
9595 @node Handling Files with Multiple Units
9596 @section Handling Files with Multiple Units
9598 @noindent
9599 The basic compilation model of GNAT requires that a file submitted to the
9600 compiler have only one unit and there be a strict correspondence
9601 between the file name and the unit name.
9603 The @code{gnatchop} utility allows both of these rules to be relaxed,
9604 allowing GNAT to process files which contain multiple compilation units
9605 and files with arbitrary file names. @code{gnatchop}
9606 reads the specified file and generates one or more output files,
9607 containing one unit per file. The unit and the file name correspond,
9608 as required by GNAT.
9610 If you want to permanently restructure a set of ``foreign'' files so that
9611 they match the GNAT rules, and do the remaining development using the
9612 GNAT structure, you can simply use @command{gnatchop} once, generate the
9613 new set of files and work with them from that point on.
9615 Alternatively, if you want to keep your files in the ``foreign'' format,
9616 perhaps to maintain compatibility with some other Ada compilation
9617 system, you can set up a procedure where you use @command{gnatchop} each
9618 time you compile, regarding the source files that it writes as temporary
9619 files that you throw away.
9622 @node Operating gnatchop in Compilation Mode
9623 @section Operating gnatchop in Compilation Mode
9625 @noindent
9626 The basic function of @code{gnatchop} is to take a file with multiple units
9627 and split it into separate files. The boundary between files is reasonably
9628 clear, except for the issue of comments and pragmas. In default mode, the
9629 rule is that any pragmas between units belong to the previous unit, except
9630 that configuration pragmas always belong to the following unit. Any comments
9631 belong to the following unit. These rules
9632 almost always result in the right choice of
9633 the split point without needing to mark it explicitly and most users will
9634 find this default to be what they want. In this default mode it is incorrect to
9635 submit a file containing only configuration pragmas, or one that ends in
9636 configuration pragmas, to @code{gnatchop}.
9638 However, using a special option to activate ``compilation mode'',
9639 @code{gnatchop}
9640 can perform another function, which is to provide exactly the semantics
9641 required by the RM for handling of configuration pragmas in a compilation.
9642 In the absence of configuration pragmas (at the main file level), this
9643 option has no effect, but it causes such configuration pragmas to be handled
9644 in a quite different manner.
9646 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9647 only configuration pragmas, then this file is appended to the
9648 @file{gnat.adc} file in the current directory. This behavior provides
9649 the required behavior described in the RM for the actions to be taken
9650 on submitting such a file to the compiler, namely that these pragmas
9651 should apply to all subsequent compilations in the same compilation
9652 environment. Using GNAT, the current directory, possibly containing a
9653 @file{gnat.adc} file is the representation
9654 of a compilation environment. For more information on the
9655 @file{gnat.adc} file, see the section on handling of configuration
9656 pragmas @pxref{Handling of Configuration Pragmas}.
9658 Second, in compilation mode, if @code{gnatchop}
9659 is given a file that starts with
9660 configuration pragmas, and contains one or more units, then these
9661 configuration pragmas are prepended to each of the chopped files. This
9662 behavior provides the required behavior described in the RM for the
9663 actions to be taken on compiling such a file, namely that the pragmas
9664 apply to all units in the compilation, but not to subsequently compiled
9665 units.
9667 Finally, if configuration pragmas appear between units, they are appended
9668 to the previous unit. This results in the previous unit being illegal,
9669 since the compiler does not accept configuration pragmas that follow
9670 a unit. This provides the required RM behavior that forbids configuration
9671 pragmas other than those preceding the first compilation unit of a
9672 compilation.
9674 For most purposes, @code{gnatchop} will be used in default mode. The
9675 compilation mode described above is used only if you need exactly
9676 accurate behavior with respect to compilations, and you have files
9677 that contain multiple units and configuration pragmas. In this
9678 circumstance the use of @code{gnatchop} with the compilation mode
9679 switch provides the required behavior, and is for example the mode
9680 in which GNAT processes the ACVC tests.
9682 @node Command Line for gnatchop
9683 @section Command Line for @code{gnatchop}
9685 @noindent
9686 The @code{gnatchop} command has the form:
9688 @smallexample
9689 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9690       [@var{directory}]
9691 @end smallexample
9693 @noindent
9694 The only required argument is the file name of the file to be chopped.
9695 There are no restrictions on the form of this file name. The file itself
9696 contains one or more Ada units, in normal GNAT format, concatenated
9697 together. As shown, more than one file may be presented to be chopped.
9699 When run in default mode, @code{gnatchop} generates one output file in
9700 the current directory for each unit in each of the files.
9702 @var{directory}, if specified, gives the name of the directory to which
9703 the output files will be written. If it is not specified, all files are
9704 written to the current directory.
9706 For example, given a
9707 file called @file{hellofiles} containing
9709 @smallexample @c ada
9710 @group
9711 @cartouche
9712 procedure hello;
9714 with Text_IO; use Text_IO;
9715 procedure hello is
9716 begin
9717    Put_Line ("Hello");
9718 end hello;
9719 @end cartouche
9720 @end group
9721 @end smallexample
9723 @noindent
9724 the command
9726 @smallexample
9727 $ gnatchop ^hellofiles^HELLOFILES.^
9728 @end smallexample
9730 @noindent
9731 generates two files in the current directory, one called
9732 @file{hello.ads} containing the single line that is the procedure spec,
9733 and the other called @file{hello.adb} containing the remaining text. The
9734 original file is not affected. The generated files can be compiled in
9735 the normal manner.
9737 @noindent
9738 When gnatchop is invoked on a file that is empty or that contains only empty
9739 lines and/or comments, gnatchop will not fail, but will not produce any
9740 new sources.
9742 For example, given a
9743 file called @file{toto.txt} containing
9745 @smallexample @c ada
9746 @group
9747 @cartouche
9748 --  Just a comment
9749 @end cartouche
9750 @end group
9751 @end smallexample
9753 @noindent
9754 the command
9756 @smallexample
9757 $ gnatchop ^toto.txt^TOT.TXT^
9758 @end smallexample
9760 @noindent
9761 will not produce any new file and will result in the following warnings:
9763 @smallexample
9764 toto.txt:1:01: warning: empty file, contains no compilation units
9765 no compilation units found
9766 no source files written
9767 @end smallexample
9769 @node Switches for gnatchop
9770 @section Switches for @code{gnatchop}
9772 @noindent
9773 @command{gnatchop} recognizes the following switches:
9775 @table @option
9776 @c !sort!
9778 @item ^-c^/COMPILATION^
9779 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9780 Causes @code{gnatchop} to operate in compilation mode, in which
9781 configuration pragmas are handled according to strict RM rules. See
9782 previous section for a full description of this mode.
9784 @ifclear vms
9785 @item -gnatxxx
9786 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9787 used to parse the given file. Not all @code{xxx} options make sense,
9788 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9789 process a source file that uses Latin-2 coding for identifiers.
9790 @end ifclear
9792 @item ^-h^/HELP^
9793 Causes @code{gnatchop} to generate a brief help summary to the standard
9794 output file showing usage information.
9796 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9797 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9798 Limit generated file names to the specified number @code{mm}
9799 of characters.
9800 This is useful if the
9801 resulting set of files is required to be interoperable with systems
9802 which limit the length of file names.
9803 @ifset vms
9804 If no value is given, or
9805 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9806 a default of 39, suitable for OpenVMS Alpha
9807 Systems, is assumed
9808 @end ifset
9809 @ifclear vms
9810 No space is allowed between the @option{-k} and the numeric value. The numeric
9811 value may be omitted in which case a default of @option{-k8},
9812 suitable for use
9813 with DOS-like file systems, is used. If no @option{-k} switch
9814 is present then
9815 there is no limit on the length of file names.
9816 @end ifclear
9818 @item ^-p^/PRESERVE^
9819 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9820 Causes the file ^modification^creation^ time stamp of the input file to be
9821 preserved and used for the time stamp of the output file(s). This may be
9822 useful for preserving coherency of time stamps in an environment where
9823 @code{gnatchop} is used as part of a standard build process.
9825 @item ^-q^/QUIET^
9826 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9827 Causes output of informational messages indicating the set of generated
9828 files to be suppressed. Warnings and error messages are unaffected.
9830 @item ^-r^/REFERENCE^
9831 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9832 @findex Source_Reference
9833 Generate @code{Source_Reference} pragmas. Use this switch if the output
9834 files are regarded as temporary and development is to be done in terms
9835 of the original unchopped file. This switch causes
9836 @code{Source_Reference} pragmas to be inserted into each of the
9837 generated files to refers back to the original file name and line number.
9838 The result is that all error messages refer back to the original
9839 unchopped file.
9840 In addition, the debugging information placed into the object file (when
9841 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9842 also refers back to this original file so that tools like profilers and
9843 debuggers will give information in terms of the original unchopped file.
9845 If the original file to be chopped itself contains
9846 a @code{Source_Reference}
9847 pragma referencing a third file, then gnatchop respects
9848 this pragma, and the generated @code{Source_Reference} pragmas
9849 in the chopped file refer to the original file, with appropriate
9850 line numbers. This is particularly useful when @code{gnatchop}
9851 is used in conjunction with @code{gnatprep} to compile files that
9852 contain preprocessing statements and multiple units.
9854 @item ^-v^/VERBOSE^
9855 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9856 Causes @code{gnatchop} to operate in verbose mode. The version
9857 number and copyright notice are output, as well as exact copies of
9858 the gnat1 commands spawned to obtain the chop control information.
9860 @item ^-w^/OVERWRITE^
9861 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9862 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9863 fatal error if there is already a file with the same name as a
9864 file it would otherwise output, in other words if the files to be
9865 chopped contain duplicated units. This switch bypasses this
9866 check, and causes all but the last instance of such duplicated
9867 units to be skipped.
9869 @ifclear vms
9870 @item --GCC=xxxx
9871 @cindex @option{--GCC=} (@code{gnatchop})
9872 Specify the path of the GNAT parser to be used. When this switch is used,
9873 no attempt is made to add the prefix to the GNAT parser executable.
9874 @end ifclear
9875 @end table
9877 @node Examples of gnatchop Usage
9878 @section Examples of @code{gnatchop} Usage
9880 @table @code
9881 @ifset vms
9882 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9883 @end ifset
9884 @ifclear vms
9885 @item gnatchop -w hello_s.ada prerelease/files
9886 @end ifclear
9888 Chops the source file @file{hello_s.ada}. The output files will be
9889 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9890 overwriting any
9891 files with matching names in that directory (no files in the current
9892 directory are modified).
9894 @item gnatchop ^archive^ARCHIVE.^
9895 Chops the source file @file{^archive^ARCHIVE.^}
9896 into the current directory. One
9897 useful application of @code{gnatchop} is in sending sets of sources
9898 around, for example in email messages. The required sources are simply
9899 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9900 command), and then
9901 @code{gnatchop} is used at the other end to reconstitute the original
9902 file names.
9904 @item gnatchop file1 file2 file3 direc
9905 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9906 the resulting files in the directory @file{direc}. Note that if any units
9907 occur more than once anywhere within this set of files, an error message
9908 is generated, and no files are written. To override this check, use the
9909 @option{^-w^/OVERWRITE^} switch,
9910 in which case the last occurrence in the last file will
9911 be the one that is output, and earlier duplicate occurrences for a given
9912 unit will be skipped.
9913 @end table
9915 @node Configuration Pragmas
9916 @chapter Configuration Pragmas
9917 @cindex Configuration pragmas
9918 @cindex Pragmas, configuration
9920 @noindent
9921 In Ada 95, configuration pragmas include those pragmas described as
9922 such in the Ada 95 Reference Manual, as well as
9923 implementation-dependent pragmas that are configuration pragmas. See the
9924 individual descriptions of pragmas in the GNAT Reference Manual for
9925 details on these additional GNAT-specific configuration pragmas. Most
9926 notably, the pragma @code{Source_File_Name}, which allows
9927 specifying non-default names for source files, is a configuration
9928 pragma. The following is a complete list of configuration pragmas
9929 recognized by @code{GNAT}:
9931 @smallexample
9932    Ada_83
9933    Ada_95
9934    C_Pass_By_Copy
9935    Component_Alignment
9936    Discard_Names
9937    Elaboration_Checks
9938    Eliminate
9939    Extend_System
9940    Extensions_Allowed
9941    External_Name_Casing
9942    Float_Representation
9943    Initialize_Scalars
9944    License
9945    Locking_Policy
9946    Long_Float
9947    Normalize_Scalars
9948    Polling
9949    Propagate_Exceptions
9950    Queuing_Policy
9951    Ravenscar
9952    Restricted_Run_Time
9953    Restrictions
9954    Reviewable
9955    Source_File_Name
9956    Style_Checks
9957    Suppress
9958    Task_Dispatching_Policy
9959    Universal_Data
9960    Unsuppress
9961    Use_VADS_Size
9962    Warnings
9963    Validity_Checks
9964 @end smallexample
9966 @menu
9967 * Handling of Configuration Pragmas::
9968 * The Configuration Pragmas Files::
9969 @end menu
9971 @node Handling of Configuration Pragmas
9972 @section Handling of Configuration Pragmas
9974 Configuration pragmas may either appear at the start of a compilation
9975 unit, in which case they apply only to that unit, or they may apply to
9976 all compilations performed in a given compilation environment.
9978 GNAT also provides the @code{gnatchop} utility to provide an automatic
9979 way to handle configuration pragmas following the semantics for
9980 compilations (that is, files with multiple units), described in the RM.
9981 See section @pxref{Operating gnatchop in Compilation Mode} for details.
9982 However, for most purposes, it will be more convenient to edit the
9983 @file{gnat.adc} file that contains configuration pragmas directly,
9984 as described in the following section.
9986 @node The Configuration Pragmas Files
9987 @section The Configuration Pragmas Files
9988 @cindex @file{gnat.adc}
9990 @noindent
9991 In GNAT a compilation environment is defined by the current
9992 directory at the time that a compile command is given. This current
9993 directory is searched for a file whose name is @file{gnat.adc}. If
9994 this file is present, it is expected to contain one or more
9995 configuration pragmas that will be applied to the current compilation.
9996 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
9997 considered.
9999 Configuration pragmas may be entered into the @file{gnat.adc} file
10000 either by running @code{gnatchop} on a source file that consists only of
10001 configuration pragmas, or more conveniently  by
10002 direct editing of the @file{gnat.adc} file, which is a standard format
10003 source file.
10005 In addition to @file{gnat.adc}, one additional file containing configuration
10006 pragmas may be applied to the current compilation using the switch
10007 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10008 contains only configuration pragmas. These configuration pragmas are
10009 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10010 is present and switch @option{-gnatA} is not used).
10012 It is allowed to specify several switches @option{-gnatec}, however only
10013 the last one on the command line will be taken into account.
10015 If you are using project file, a separate mechanism is provided using
10016 project attributes, see @ref{Specifying Configuration Pragmas} for more
10017 details.
10019 @ifset vms
10020 Of special interest to GNAT OpenVMS Alpha is the following
10021 configuration pragma:
10023 @smallexample @c ada
10024 @cartouche
10025 pragma Extend_System (Aux_DEC);
10026 @end cartouche
10027 @end smallexample
10029 @noindent
10030 In the presence of this pragma, GNAT adds to the definition of the
10031 predefined package SYSTEM all the additional types and subprograms that are
10032 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10033 @end ifset
10035 @node Handling Arbitrary File Naming Conventions Using gnatname
10036 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10037 @cindex Arbitrary File Naming Conventions
10039 @menu
10040 * Arbitrary File Naming Conventions::
10041 * Running gnatname::
10042 * Switches for gnatname::
10043 * Examples of gnatname Usage::
10044 @end menu
10046 @node Arbitrary File Naming Conventions
10047 @section Arbitrary File Naming Conventions
10049 @noindent
10050 The GNAT compiler must be able to know the source file name of a compilation
10051 unit.  When using the standard GNAT default file naming conventions
10052 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10053 does not need additional information.
10055 @noindent
10056 When the source file names do not follow the standard GNAT default file naming
10057 conventions, the GNAT compiler must be given additional information through
10058 a configuration pragmas file (see @ref{Configuration Pragmas})
10059 or a project file.
10060 When the non standard file naming conventions are well-defined,
10061 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10062 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10063 if the file naming conventions are irregular or arbitrary, a number
10064 of pragma @code{Source_File_Name} for individual compilation units
10065 must be defined.
10066 To help maintain the correspondence between compilation unit names and
10067 source file names within the compiler,
10068 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10069 set of files.
10071 @node Running gnatname
10072 @section Running @code{gnatname}
10074 @noindent
10075 The usual form of the @code{gnatname} command is
10077 @smallexample
10078 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10079 @end smallexample
10081 @noindent
10082 All of the arguments are optional. If invoked without any argument,
10083 @code{gnatname} will display its usage.
10085 @noindent
10086 When used with at least one naming pattern, @code{gnatname} will attempt to
10087 find all the compilation units in files that follow at least one of the
10088 naming patterns. To find these compilation units,
10089 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10090 regular files.
10092 @noindent
10093 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10094 Each Naming Pattern is enclosed between double quotes.
10095 A Naming Pattern is a regular expression similar to the wildcard patterns
10096 used in file names by the Unix shells or the DOS prompt.
10098 @noindent
10099 Examples of Naming Patterns are
10101 @smallexample
10102    "*.[12].ada"
10103    "*.ad[sb]*"
10104    "body_*"    "spec_*"
10105 @end smallexample
10107 @noindent
10108 For a more complete description of the syntax of Naming Patterns,
10109 see the second kind of regular expressions described in @file{g-regexp.ads}
10110 (the ``Glob'' regular expressions).
10112 @noindent
10113 When invoked with no switches, @code{gnatname} will create a configuration
10114 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10115 @code{Source_File_Name} for each file that contains a valid Ada unit.
10117 @node Switches for gnatname
10118 @section Switches for @code{gnatname}
10120 @noindent
10121 Switches for @code{gnatname} must precede any specified Naming Pattern.
10123 @noindent
10124 You may specify any of the following switches to @code{gnatname}:
10126 @table @option
10127 @c !sort!
10129 @item ^-c^/CONFIG_FILE=^@file{file}
10130 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10131 Create a configuration pragmas file @file{file} (instead of the default
10132 @file{gnat.adc}).
10133 @ifclear vms
10134 There may be zero, one or more space between @option{-c} and
10135 @file{file}.
10136 @end ifclear
10137 @file{file} may include directory information. @file{file} must be
10138 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10139 When a switch @option{^-c^/CONFIG_FILE^} is
10140 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10142 @item ^-d^/SOURCE_DIRS=^@file{dir}
10143 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10144 Look for source files in directory @file{dir}. There may be zero, one or more
10145 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10146 When a switch @option{^-d^/SOURCE_DIRS^}
10147 is specified, the current working directory will not be searched for source
10148 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10149 or @option{^-D^/DIR_FILES^} switch.
10150 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10151 If @file{dir} is a relative path, it is relative to the directory of
10152 the configuration pragmas file specified with switch
10153 @option{^-c^/CONFIG_FILE^},
10154 or to the directory of the project file specified with switch
10155 @option{^-P^/PROJECT_FILE^} or,
10156 if neither switch @option{^-c^/CONFIG_FILE^}
10157 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10158 current working directory. The directory
10159 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10161 @item ^-D^/DIRS_FILE=^@file{file}
10162 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10163 Look for source files in all directories listed in text file @file{file}.
10164 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10165 and @file{file}.
10166 @file{file} must be an existing, readable text file.
10167 Each non empty line in @file{file} must be a directory.
10168 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10169 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10170 @file{file}.
10172 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10173 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10174 Foreign patterns. Using this switch, it is possible to add sources of languages
10175 other than Ada to the list of sources of a project file.
10176 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10177 For example,
10178 @smallexample
10179 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10180 @end smallexample
10181 @noindent
10182 will look for Ada units in all files with the @file{.ada} extension,
10183 and will add to the list of file for project @file{prj.gpr} the C files
10184 with extension ".^c^C^".
10186 @item ^-h^/HELP^
10187 @cindex @option{^-h^/HELP^} (@code{gnatname})
10188 Output usage (help) information. The output is written to @file{stdout}.
10190 @item ^-P^/PROJECT_FILE=^@file{proj}
10191 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10192 Create or update project file @file{proj}. There may be zero, one or more space
10193 between @option{-P} and @file{proj}. @file{proj} may include directory
10194 information. @file{proj} must be writable.
10195 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10196 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10197 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10199 @item ^-v^/VERBOSE^
10200 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10201 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10202 This includes name of the file written, the name of the directories to search
10203 and, for each file in those directories whose name matches at least one of
10204 the Naming Patterns, an indication of whether the file contains a unit,
10205 and if so the name of the unit.
10207 @item ^-v -v^/VERBOSE /VERBOSE^
10208 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10209 Very Verbose mode. In addition to the output produced in verbose mode,
10210 for each file in the searched directories whose name matches none of
10211 the Naming Patterns, an indication is given that there is no match.
10213 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10214 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10215 Excluded patterns. Using this switch, it is possible to exclude some files
10216 that would match the name patterns. For example,
10217 @smallexample
10218 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10219 @end smallexample
10220 @noindent
10221 will look for Ada units in all files with the @file{.ada} extension,
10222 except those whose names end with @file{_nt.ada}.
10224 @end table
10226 @node Examples of gnatname Usage
10227 @section Examples of @code{gnatname} Usage
10229 @ifset vms
10230 @smallexample
10231 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10232 @end smallexample
10233 @end ifset
10235 @ifclear vms
10236 @smallexample
10237 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10238 @end smallexample
10239 @end ifclear
10241 @noindent
10242 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10243 and be writable. In addition, the directory
10244 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10245 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10247 @ifclear vms
10248 Note the optional spaces after @option{-c} and @option{-d}.
10249 @end ifclear
10251 @smallexample
10252 @ifclear vms
10253 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10254   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10255 @end ifclear
10256 @ifset vms
10257 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10258   /EXCLUDED_PATTERN=*_nt_body.ada
10259   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10260   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10261 @end ifset
10262 @end smallexample
10264 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10265 even in conjunction with one or several switches
10266 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10267 are used in this example.
10270 @c *****************************************
10271 @c * G N A T  P r o j e c t  M a n a g e r *
10272 @c *****************************************
10273 @node GNAT Project Manager
10274 @chapter GNAT Project Manager
10276 @menu
10277 * Introduction::
10278 * Examples of Project Files::
10279 * Project File Syntax::
10280 * Objects and Sources in Project Files::
10281 * Importing Projects::
10282 * Project Extension::
10283 * External References in Project Files::
10284 * Packages in Project Files::
10285 * Variables from Imported Projects::
10286 * Naming Schemes::
10287 * Library Projects::
10288 * Using Third-Party Libraries through Projects::
10289 * Stand-alone Library Projects::
10290 * Switches Related to Project Files::
10291 * Tools Supporting Project Files::
10292 * An Extended Example::
10293 * Project File Complete Syntax::
10294 @end menu
10296 @c ****************
10297 @c * Introduction *
10298 @c ****************
10300 @node Introduction
10301 @section Introduction
10303 @noindent
10304 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10305 you to manage complex builds involving a number of source files, directories,
10306 and compilation options for different system configurations. In particular,
10307 project files allow you to specify:
10308 @itemize @bullet
10309 @item
10310 The directory or set of directories containing the source files, and/or the
10311 names of the specific source files themselves
10312 @item
10313 The directory in which the compiler's output
10314 (@file{ALI} files, object files, tree files) is to be placed
10315 @item
10316 The directory in which the executable programs is to be placed
10317 @item
10318 ^Switch^Switch^ settings for any of the project-enabled tools
10319 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10320 @code{gnatfind}); you can apply these settings either globally or to individual
10321 compilation units.
10322 @item
10323 The source files containing the main subprogram(s) to be built
10324 @item
10325 The source programming language(s) (currently Ada and/or C)
10326 @item
10327 Source file naming conventions; you can specify these either globally or for
10328 individual compilation units
10329 @end itemize
10331 @menu
10332 * Project Files::
10333 @end menu
10335 @node Project Files
10336 @subsection Project Files
10338 @noindent
10339 Project files are written in a syntax close to that of Ada, using  familiar
10340 notions such as packages, context clauses, declarations, default values,
10341 assignments, and inheritance. Finally, project files can be built
10342 hierarchically from other project files, simplifying complex system
10343 integration and project reuse.
10345 A @dfn{project} is a specific set of values for various compilation properties.
10346 The settings for a given project are described by means of
10347 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10348 Property values in project files are either strings or lists of strings.
10349 Properties that are not explicitly set receive default values.  A project
10350 file may interrogate the values of @dfn{external variables} (user-defined
10351 command-line switches or environment variables), and it may specify property
10352 settings conditionally, based on the value of such variables.
10354 In simple cases, a project's source files depend only on other source files
10355 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10356 used in
10357 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10358 the Project Manager also allows more sophisticated arrangements,
10359 where the source files in one project depend on source files in other
10360 projects:
10361 @itemize @bullet
10362 @item
10363 One project can @emph{import} other projects containing needed source files.
10364 @item
10365 You can organize GNAT projects in a hierarchy: a @emph{child} project
10366 can extend a @emph{parent} project, inheriting the parent's source files and
10367 optionally overriding any of them with alternative versions
10368 @end itemize
10370 @noindent
10371 More generally, the Project Manager lets you structure large development
10372 efforts into hierarchical subsystems, where build decisions are delegated
10373 to the subsystem level, and thus different compilation environments
10374 (^switch^switch^ settings) used for different subsystems.
10376 The Project Manager is invoked through the
10377 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10378 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10379 @ifclear vms
10380 There may be zero, one or more spaces between @option{-P} and
10381 @option{@emph{projectfile}}.
10382 @end ifclear
10383 If you want to define (on the command line) an external variable that is
10384 queried by the project file, you must use the
10385 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10386 The Project Manager parses and interprets the project file, and drives the
10387 invoked tool based on the project settings.
10389 The Project Manager supports a wide range of development strategies,
10390 for systems of all sizes.  Here are some typical practices that are
10391 easily handled:
10392 @itemize @bullet
10393 @item
10394 Using a common set of source files, but generating object files in different
10395 directories via different ^switch^switch^ settings
10396 @item
10397 Using a mostly-shared set of source files, but with different versions of
10398 some unit or units
10399 @end itemize
10401 @noindent
10402 The destination of an executable can be controlled inside a project file
10403 using the @option{^-o^-o^}
10404 ^switch^switch^.
10405 In the absence of such a ^switch^switch^ either inside
10406 the project file or on the command line, any executable files generated by
10407 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10408 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10409 in the object directory of the project.
10411 You can use project files to achieve some of the effects of a source
10412 versioning system (for example, defining separate projects for
10413 the different sets of sources that comprise different releases) but the
10414 Project Manager is independent of any source configuration management tools
10415 that might be used by the developers.
10417 The next section introduces the main features of GNAT's project facility
10418 through a sequence of examples; subsequent sections will present the syntax
10419 and semantics in more detail. A more formal description of the project
10420 facility appears in the GNAT Reference Manual.
10422 @c *****************************
10423 @c * Examples of Project Files *
10424 @c *****************************
10426 @node Examples of Project Files
10427 @section Examples of Project Files
10428 @noindent
10429 This section illustrates some of the typical uses of project files and
10430 explains their basic structure and behavior.
10432 @menu
10433 * Common Sources with Different ^Switches^Switches^ and Directories::
10434 * Using External Variables::
10435 * Importing Other Projects::
10436 * Extending a Project::
10437 @end menu
10439 @node Common Sources with Different ^Switches^Switches^ and Directories
10440 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10442 @menu
10443 * Source Files::
10444 * Specifying the Object Directory::
10445 * Specifying the Exec Directory::
10446 * Project File Packages::
10447 * Specifying ^Switch^Switch^ Settings::
10448 * Main Subprograms::
10449 * Executable File Names::
10450 * Source File Naming Conventions::
10451 * Source Language(s)::
10452 @end menu
10454 @noindent
10455 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10456 @file{proc.adb} are in the @file{/common} directory.  The file
10457 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10458 package @code{Pack}.  We want to compile these source files under two sets
10459 of ^switches^switches^:
10460 @itemize @bullet
10461 @item
10462 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10463 and the @option{^-gnata^-gnata^},
10464 @option{^-gnato^-gnato^},
10465 and @option{^-gnatE^-gnatE^} switches to the
10466 compiler; the compiler's output is to appear in @file{/common/debug}
10467 @item
10468 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10469 to the compiler; the compiler's output is to appear in @file{/common/release}
10470 @end itemize
10472 @noindent
10473 The GNAT project files shown below, respectively @file{debug.gpr} and
10474 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10476 Schematically:
10477 @smallexample
10478 @group
10479 ^/common^[COMMON]^
10480   debug.gpr
10481   release.gpr
10482   pack.ads
10483   pack.adb
10484   proc.adb
10485 @end group
10486 @group
10487 ^/common/debug^[COMMON.DEBUG]^
10488   proc.ali, proc.o
10489   pack.ali, pack.o
10490 @end group
10491 @group
10492 ^/common/release^[COMMON.RELEASE]^
10493   proc.ali, proc.o
10494   pack.ali, pack.o
10495 @end group
10496 @end smallexample
10497 Here are the corresponding project files:
10499 @smallexample @c projectfile
10500 @group
10501 project Debug is
10502   for Object_Dir use "debug";
10503   for Main use ("proc");
10505   package Builder is
10506     for ^Default_Switches^Default_Switches^ ("Ada")
10507         use ("^-g^-g^");
10508     for Executable ("proc.adb") use "proc1";
10509   end Builder;
10510 @end group
10512 @group
10513   package Compiler is
10514     for ^Default_Switches^Default_Switches^ ("Ada")
10515        use ("-fstack-check",
10516             "^-gnata^-gnata^",
10517             "^-gnato^-gnato^",
10518             "^-gnatE^-gnatE^");
10519   end Compiler;
10520 end Debug;
10521 @end group
10522 @end smallexample
10524 @smallexample @c projectfile
10525 @group
10526 project Release is
10527   for Object_Dir use "release";
10528   for Exec_Dir use ".";
10529   for Main use ("proc");
10531   package Compiler is
10532     for ^Default_Switches^Default_Switches^ ("Ada")
10533         use ("^-O2^-O2^");
10534   end Compiler;
10535 end Release;
10536 @end group
10537 @end smallexample
10539 @noindent
10540 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10541 insensitive), and analogously the project defined by @file{release.gpr} is
10542 @code{"Release"}.  For consistency the file should have the same name as the
10543 project, and the project file's extension should be @code{"gpr"}. These
10544 conventions are not required, but a warning is issued if they are not followed.
10546 If the current directory is @file{^/temp^[TEMP]^}, then the command
10547 @smallexample
10548 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10549 @end smallexample
10551 @noindent
10552 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10553 as well as the @code{^proc1^PROC1.EXE^} executable,
10554 using the ^switch^switch^ settings defined in the project file.
10556 Likewise, the command
10557 @smallexample
10558 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10559 @end smallexample
10561 @noindent
10562 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10563 and the @code{^proc^PROC.EXE^}
10564 executable in @file{^/common^[COMMON]^},
10565 using the ^switch^switch^ settings from the project file.
10567 @node Source Files
10568 @unnumberedsubsubsec Source Files
10570 @noindent
10571 If a project file does not explicitly specify a set of source directories or
10572 a set of source files, then by default the project's source files are the
10573 Ada source files in the project file directory.  Thus @file{pack.ads},
10574 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10576 @node Specifying the Object Directory
10577 @unnumberedsubsubsec Specifying the Object Directory
10579 @noindent
10580 Several project properties are modeled by Ada-style @emph{attributes};
10581 a property is defined by supplying the equivalent of an Ada attribute
10582 definition clause in the project file.
10583 A project's object directory is another such a property; the corresponding
10584 attribute is @code{Object_Dir}, and its value is also a string expression,
10585 specified either as absolute or relative. In the later case,
10586 it is relative to the project file directory. Thus the compiler's
10587 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10588 (for the @code{Debug} project)
10589 and to @file{^/common/release^[COMMON.RELEASE]^}
10590 (for the @code{Release} project).
10591 If @code{Object_Dir} is not specified, then the default is the project file
10592 directory itself.
10594 @node Specifying the Exec Directory
10595 @unnumberedsubsubsec Specifying the Exec Directory
10597 @noindent
10598 A project's exec directory is another property; the corresponding
10599 attribute is @code{Exec_Dir}, and its value is also a string expression,
10600 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10601 then the default is the object directory (which may also be the project file
10602 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10603 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10604 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10605 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10607 @node Project File Packages
10608 @unnumberedsubsubsec Project File Packages
10610 @noindent
10611 A GNAT tool that is integrated with the Project Manager is modeled by a
10612 corresponding package in the project file. In the example above,
10613 The @code{Debug} project defines the packages @code{Builder}
10614 (for @command{gnatmake}) and @code{Compiler};
10615 the @code{Release} project defines only the @code{Compiler} package.
10617 The Ada-like package syntax is not to be taken literally.  Although packages in
10618 project files bear a surface resemblance to packages in Ada source code, the
10619 notation is simply a way to convey a grouping of properties for a named
10620 entity.  Indeed, the package names permitted in project files are restricted
10621 to a predefined set, corresponding to the project-aware tools, and the contents
10622 of packages are limited to a small set of constructs.
10623 The packages in the example above contain attribute definitions.
10625 @node Specifying ^Switch^Switch^ Settings
10626 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10628 @noindent
10629 ^Switch^Switch^ settings for a project-aware tool can be specified through
10630 attributes in the package that corresponds to the tool.
10631 The example above illustrates one of the relevant attributes,
10632 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10633 in both project files.
10634 Unlike simple attributes like @code{Source_Dirs},
10635 @code{^Default_Switches^Default_Switches^} is
10636 known as an @emph{associative array}.  When you define this attribute, you must
10637 supply an ``index'' (a literal string), and the effect of the attribute
10638 definition is to set the value of the array at the specified index.
10639 For the @code{^Default_Switches^Default_Switches^} attribute,
10640 the index is a programming language (in our case, Ada),
10641 and the value specified (after @code{use}) must be a list
10642 of string expressions.
10644 The attributes permitted in project files are restricted to a predefined set.
10645 Some may appear at project level, others in packages.
10646 For any attribute that is an associative array, the index must always be a
10647 literal string, but the restrictions on this string (e.g., a file name or a
10648 language name) depend on the individual attribute.
10649 Also depending on the attribute, its specified value will need to be either a
10650 string or a string list.
10652 In the @code{Debug} project, we set the switches for two tools,
10653 @command{gnatmake} and the compiler, and thus we include the two corresponding
10654 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10655 attribute with index @code{"Ada"}.
10656 Note that the package corresponding to
10657 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10658 similar, but only includes the @code{Compiler} package.
10660 In project @code{Debug} above, the ^switches^switches^ starting with
10661 @option{-gnat} that are specified in package @code{Compiler}
10662 could have been placed in package @code{Builder}, since @command{gnatmake}
10663 transmits all such ^switches^switches^ to the compiler.
10665 @node Main Subprograms
10666 @unnumberedsubsubsec Main Subprograms
10668 @noindent
10669 One of the specifiable properties of a project is a list of files that contain
10670 main subprograms.  This property is captured in the @code{Main} attribute,
10671 whose value is a list of strings.  If a project defines the @code{Main}
10672 attribute, it is not necessary to identify the main subprogram(s) when
10673 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10675 @node Executable File Names
10676 @unnumberedsubsubsec Executable File Names
10678 @noindent
10679 By default, the executable file name corresponding to a main source is
10680 deducted from the main source file name. Through the attributes
10681 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10682 it is possible to change this default.
10683 In project @code{Debug} above, the executable file name
10684 for main source @file{^proc.adb^PROC.ADB^} is
10685 @file{^proc1^PROC1.EXE^}.
10686 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10687 of the the executable files, when no attribute @code{Executable} applies:
10688 its value replace the platform-specific executable suffix.
10689 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10690 specify a non default executable file name when several mains are built at once
10691 in a single @command{gnatmake} command.
10693 @node Source File Naming Conventions
10694 @unnumberedsubsubsec Source File Naming Conventions
10696 @noindent
10697 Since the project files above do not specify any source file naming
10698 conventions, the GNAT defaults are used.  The mechanism for defining source
10699 file naming conventions -- a package named @code{Naming} --
10700 is described below (@pxref{Naming Schemes}).
10702 @node Source Language(s)
10703 @unnumberedsubsubsec Source Language(s)
10705 @noindent
10706 Since the project files do not specify a @code{Languages} attribute, by
10707 default the GNAT tools assume that the language of the project file is Ada.
10708 More generally, a project can comprise source files
10709 in Ada, C, and/or other languages.
10711 @node Using External Variables
10712 @subsection Using External Variables
10714 @noindent
10715 Instead of supplying different project files for debug and release, we can
10716 define a single project file that queries an external variable (set either
10717 on the command line or via an ^environment variable^logical name^) in order to
10718 conditionally define the appropriate settings.  Again, assume that the
10719 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10720 located in directory @file{^/common^[COMMON]^}.  The following project file,
10721 @file{build.gpr}, queries the external variable named @code{STYLE} and
10722 defines an object directory and ^switch^switch^ settings based on whether
10723 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10724 the default is @code{"deb"}.
10726 @smallexample @c projectfile
10727 @group
10728 project Build is
10729   for Main use ("proc");
10731   type Style_Type is ("deb", "rel");
10732   Style : Style_Type := external ("STYLE", "deb");
10734   case Style is
10735     when "deb" =>
10736       for Object_Dir use "debug";
10738     when "rel" =>
10739       for Object_Dir use "release";
10740       for Exec_Dir use ".";
10741   end case;
10742 @end group
10744 @group
10745   package Builder is
10747     case Style is
10748       when "deb" =>
10749         for ^Default_Switches^Default_Switches^ ("Ada")
10750             use ("^-g^-g^");
10751         for Executable ("proc") use "proc1";
10752     end case;
10754   end Builder;
10755 @end group
10757 @group
10758   package Compiler is
10760     case Style is
10761       when "deb" =>
10762         for ^Default_Switches^Default_Switches^ ("Ada")
10763             use ("^-gnata^-gnata^",
10764                  "^-gnato^-gnato^",
10765                  "^-gnatE^-gnatE^");
10767       when "rel" =>
10768         for ^Default_Switches^Default_Switches^ ("Ada")
10769             use ("^-O2^-O2^");
10770     end case;
10772   end Compiler;
10774 end Build;
10775 @end group
10776 @end smallexample
10778 @noindent
10779 @code{Style_Type} is an example of a @emph{string type}, which is the project
10780 file analog of an Ada enumeration type but whose components are string literals
10781 rather than identifiers.  @code{Style} is declared as a variable of this type.
10783 The form @code{external("STYLE", "deb")} is known as an
10784 @emph{external reference}; its first argument is the name of an
10785 @emph{external variable}, and the second argument is a default value to be
10786 used if the external variable doesn't exist.  You can define an external
10787 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10788 or you can use ^an environment variable^a logical name^
10789 as an external variable.
10791 Each @code{case} construct is expanded by the Project Manager based on the
10792 value of @code{Style}. Thus the command
10793 @ifclear vms
10794 @smallexample
10795 gnatmake -P/common/build.gpr -XSTYLE=deb
10796 @end smallexample
10797 @end ifclear
10799 @ifset vms
10800 @smallexample
10801 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10802 @end smallexample
10803 @end ifset
10805 @noindent
10806 is equivalent to the @command{gnatmake} invocation using the project file
10807 @file{debug.gpr} in the earlier example.  So is the command
10808 @smallexample
10809 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10810 @end smallexample
10812 @noindent
10813 since @code{"deb"} is the default for @code{STYLE}.
10815 Analogously,
10817 @ifclear vms
10818 @smallexample
10819 gnatmake -P/common/build.gpr -XSTYLE=rel
10820 @end smallexample
10821 @end ifclear
10823 @ifset vms
10824 @smallexample
10825 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10826 @end smallexample
10827 @end ifset
10829 @noindent
10830 is equivalent to the @command{gnatmake} invocation using the project file
10831 @file{release.gpr} in the earlier example.
10833 @node Importing Other Projects
10834 @subsection Importing Other Projects
10836 @noindent
10837 A compilation unit in a source file in one project may depend on compilation
10838 units in source files in other projects.  To compile this unit under
10839 control of a project file, the
10840 dependent project must @emph{import} the projects containing the needed source
10841 files.
10842 This effect is obtained using syntax similar to an Ada @code{with} clause,
10843 but where @code{with}ed entities are strings that denote project files.
10845 As an example, suppose that the two projects @code{GUI_Proj} and
10846 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10847 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10848 and @file{^/comm^[COMM]^}, respectively.
10849 Suppose that the source files for @code{GUI_Proj} are
10850 @file{gui.ads} and @file{gui.adb}, and that the source files for
10851 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10852 files is located in its respective project file directory.  Schematically:
10854 @smallexample
10855 @group
10856 ^/gui^[GUI]^
10857   gui_proj.gpr
10858   gui.ads
10859   gui.adb
10860 @end group
10862 @group
10863 ^/comm^[COMM]^
10864   comm_proj.gpr
10865   comm.ads
10866   comm.adb
10867 @end group
10868 @end smallexample
10870 @noindent
10871 We want to develop an application in directory @file{^/app^[APP]^} that
10872 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10873 the corresponding project files (e.g. the ^switch^switch^ settings
10874 and object directory).
10875 Skeletal code for a main procedure might be something like the following:
10877 @smallexample @c ada
10878 @group
10879 with GUI, Comm;
10880 procedure App_Main is
10881    ...
10882 begin
10883    ...
10884 end App_Main;
10885 @end group
10886 @end smallexample
10888 @noindent
10889 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10890 effect:
10892 @smallexample @c projectfile
10893 @group
10894 with "/gui/gui_proj", "/comm/comm_proj";
10895 project App_Proj is
10896    for Main use ("app_main");
10897 end App_Proj;
10898 @end group
10899 @end smallexample
10901 @noindent
10902 Building an executable is achieved through the command:
10903 @smallexample
10904 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10905 @end smallexample
10906 @noindent
10907 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10908 in the directory where @file{app_proj.gpr} resides.
10910 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10911 (as illustrated above) the @code{with} clause can omit the extension.
10913 Our example specified an absolute path for each imported project file.
10914 Alternatively, the directory name of an imported object can be omitted
10915 if either
10916 @itemize @bullet
10917 @item
10918 The imported project file is in the same directory as the importing project
10919 file, or
10920 @item
10921 You have defined ^an environment variable^a logical name^
10922 that includes the directory containing
10923 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10924 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10925 directory names separated by colons (semicolons on Windows).
10926 @end itemize
10928 @noindent
10929 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10930 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10931 as follows:
10933 @smallexample @c projectfile
10934 @group
10935 with "gui_proj", "comm_proj";
10936 project App_Proj is
10937    for Main use ("app_main");
10938 end App_Proj;
10939 @end group
10940 @end smallexample
10942 @noindent
10943 Importing other projects can create ambiguities.
10944 For example, the same unit might be present in different imported projects, or
10945 it might be present in both the importing project and in an imported project.
10946 Both of these conditions are errors.  Note that in the current version of
10947 the Project Manager, it is illegal to have an ambiguous unit even if the
10948 unit is never referenced by the importing project.  This restriction may be
10949 relaxed in a future release.
10951 @node Extending a Project
10952 @subsection Extending a Project
10954 @noindent
10955 In large software systems it is common to have multiple
10956 implementations of a common interface; in Ada terms, multiple versions of a
10957 package body for the same specification.  For example, one implementation
10958 might be safe for use in tasking programs, while another might only be used
10959 in sequential applications.  This can be modeled in GNAT using the concept
10960 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
10961 another project (the ``parent'') then by default all source files of the
10962 parent project are inherited by the child, but the child project can
10963 override any of the parent's source files with new versions, and can also
10964 add new files.  This facility is the project analog of a type extension in
10965 Object-Oriented Programming.  Project hierarchies are permitted (a child
10966 project may be the parent of yet another project), and a project that
10967 inherits one project can also import other projects.
10969 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
10970 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
10971 @file{pack.adb}, and @file{proc.adb}:
10973 @smallexample
10974 @group
10975 ^/seq^[SEQ]^
10976   pack.ads
10977   pack.adb
10978   proc.adb
10979   seq_proj.gpr
10980 @end group
10981 @end smallexample
10983 @noindent
10984 Note that the project file can simply be empty (that is, no attribute or
10985 package is defined):
10987 @smallexample @c projectfile
10988 @group
10989 project Seq_Proj is
10990 end Seq_Proj;
10991 @end group
10992 @end smallexample
10994 @noindent
10995 implying that its source files are all the Ada source files in the project
10996 directory.
10998 Suppose we want to supply an alternate version of @file{pack.adb}, in
10999 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11000 @file{pack.ads} and @file{proc.adb}.  We can define a project
11001 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11003 @smallexample
11004 @group
11005 ^/tasking^[TASKING]^
11006   pack.adb
11007   tasking_proj.gpr
11008 @end group
11010 @group
11011 project Tasking_Proj extends "/seq/seq_proj" is
11012 end Tasking_Proj;
11013 @end group
11014 @end smallexample
11016 @noindent
11017 The version of @file{pack.adb} used in a build depends on which project file
11018 is specified.
11020 Note that we could have obtained the desired behavior using project import
11021 rather than project inheritance; a @code{base} project would contain the
11022 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11023 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11024 would import @code{base} and add a different version of @file{pack.adb}.  The
11025 choice depends on whether other sources in the original project need to be
11026 overridden.  If they do, then project extension is necessary, otherwise,
11027 importing is sufficient.
11029 @noindent
11030 In a project file that extends another project file, it is possible to
11031 indicate that an inherited source is not part of the sources of the extending
11032 project. This is necessary sometimes when a package spec has been overloaded
11033 and no longer requires a body: in this case, it is necessary to indicate that
11034 the inherited body is not part of the sources of the project, otherwise there
11035 will be a compilation error when compiling the spec.
11037 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11038 Its value is a string list: a list of file names.
11040 @smallexample @c @projectfile
11041 project B extends "a" is
11042    for Source_Files use ("pkg.ads");
11043    --  New spec of Pkg does not need a completion
11044    for Locally_Removed_Files use ("pkg.adb");
11045 end B;
11046 @end smallexample
11048 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11049 is still needed: if it is possible to build using @code{gnatmake} when such
11050 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11051 it is possible to remove the source completely from a system that includes
11052 project P.
11054 @c ***********************
11055 @c * Project File Syntax *
11056 @c ***********************
11058 @node Project File Syntax
11059 @section Project File Syntax
11061 @menu
11062 * Basic Syntax::
11063 * Packages::
11064 * Expressions::
11065 * String Types::
11066 * Variables::
11067 * Attributes::
11068 * Associative Array Attributes::
11069 * case Constructions::
11070 @end menu
11072 @noindent
11073 This section describes the structure of project files.
11075 A project may be an @emph{independent project}, entirely defined by a single
11076 project file. Any Ada source file in an independent project depends only
11077 on the predefined library and other Ada source files in the same project.
11079 @noindent
11080 A project may also @dfn{depend on} other projects, in either or both of
11081 the following ways:
11082 @itemize @bullet
11083 @item It may import any number of projects
11084 @item It may extend at most one other project
11085 @end itemize
11087 @noindent
11088 The dependence relation is a directed acyclic graph (the subgraph reflecting
11089 the ``extends'' relation is a tree).
11091 A project's @dfn{immediate sources} are the source files directly defined by
11092 that project, either implicitly by residing in the project file's directory,
11093 or explicitly through any of the source-related attributes described below.
11094 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11095 of @var{proj} together with the immediate sources (unless overridden) of any
11096 project on which @var{proj} depends (either directly or indirectly).
11098 @node Basic Syntax
11099 @subsection Basic Syntax
11101 @noindent
11102 As seen in the earlier examples, project files have an Ada-like syntax.
11103 The minimal project file is:
11104 @smallexample @c projectfile
11105 @group
11106 project Empty is
11108 end Empty;
11109 @end group
11110 @end smallexample
11112 @noindent
11113 The identifier @code{Empty} is the name of the project.
11114 This project name must be present after the reserved
11115 word @code{end} at the end of the project file, followed by a semi-colon.
11117 Any name in a project file, such as the project name or a variable name,
11118 has the same syntax as an Ada identifier.
11120 The reserved words of project files are the Ada reserved words plus
11121 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11122 reserved words currently used in project file syntax are:
11124 @itemize @bullet
11125 @item
11126 @code{case}
11127 @item
11128 @code{end}
11129 @item
11130 @code{for}
11131 @item
11132 @code{is}
11133 @item
11134 @code{others}
11135 @item
11136 @code{package}
11137 @item
11138 @code{renames}
11139 @item
11140 @code{type}
11141 @item
11142 @code{use}
11143 @item
11144 @code{when}
11145 @item
11146 @code{with}
11147 @end itemize
11149 @noindent
11150 Comments in project files have the same syntax as in Ada, two consecutives
11151 hyphens through the end of the line.
11153 @node Packages
11154 @subsection Packages
11156 @noindent
11157 A project file may contain @emph{packages}. The name of a package must be one
11158 of the identifiers from the following list. A package
11159 with a given name may only appear once in a project file. Package names are
11160 case insensitive. The following package names are legal:
11162 @itemize @bullet
11163 @item
11164 @code{Naming}
11165 @item
11166 @code{Builder}
11167 @item
11168 @code{Compiler}
11169 @item
11170 @code{Binder}
11171 @item
11172 @code{Linker}
11173 @item
11174 @code{Finder}
11175 @item
11176 @code{Cross_Reference}
11177 @item
11178 @code{Eliminate}
11179 @item
11180 @code{gnatls}
11181 @item
11182 @code{gnatstub}
11183 @item
11184 @code{IDE}
11185 @end itemize
11187 @noindent
11188 In its simplest form, a package may be empty:
11190 @smallexample @c projectfile
11191 @group
11192 project Simple is
11193   package Builder is
11194   end Builder;
11195 end Simple;
11196 @end group
11197 @end smallexample
11199 @noindent
11200 A package may contain @emph{attribute declarations},
11201 @emph{variable declarations} and @emph{case constructions}, as will be
11202 described below.
11204 When there is ambiguity between a project name and a package name,
11205 the name always designates the project. To avoid possible confusion, it is
11206 always a good idea to avoid naming a project with one of the
11207 names allowed for packages or any name that starts with @code{gnat}.
11209 @node Expressions
11210 @subsection Expressions
11212 @noindent
11213 An @emph{expression} is either a @emph{string expression} or a
11214 @emph{string list expression}.
11216 A @emph{string expression} is either a @emph{simple string expression} or a
11217 @emph{compound string expression}.
11219 A @emph{simple string expression} is one of the following:
11220 @itemize @bullet
11221 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11222 @item A string-valued variable reference (see @ref{Variables})
11223 @item A string-valued attribute reference (see @ref{Attributes})
11224 @item An external reference (see @ref{External References in Project Files})
11225 @end itemize
11227 @noindent
11228 A @emph{compound string expression} is a concatenation of string expressions,
11229 using the operator @code{"&"}
11230 @smallexample
11231        Path & "/" & File_Name & ".ads"
11232 @end smallexample
11234 @noindent
11235 A @emph{string list expression} is either a
11236 @emph{simple string list expression} or a
11237 @emph{compound string list expression}.
11239 A @emph{simple string list expression} is one of the following:
11240 @itemize @bullet
11241 @item A parenthesized list of zero or more string expressions,
11242 separated by commas
11243 @smallexample
11244    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11245    Empty_List := ();
11246 @end smallexample
11247 @item A string list-valued variable reference
11248 @item A string list-valued attribute reference
11249 @end itemize
11251 @noindent
11252 A @emph{compound string list expression} is the concatenation (using
11253 @code{"&"}) of a simple string list expression and an expression.  Note that
11254 each term in a compound string list expression, except the first, may be
11255 either a string expression or a string list expression.
11257 @smallexample @c projectfile
11258 @group
11259    File_Name_List := () & File_Name; --  One string in this list
11260    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11261    --  Two strings
11262    Big_List := File_Name_List & Extended_File_Name_List;
11263    --  Concatenation of two string lists: three strings
11264    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11265    --  Illegal: must start with a string list
11266 @end group
11267 @end smallexample
11269 @node String Types
11270 @subsection String Types
11272 @noindent
11273 A @emph{string type declaration} introduces a discrete set of string literals.
11274 If a string variable is declared to have this type, its value
11275 is restricted to the given set of literals.
11277 Here is an example of a string type declaration:
11279 @smallexample @c projectfile
11280    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11281 @end smallexample
11283 @noindent
11284 Variables of a string type are called @emph{typed variables}; all other
11285 variables are called @emph{untyped variables}. Typed variables are
11286 particularly useful in @code{case} constructions, to support conditional
11287 attribute declarations.
11288 (see @ref{case Constructions}).
11290 The string literals in the list are case sensitive and must all be different.
11291 They may include any graphic characters allowed in Ada, including spaces.
11293 A string type may only be declared at the project level, not inside a package.
11295 A string type may be referenced by its name if it has been declared in the same
11296 project file, or by an expanded name whose prefix is the name of the project
11297 in which it is declared.
11299 @node Variables
11300 @subsection Variables
11302 @noindent
11303 A variable may be declared at the project file level, or within a package.
11304 Here are some examples of variable declarations:
11306 @smallexample @c projectfile
11307 @group
11308    This_OS : OS := external ("OS"); --  a typed variable declaration
11309    That_OS := "GNU/Linux";          --  an untyped variable declaration
11310 @end group
11311 @end smallexample
11313 @noindent
11314 The syntax of a @emph{typed variable declaration} is identical to the Ada
11315 syntax for an object declaration. By contrast, the syntax of an untyped
11316 variable declaration is identical to an Ada assignment statement. In fact,
11317 variable declarations in project files have some of the characteristics of
11318 an assignment, in that successive declarations for the same variable are
11319 allowed. Untyped variable declarations do establish the expected kind of the
11320 variable (string or string list), and successive declarations for it must
11321 respect the initial kind.
11323 @noindent
11324 A string variable declaration (typed or untyped) declares a variable
11325 whose value is a string. This variable may be used as a string expression.
11326 @smallexample @c projectfile
11327    File_Name       := "readme.txt";
11328    Saved_File_Name := File_Name & ".saved";
11329 @end smallexample
11331 @noindent
11332 A string list variable declaration declares a variable whose value is a list
11333 of strings. The list may contain any number (zero or more) of strings.
11335 @smallexample @c projectfile
11336    Empty_List := ();
11337    List_With_One_Element := ("^-gnaty^-gnaty^");
11338    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11339    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11340                  "pack2.ada", "util_.ada", "util.ada");
11341 @end smallexample
11343 @noindent
11344 The same typed variable may not be declared more than once at project level,
11345 and it may not be declared more than once in any package; it is in effect
11346 a constant.
11348 The same untyped variable may be declared several times. Declarations are
11349 elaborated in the order in which they appear, so  the new value replaces
11350 the old one, and any subsequent reference to the variable uses the new value.
11351 However, as noted above, if a variable has been declared as a string, all
11352 subsequent
11353 declarations must give it a string value. Similarly, if a variable has
11354 been declared as a string list, all subsequent declarations
11355 must give it a string list value.
11357 A @emph{variable reference} may take several forms:
11359 @itemize @bullet
11360 @item The simple variable name, for a variable in the current package (if any)
11361 or in the current project
11362 @item An expanded name, whose prefix is a context name.
11363 @end itemize
11365 @noindent
11366 A @emph{context} may be one of the following:
11368 @itemize @bullet
11369 @item The name of an existing package in the current project
11370 @item The name of an imported project of the current project
11371 @item The name of an ancestor project (i.e., a project extended by the current
11372 project, either directly or indirectly)
11373 @item An expanded name whose prefix is an imported/parent project name, and
11374 whose selector is a package name in that project.
11375 @end itemize
11377 @noindent
11378 A variable reference may be used in an expression.
11380 @node Attributes
11381 @subsection Attributes
11383 @noindent
11384 A project (and its packages) may have @emph{attributes} that define
11385 the project's properties.  Some attributes have values that are strings;
11386 others have values that are string lists.
11388 There are two categories of attributes: @emph{simple attributes}
11389 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11391 Legal project attribute names, and attribute names for each legal package are
11392 listed below. Attributes names are case-insensitive.
11394 The following attributes are defined on projects (all are simple attributes):
11396 @multitable @columnfractions .4 .3
11397 @item @emph{Attribute Name}
11398 @tab @emph{Value}
11399 @item @code{Source_Files}
11400 @tab string list
11401 @item @code{Source_Dirs}
11402 @tab string list
11403 @item @code{Source_List_File}
11404 @tab string
11405 @item @code{Object_Dir}
11406 @tab string
11407 @item @code{Exec_Dir}
11408 @tab string
11409 @item @code{Locally_Removed_Files}
11410 @tab string list
11411 @item @code{Main}
11412 @tab string list
11413 @item @code{Languages}
11414 @tab string list
11415 @item @code{Main_Language}
11416 @tab string
11417 @item @code{Library_Dir}
11418 @tab string
11419 @item @code{Library_Name}
11420 @tab string
11421 @item @code{Library_Kind}
11422 @tab string
11423 @item @code{Library_Version}
11424 @tab string
11425 @item @code{Library_Interface}
11426 @tab string
11427 @item @code{Library_Auto_Init}
11428 @tab string
11429 @item @code{Library_Options}
11430 @tab string list
11431 @item @code{Library_GCC}
11432 @tab string
11433 @end multitable
11435 @noindent
11436 The following attributes are defined for package  @code{Naming}
11437 (see @ref{Naming Schemes}):
11439 @multitable @columnfractions .4 .2 .2 .2
11440 @item Attribute Name @tab Category @tab Index @tab Value
11441 @item @code{Spec_Suffix}
11442 @tab associative array
11443 @tab language name
11444 @tab string
11445 @item @code{Body_Suffix}
11446 @tab associative array
11447 @tab language name
11448 @tab string
11449 @item @code{Separate_Suffix}
11450 @tab simple attribute
11451 @tab n/a
11452 @tab string
11453 @item @code{Casing}
11454 @tab simple attribute
11455 @tab n/a
11456 @tab string
11457 @item @code{Dot_Replacement}
11458 @tab simple attribute
11459 @tab n/a
11460 @tab string
11461 @item @code{Spec}
11462 @tab associative array
11463 @tab Ada unit name
11464 @tab string
11465 @item @code{Body}
11466 @tab associative array
11467 @tab Ada unit name
11468 @tab string
11469 @item @code{Specification_Exceptions}
11470 @tab associative array
11471 @tab language name
11472 @tab string list
11473 @item @code{Implementation_Exceptions}
11474 @tab associative array
11475 @tab language name
11476 @tab string list
11477 @end multitable
11479 @noindent
11480 The following attributes are defined for packages @code{Builder},
11481 @code{Compiler}, @code{Binder},
11482 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11483 (see @ref{^Switches^Switches^ and Project Files}).
11485 @multitable @columnfractions .4 .2 .2 .2
11486 @item Attribute Name @tab Category @tab Index @tab Value
11487 @item @code{^Default_Switches^Default_Switches^}
11488 @tab associative array
11489 @tab language name
11490 @tab string list
11491 @item @code{^Switches^Switches^}
11492 @tab associative array
11493 @tab file name
11494 @tab string list
11495 @end multitable
11497 @noindent
11498 In addition, package @code{Compiler} has a single string attribute
11499 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11500 string attribute @code{Global_Configuration_Pragmas}.
11502 @noindent
11503 Each simple attribute has a default value: the empty string (for string-valued
11504 attributes) and the empty list (for string list-valued attributes).
11506 An attribute declaration defines a new value for an attribute.
11508 Examples of simple attribute declarations:
11510 @smallexample @c projectfile
11511    for Object_Dir use "objects";
11512    for Source_Dirs use ("units", "test/drivers");
11513 @end smallexample
11515 @noindent
11516 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11517 attribute definition clause in Ada.
11519 Attributes references may be appear in expressions.
11520 The general form for such a reference is @code{<entity>'<attribute>}:
11521 Associative array attributes are functions. Associative
11522 array attribute references must have an argument that is a string literal.
11524 Examples are:
11526 @smallexample @c projectfile
11527   project'Object_Dir
11528   Naming'Dot_Replacement
11529   Imported_Project'Source_Dirs
11530   Imported_Project.Naming'Casing
11531   Builder'^Default_Switches^Default_Switches^("Ada")
11532 @end smallexample
11534 @noindent
11535 The prefix of an attribute may be:
11536 @itemize @bullet
11537 @item @code{project} for an attribute of the current project
11538 @item The name of an existing package of the current project
11539 @item The name of an imported project
11540 @item The name of a parent project that is extended by the current project
11541 @item An expanded name whose prefix is imported/parent project name,
11542       and whose selector is a package name
11543 @end itemize
11545 @noindent
11546 Example:
11547 @smallexample @c projectfile
11548 @group
11549    project Prj is
11550      for Source_Dirs use project'Source_Dirs & "units";
11551      for Source_Dirs use project'Source_Dirs & "test/drivers"
11552    end Prj;
11553 @end group
11554 @end smallexample
11556 @noindent
11557 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11558 has the default value: an empty string list. After this declaration,
11559 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11560 After the second attribute declaration @code{Source_Dirs} is a string list of
11561 two elements: @code{"units"} and @code{"test/drivers"}.
11563 Note: this example is for illustration only. In practice,
11564 the project file would contain only one attribute declaration:
11566 @smallexample @c projectfile
11567    for Source_Dirs use ("units", "test/drivers");
11568 @end smallexample
11570 @node Associative Array Attributes
11571 @subsection Associative Array Attributes
11573 @noindent
11574 Some attributes are defined as @emph{associative arrays}. An associative
11575 array may be regarded as a function that takes a string as a parameter
11576 and delivers a string or string list value as its result.
11578 Here are some examples of single associative array attribute associations:
11580 @smallexample @c projectfile
11581    for Body ("main") use "Main.ada";
11582    for ^Switches^Switches^ ("main.ada")
11583        use ("^-v^-v^",
11584             "^-gnatv^-gnatv^");
11585    for ^Switches^Switches^ ("main.ada")
11586             use Builder'^Switches^Switches^ ("main.ada")
11587               & "^-g^-g^";
11588 @end smallexample
11590 @noindent
11591 Like untyped variables and simple attributes, associative array attributes
11592 may be declared several times. Each declaration supplies a new value for the
11593 attribute, and replaces the previous setting.
11595 @noindent
11596 An associative array attribute may be declared as a full associative array
11597 declaration, with the value of the same attribute in an imported or extended
11598 project.
11600 @smallexample @c projectfile
11601    package Builder is
11602       for Default_Switches use Default.Builder'Default_Switches;
11603    end Builder;
11604 @end smallexample
11606 @noindent
11607 In this example, @code{Default} must be either an project imported by the
11608 current project, or the project that the current project extends. If the
11609 attribute is in a package (in this case, in package @code{Builder}), the same
11610 package needs to be specified.
11612 @noindent
11613 A full associative array declaration replaces any other declaration for the
11614 attribute, including other full associative array declaration. Single
11615 associative array associations may be declare after a full associative
11616 declaration, modifying the value for a single association of the attribute.
11618 @node case Constructions
11619 @subsection @code{case} Constructions
11621 @noindent
11622 A @code{case} construction is used in a project file to effect conditional
11623 behavior.
11624 Here is a typical example:
11626 @smallexample @c projectfile
11627 @group
11628 project MyProj is
11629    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11631    OS : OS_Type := external ("OS", "GNU/Linux");
11632 @end group
11634 @group
11635    package Compiler is
11636      case OS is
11637        when "GNU/Linux" | "Unix" =>
11638          for ^Default_Switches^Default_Switches^ ("Ada")
11639              use ("^-gnath^-gnath^");
11640        when "NT" =>
11641          for ^Default_Switches^Default_Switches^ ("Ada")
11642              use ("^-gnatP^-gnatP^");
11643        when others =>
11644      end case;
11645    end Compiler;
11646 end MyProj;
11647 @end group
11648 @end smallexample
11650 @noindent
11651 The syntax of a @code{case} construction is based on the Ada case statement
11652 (although there is no @code{null} construction for empty alternatives).
11654 The case expression must a typed string variable.
11655 Each alternative comprises the reserved word @code{when}, either a list of
11656 literal strings separated by the @code{"|"} character or the reserved word
11657 @code{others},  and the @code{"=>"} token.
11658 Each literal string must belong to the string type that is the type of the
11659 case variable.
11660 An @code{others} alternative, if present, must occur last.
11662 After each @code{=>}, there are zero or more constructions.  The only
11663 constructions allowed in a case construction are other case constructions and
11664 attribute declarations. String type declarations, variable declarations and
11665 package declarations are not allowed.
11667 The value of the case variable is often given by an external reference
11668 (see @ref{External References in Project Files}).
11670 @c ****************************************
11671 @c * Objects and Sources in Project Files *
11672 @c ****************************************
11674 @node Objects and Sources in Project Files
11675 @section Objects and Sources in Project Files
11677 @menu
11678 * Object Directory::
11679 * Exec Directory::
11680 * Source Directories::
11681 * Source File Names::
11682 @end menu
11684 @noindent
11685 Each project has exactly one object directory and one or more source
11686 directories. The source directories must contain at least one source file,
11687 unless  the project file explicitly specifies that no source files are present
11688 (see @ref{Source File Names}).
11690 @node Object Directory
11691 @subsection Object Directory
11693 @noindent
11694 The object directory for a project is the directory containing the compiler's
11695 output (such as @file{ALI} files and object files) for the project's immediate
11696 sources.
11698 The object directory is given by the value of the attribute @code{Object_Dir}
11699 in the project file.
11701 @smallexample @c projectfile
11702    for Object_Dir use "objects";
11703 @end smallexample
11705 @noindent
11706 The attribute @var{Object_Dir} has a string value, the path name of the object
11707 directory. The path name may be absolute or relative to the directory of the
11708 project file. This directory must already exist, and be readable and writable.
11710 By default, when the attribute @code{Object_Dir} is not given an explicit value
11711 or when its value is the empty string, the object directory is the same as the
11712 directory containing the project file.
11714 @node Exec Directory
11715 @subsection Exec Directory
11717 @noindent
11718 The exec directory for a project is the directory containing the executables
11719 for the project's main subprograms.
11721 The exec directory is given by the value of the attribute @code{Exec_Dir}
11722 in the project file.
11724 @smallexample @c projectfile
11725    for Exec_Dir use "executables";
11726 @end smallexample
11728 @noindent
11729 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11730 directory. The path name may be absolute or relative to the directory of the
11731 project file. This directory must already exist, and be writable.
11733 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11734 or when its value is the empty string, the exec directory is the same as the
11735 object directory of the project file.
11737 @node Source Directories
11738 @subsection Source Directories
11740 @noindent
11741 The source directories of a project are specified by the project file
11742 attribute @code{Source_Dirs}.
11744 This attribute's value is a string list. If the attribute is not given an
11745 explicit value, then there is only one source directory, the one where the
11746 project file resides.
11748 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11749 as in
11751 @smallexample @c projectfile
11752     for Source_Dirs use ();
11753 @end smallexample
11755 @noindent
11756 indicates that the project contains no source files.
11758 Otherwise, each string in the string list designates one or more
11759 source directories.
11761 @smallexample @c projectfile
11762    for Source_Dirs use ("sources", "test/drivers");
11763 @end smallexample
11765 @noindent
11766 If a string in the list ends with @code{"/**"},  then the directory whose path
11767 name precedes the two asterisks, as well as all its subdirectories
11768 (recursively), are source directories.
11770 @smallexample @c projectfile
11771    for Source_Dirs use ("/system/sources/**");
11772 @end smallexample
11774 @noindent
11775 Here the directory @code{/system/sources} and all of its subdirectories
11776 (recursively) are source directories.
11778 To specify that the source directories are the directory of the project file
11779 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11780 @smallexample @c projectfile
11781    for Source_Dirs use ("./**");
11782 @end smallexample
11784 @noindent
11785 Each of the source directories must exist and be readable.
11787 @node Source File Names
11788 @subsection Source File Names
11790 @noindent
11791 In a project that contains source files, their names may be specified by the
11792 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11793 (a string). Source file names never include any directory information.
11795 If the attribute @code{Source_Files} is given an explicit value, then each
11796 element of the list is a source file name.
11798 @smallexample @c projectfile
11799    for Source_Files use ("main.adb");
11800    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11801 @end smallexample
11803 @noindent
11804 If the attribute @code{Source_Files} is not given an explicit value,
11805 but the attribute @code{Source_List_File} is given a string value,
11806 then the source file names are contained in the text file whose path name
11807 (absolute or relative to the directory of the project file) is the
11808 value of the attribute @code{Source_List_File}.
11810 Each line in the file that is not empty or is not a comment
11811 contains a source file name.
11813 @smallexample @c projectfile
11814    for Source_List_File use "source_list.txt";
11815 @end smallexample
11817 @noindent
11818 By default, if neither the attribute @code{Source_Files} nor the attribute
11819 @code{Source_List_File} is given an explicit value, then each file in the
11820 source directories that conforms to the project's naming scheme
11821 (see @ref{Naming Schemes}) is an immediate source of the project.
11823 A warning is issued if both attributes @code{Source_Files} and
11824 @code{Source_List_File} are given explicit values. In this case, the attribute
11825 @code{Source_Files} prevails.
11827 Each source file name must be the name of one existing source file
11828 in one of the source directories.
11830 A @code{Source_Files} attribute whose value is an empty list
11831 indicates that there are no source files in the project.
11833 If the order of the source directories is known statically, that is if
11834 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11835 be several files with the same source file name. In this case, only the file
11836 in the first directory is considered as an immediate source of the project
11837 file. If the order of the source directories is not known statically, it is
11838 an error to have several files with the same source file name.
11840 Projects can be specified to have no Ada source
11841 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11842 list, or the @code{"Ada"} may be absent from @code{Languages}:
11844 @smallexample @c projectfile
11845    for Source_Dirs use ();
11846    for Source_Files use ();
11847    for Languages use ("C", "C++");
11848 @end smallexample
11850 @noindent
11851 Otherwise, a project must contain at least one immediate source.
11853 Projects with no source files are useful as template packages
11854 (see @ref{Packages in Project Files}) for other projects; in particular to
11855 define a package @code{Naming} (see @ref{Naming Schemes}).
11857 @c ****************************
11858 @c * Importing Projects *
11859 @c ****************************
11861 @node  Importing Projects
11862 @section Importing Projects
11864 @noindent
11865 An immediate source of a project P may depend on source files that
11866 are neither immediate sources of P nor in the predefined library.
11867 To get this effect, P must @emph{import} the projects that contain the needed
11868 source files.
11870 @smallexample @c projectfile
11871 @group
11872   with "project1", "utilities.gpr";
11873   with "/namings/apex.gpr";
11874   project Main is
11875     ...
11876 @end group
11877 @end smallexample
11879 @noindent
11880 As can be seen in this example, the syntax for importing projects is similar
11881 to the syntax for importing compilation units in Ada. However, project files
11882 use literal strings instead of names, and the @code{with} clause identifies
11883 project files rather than packages.
11885 Each literal string is the file name or path name (absolute or relative) of a
11886 project file. If a string is simply a file name, with no path, then its
11887 location is determined by the @emph{project path}:
11889 @itemize @bullet
11890 @item
11891 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11892 then the project path includes all the directories in this
11893 ^environment variable^logical name^, plus the directory of the project file.
11895 @item
11896 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11897 exist, then the project path contains only one directory, namely the one where
11898 the project file is located.
11899 @end itemize
11901 @noindent
11902 If a relative pathname is used, as in
11904 @smallexample @c projectfile
11905   with "tests/proj";
11906 @end smallexample
11908 @noindent
11909 then the path is relative to the directory where the importing project file is
11910 located. Any symbolic link will be fully resolved in the directory
11911 of the importing project file before the imported project file is examined.
11913 If the @code{with}'ed project file name does not have an extension,
11914 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11915 then the file name as specified in the @code{with} clause (no extension) will
11916 be used. In the above example, if a file @code{project1.gpr} is found, then it
11917 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11918 then it will be used; if neither file exists, this is an error.
11920 A warning is issued if the name of the project file does not match the
11921 name of the project; this check is case insensitive.
11923 Any source file that is an immediate source of the imported project can be
11924 used by the immediate sources of the importing project, transitively. Thus
11925 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11926 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11927 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11928 because if and when @code{B} ceases to import @code{C}, some sources in
11929 @code{A} will no longer compile.
11931 A side effect of this capability is that normally cyclic dependencies are not
11932 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11933 is not allowed to import @code{A}. However, there are cases when cyclic
11934 dependencies would be beneficial. For these cases, another form of import
11935 between projects exists, the @code{limited with}: a project @code{A} that
11936 imports a project @code{B} with a straigh @code{with} may also be imported,
11937 directly or indirectly, by @code{B} on the condition that imports from @code{B}
11938 to @code{A} include at least one @code{limited with}.
11940 @smallexample @c 0projectfile
11941 with "../b/b.gpr";
11942 with "../c/c.gpr";
11943 project A is
11944 end A;
11946 limited with "../a/a.gpr";
11947 project B is
11948 end B;
11950 with "../d/d.gpr";
11951 project C is
11952 end C;
11954 limited with "../a/a.gpr";
11955 project D is
11956 end D;
11957 @end smallexample
11959 @noindent
11960 In the above legal example, there are two project cycles:
11961 @itemize @bullet
11962 @item A-> B-> A
11963 @item A -> C -> D -> A
11964 @end itemize
11966 @noindent
11967 In each of these cycle there is one @code{limited with}: import of @code{A}
11968 from @code{B} and import of @code{A} from @code{D}.
11970 The difference between straight @code{with} and @code{limited with} is that
11971 the name of a project imported with a @code{limited with} cannot be used in the
11972 project that imports it. In particular, its packages cannot be renamed and
11973 its variables cannot be referred to.
11975 An exception to the above rules for @code{limited with} is that for the main
11976 project specified to @command{gnatmake} or to the @command{GNAT} driver a
11977 @code{limited with} is equivalent to a straight @code{with}. For example,
11978 in the example above, projects @code{B} and @code{D} could not be main
11979 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
11980 each have a @code{limited with} that is the only one in a cycle of importing
11981 projects.
11983 @c *********************
11984 @c * Project Extension *
11985 @c *********************
11987 @node Project Extension
11988 @section Project Extension
11990 @noindent
11991 During development of a large system, it is sometimes necessary to use
11992 modified versions of some of the source files, without changing the original
11993 sources. This can be achieved through the @emph{project extension} facility.
11995 @smallexample @c projectfile
11996    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
11997 @end smallexample
11999 @noindent
12000 A project extension declaration introduces an extending project
12001 (the @emph{child}) and a project being extended (the @emph{parent}).
12003 By default, a child project inherits all the sources of its parent.
12004 However, inherited sources can be overridden: a unit in a parent is hidden
12005 by a unit of the same name in the child.
12007 Inherited sources are considered to be sources (but not immediate sources)
12008 of the child project; see @ref{Project File Syntax}.
12010 An inherited source file retains any switches specified in the parent project.
12012 For example if the project @code{Utilities} contains the specification and the
12013 body of an Ada package @code{Util_IO}, then the project
12014 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12015 The original body of @code{Util_IO} will not be considered in program builds.
12016 However, the package specification will still be found in the project
12017 @code{Utilities}.
12019 A child project can have only one parent but it may import any number of other
12020 projects.
12022 A project is not allowed to import directly or indirectly at the same time a
12023 child project and any of its ancestors.
12025 @c ****************************************
12026 @c * External References in Project Files *
12027 @c ****************************************
12029 @node  External References in Project Files
12030 @section External References in Project Files
12032 @noindent
12033 A project file may contain references to external variables; such references
12034 are called @emph{external references}.
12036 An external variable is either defined as part of the environment (an
12037 environment variable in Unix, for example) or else specified on the command
12038 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12039 If both, then the command line value is used.
12041 The value of an external reference is obtained by means of the built-in
12042 function @code{external}, which returns a string value.
12043 This function has two forms:
12044 @itemize @bullet
12045 @item @code{external (external_variable_name)}
12046 @item @code{external (external_variable_name, default_value)}
12047 @end itemize
12049 @noindent
12050 Each parameter must be a string literal.  For example:
12052 @smallexample @c projectfile
12053    external ("USER")
12054    external ("OS", "GNU/Linux")
12055 @end smallexample
12057 @noindent
12058 In the form with one parameter, the function returns the value of
12059 the external variable given as parameter. If this name is not present in the
12060 environment, the function returns an empty string.
12062 In the form with two string parameters, the second argument is
12063 the value returned when the variable given as the first argument is not
12064 present in the environment. In the example above, if @code{"OS"} is not
12065 the name of ^an environment variable^a logical name^ and is not passed on
12066 the command line, then the returned value is @code{"GNU/Linux"}.
12068 An external reference may be part of a string expression or of a string
12069 list expression, and can therefore appear in a variable declaration or
12070 an attribute declaration.
12072 @smallexample @c projectfile
12073 @group
12074    type Mode_Type is ("Debug", "Release");
12075    Mode : Mode_Type := external ("MODE");
12076    case Mode is
12077      when "Debug" =>
12078         ...
12079 @end group
12080 @end smallexample
12082 @c *****************************
12083 @c * Packages in Project Files *
12084 @c *****************************
12086 @node  Packages in Project Files
12087 @section Packages in Project Files
12089 @noindent
12090 A @emph{package} defines the settings for project-aware tools within a
12091 project.
12092 For each such tool one can declare a package; the names for these
12093 packages are preset (see @ref{Packages}).
12094 A package may contain variable declarations, attribute declarations, and case
12095 constructions.
12097 @smallexample @c projectfile
12098 @group
12099    project Proj is
12100       package Builder is  -- used by gnatmake
12101          for ^Default_Switches^Default_Switches^ ("Ada")
12102              use ("^-v^-v^",
12103                   "^-g^-g^");
12104       end Builder;
12105    end Proj;
12106 @end group
12107 @end smallexample
12109 @noindent
12110 The syntax of package declarations mimics that of package in Ada.
12112 Most of the packages have an attribute
12113 @code{^Default_Switches^Default_Switches^}.
12114 This attribute is an associative array, and its value is a string list.
12115 The index of the associative array is the name of a programming language (case
12116 insensitive). This attribute indicates the ^switch^switch^
12117 or ^switches^switches^ to be used
12118 with the corresponding tool.
12120 Some packages also have another attribute, @code{^Switches^Switches^},
12121 an associative array whose value is a string list.
12122 The index is the name of a source file.
12123 This attribute indicates the ^switch^switch^
12124 or ^switches^switches^ to be used by the corresponding
12125 tool when dealing with this specific file.
12127 Further information on these ^switch^switch^-related attributes is found in
12128 @ref{^Switches^Switches^ and Project Files}.
12130 A package may be declared as a @emph{renaming} of another package; e.g., from
12131 the project file for an imported project.
12133 @smallexample @c projectfile
12134 @group
12135   with "/global/apex.gpr";
12136   project Example is
12137     package Naming renames Apex.Naming;
12138     ...
12139   end Example;
12140 @end group
12141 @end smallexample
12143 @noindent
12144 Packages that are renamed in other project files often come from project files
12145 that have no sources: they are just used as templates. Any modification in the
12146 template will be reflected automatically in all the project files that rename
12147 a package from the template.
12149 In addition to the tool-oriented packages, you can also declare a package
12150 named @code{Naming} to establish specialized source file naming conventions
12151 (see @ref{Naming Schemes}).
12153 @c ************************************
12154 @c * Variables from Imported Projects *
12155 @c ************************************
12157 @node Variables from Imported Projects
12158 @section Variables from Imported Projects
12160 @noindent
12161 An attribute or variable defined in an imported or parent project can
12162 be used in expressions in the importing / extending project.
12163 Such an attribute or variable is denoted by an expanded name whose prefix
12164 is either the name of the project or the expanded name of a package within
12165 a project.
12167 @smallexample @c projectfile
12168 @group
12169   with "imported";
12170   project Main extends "base" is
12171      Var1 := Imported.Var;
12172      Var2 := Base.Var & ".new";
12173 @end group
12175 @group
12176      package Builder is
12177         for ^Default_Switches^Default_Switches^ ("Ada")
12178             use Imported.Builder.Ada_^Switches^Switches^ &
12179                 "^-gnatg^-gnatg^" &
12180                 "^-v^-v^";
12181      end Builder;
12182 @end group
12184 @group
12185      package Compiler is
12186         for ^Default_Switches^Default_Switches^ ("Ada")
12187             use Base.Compiler.Ada_^Switches^Switches^;
12188      end Compiler;
12189   end Main;
12190 @end group
12191 @end smallexample
12193 @noindent
12194 In this example:
12196 @itemize @bullet
12197 @item
12198 The value of @code{Var1} is a copy of the variable @code{Var} defined
12199 in the project file @file{"imported.gpr"}
12200 @item
12201 the value of @code{Var2} is a copy of the value of variable @code{Var}
12202 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12203 @item
12204 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12205 @code{Builder} is a string list that includes in its value a copy of the value
12206 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12207 in project file @file{imported.gpr} plus two new elements:
12208 @option{"^-gnatg^-gnatg^"}
12209 and @option{"^-v^-v^"};
12210 @item
12211 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12212 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12213 defined in the @code{Compiler} package in project file @file{base.gpr},
12214 the project being extended.
12215 @end itemize
12217 @c ******************
12218 @c * Naming Schemes *
12219 @c ******************
12221 @node  Naming Schemes
12222 @section Naming Schemes
12224 @noindent
12225 Sometimes an Ada software system is ported from a foreign compilation
12226 environment to GNAT, and the file names do not use the default GNAT
12227 conventions. Instead of changing all the file names (which for a variety
12228 of reasons might not be possible), you can define the relevant file
12229 naming scheme in the @code{Naming} package in your project file.
12231 @noindent
12232 Note that the use of pragmas described in @ref{Alternative
12233 File Naming Schemes} by mean of a configuration pragmas file is not
12234 supported when using project files. You must use the features described
12235 in this paragraph. You can however use specify other configuration
12236 pragmas (see @ref{Specifying Configuration Pragmas}).
12238 @ifclear vms
12239 For example, the following
12240 package models the Apex file naming rules:
12242 @smallexample @c projectfile
12243 @group
12244   package Naming is
12245     for Casing               use "lowercase";
12246     for Dot_Replacement      use ".";
12247     for Spec_Suffix ("Ada")  use ".1.ada";
12248     for Body_Suffix ("Ada")  use ".2.ada";
12249   end Naming;
12250 @end group
12251 @end smallexample
12252 @end ifclear
12254 @ifset vms
12255 For example, the following package models the DEC Ada file naming rules:
12257 @smallexample @c projectfile
12258 @group
12259   package Naming is
12260     for Casing               use "lowercase";
12261     for Dot_Replacement      use "__";
12262     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12263     for Body_Suffix ("Ada")  use ".^ada^ada^";
12264   end Naming;
12265 @end group
12266 @end smallexample
12268 @noindent
12269 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12270 names in lower case)
12271 @end ifset
12273 @noindent
12274 You can define the following attributes in package @code{Naming}:
12276 @table @code
12278 @item @var{Casing}
12279 This must be a string with one of the three values @code{"lowercase"},
12280 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12282 @noindent
12283 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12285 @item @var{Dot_Replacement}
12286 This must be a string whose value satisfies the following conditions:
12288 @itemize @bullet
12289 @item It must not be empty
12290 @item It cannot start or end with an alphanumeric character
12291 @item It cannot be a single underscore
12292 @item It cannot start with an underscore followed by an alphanumeric
12293 @item It cannot contain a dot @code{'.'} except if the entire string
12294 is @code{"."}
12295 @end itemize
12297 @noindent
12298 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12300 @item @var{Spec_Suffix}
12301 This is an associative array (indexed by the programming language name, case
12302 insensitive) whose value is a string that must satisfy the following
12303 conditions:
12305 @itemize @bullet
12306 @item It must not be empty
12307 @item It must include at least one dot
12308 @end itemize
12309 @noindent
12310 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12311 @code{"^.ads^.ADS^"}.
12313 @item @var{Body_Suffix}
12314 This is an associative array (indexed by the programming language name, case
12315 insensitive) whose value is a string that must satisfy the following
12316 conditions:
12318 @itemize @bullet
12319 @item It must not be empty
12320 @item It must include at least one dot
12321 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12322 @end itemize
12323 @noindent
12324 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12325 @code{"^.adb^.ADB^"}.
12327 @item @var{Separate_Suffix}
12328 This must be a string whose value satisfies the same conditions as
12329 @code{Body_Suffix}.
12331 @noindent
12332 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12333 value as @code{Body_Suffix ("Ada")}.
12335 @item @var{Spec}
12336 @noindent
12337 You can use the associative array attribute @code{Spec}  to define
12338 the source file name for an individual Ada compilation unit's spec. The array
12339 index must be a string literal that identifies the Ada unit (case insensitive).
12340 The value of this attribute must be a string that identifies the file that
12341 contains this unit's spec (case sensitive or insensitive depending on the
12342 operating system).
12344 @smallexample @c projectfile
12345    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12346 @end smallexample
12348 @item @var{Body}
12350 You can use the associative array attribute @code{Body} to
12351 define the source file name for an individual Ada compilation unit's body
12352 (possibly a subunit).  The array index must be a string literal that identifies
12353 the Ada unit (case insensitive).  The value of this attribute must be a string
12354 that identifies the file that contains this unit's body or subunit (case
12355 sensitive or insensitive depending on the operating system).
12357 @smallexample @c projectfile
12358    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12359 @end smallexample
12360 @end table
12362 @c ********************
12363 @c * Library Projects *
12364 @c ********************
12366 @node Library Projects
12367 @section Library Projects
12369 @noindent
12370 @emph{Library projects} are projects whose object code is placed in a library.
12371 (Note that this facility is not yet supported on all platforms)
12373 To create a library project, you need to define in its project file
12374 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12375 Additionally, you may define the library-related attributes
12376 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12377 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12379 The @code{Library_Name} attribute has a string value. There is no restriction
12380 on the name of a library. It is the responsability of the developer to
12381 choose a name that will be accepted by the platform. It is recommanded to
12382 choose names that could be Ada identifiers; such names are almost guaranteed
12383 to be acceptable on all platforms.
12385 The @code{Library_Dir} attribute has a string value that designates the path
12386 (absolute or relative) of the directory where the library will reside.
12387 It must designate an existing directory, and this directory must be
12388 different from the project's object directory. It also needs to be writable.
12390 If both @code{Library_Name} and @code{Library_Dir} are specified and
12391 are legal, then the project file defines a library project.  The optional
12392 library-related attributes are checked only for such project files.
12394 The @code{Library_Kind} attribute has a string value that must be one of the
12395 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12396 @code{"relocatable"}. If this attribute is not specified, the library is a
12397 static library, that is an archive of object files that can be potentially
12398 linked into an static executable. Otherwise, the library may be dynamic or
12399 relocatable, that is a library that is loaded only at the start of execution.
12400 Depending on the operating system, there may or may not be a distinction
12401 between dynamic and relocatable libraries. For Unix and VMS Unix there is no
12402 such distinction.
12404 If you need to build both a static and a dynamic library, you should use two
12405 different object directories, since in some cases some extra code needs to
12406 be generated for the latter. For such cases, it is recommended to either use
12407 two different project files, or a single one which uses external variables
12408 to indicate what kind of library should be build.
12410 The @code{Library_Version} attribute has a string value whose interpretation
12411 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12412 used only for dynamic/relocatable libraries as the internal name of the
12413 library (the @code{"soname"}). If the library file name (built from the
12414 @code{Library_Name}) is different from the @code{Library_Version}, then the
12415 library file will be a symbolic link to the actual file whose name will be
12416 @code{Library_Version}.
12418 Example (on Unix):
12420 @smallexample @c projectfile
12421 @group
12422 project Plib is
12424    Version := "1";
12426    for Library_Dir use "lib_dir";
12427    for Library_Name use "dummy";
12428    for Library_Kind use "relocatable";
12429    for Library_Version use "libdummy.so." & Version;
12431 end Plib;
12432 @end group
12433 @end smallexample
12435 @noindent
12436 Directory @file{lib_dir} will contain the internal library file whose name
12437 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12438 @file{libdummy.so.1}.
12440 When @command{gnatmake} detects that a project file
12441 is a library project file, it will check all immediate sources of the project
12442 and rebuild the library if any of the sources have been recompiled.
12444 When a library is built or rebuilt, an attempt is made to delete all
12445 files in the library directory.
12446 All @file{ALI} files will also be copied from the object directory to the
12447 library directory. To build executables, @command{gnatmake} will use the
12448 library rather than the individual object files. The copy of the @file{ALI}
12449 files are made read-only.
12452 @c **********************************************
12453 @c * Using Third-Party Libraries through Projects
12454 @c **********************************************
12455 @node Using Third-Party Libraries through Projects
12456 @section Using Third-Party Libraries through Projects
12458 Whether you are exporting your own library to make it available to
12459 clients, or you are using a library provided by a third party, it is
12460 convenient to have project files that automatically set the correct
12461 command line switches for the compiler and linker.
12463 Such project files are very similar to the library project files;
12464 @xref{Library Projects}. The only difference is that you set the
12465 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12466 directories where, respectively, the sources and the read-only ALI files have
12467 been installed.
12469 If you need to interface with a set of libraries, as opposed to a
12470 single one, you need to create one library project for each of the
12471 libraries. In addition, a top-level project that imports all these
12472 library projects should be provided, so that the user of your library
12473 has a single @code{with} clause to add to his own projects.
12475 For instance, let's assume you are providing two static libraries
12476 @file{liba.a} and @file{libb.a}. The user needs to link with
12477 both of these libraries. Each of these is associated with its
12478 own set of header files. Let's assume furthermore that all the
12479 header files for the two libraries have been installed in the same
12480 directory @file{headers}. The @file{ALI} files are found in the same
12481 @file{headers} directory.
12483 In this case, you should provide the following three projects:
12485 @smallexample @c projectfile
12486 @group
12487 with "liba", "libb";
12488 project My_Library is
12489   for Source_Dirs use ("headers");
12490   for Object_Dir  use "headers";
12491 end My_Library;
12492 @end group
12494 @group
12495 project Liba is
12496    for Source_Dirs use ();
12497    for Library_Dir use "lib";
12498    for Library_Name use "a";
12499    for Library_Kind use "static";
12500 end Liba;
12501 @end group
12503 @group
12504 project Libb is
12505    for Source_Dirs use ();
12506    for Library_Dir use "lib";
12507    for Library_Name use "b";
12508    for Library_Kind use "static";
12509 end Libb;
12510 @end group
12511 @end smallexample
12513 @c *******************************
12514 @c * Stand-alone Library Projects *
12515 @c *******************************
12517 @node Stand-alone Library Projects
12518 @section Stand-alone Library Projects
12520 @noindent
12521 A Stand-alone Library is a library that contains the necessary code to
12522 elaborate the Ada units that are included in the library. A Stand-alone
12523 Library is suitable to be used in an executable when the main is not
12524 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12525 subprogram.
12527 A Stand-alone Library Project is a Library Project where the library is
12528 a Stand-alone Library.
12530 To be a Stand-alone Library Project, in addition to the two attributes
12531 that make a project a Library Project (@code{Library_Name} and
12532 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12533 @code{Library_Interface} must be defined.
12535 @smallexample @c projectfile
12536 @group
12537    for Library_Dir use "lib_dir";
12538    for Library_Name use "dummy";
12539    for Library_Interface use ("int1", "int1.child");
12540 @end group
12541 @end smallexample
12543 Attribute @code{Library_Interface} has a non empty string list value,
12544 each string in the list designating a unit contained in an immediate source
12545 of the project file.
12547 When a Stand-alone Library is built, first the binder is invoked to build
12548 a package whose name depends on the library name
12549 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12550 This binder-generated package includes initialization and
12551 finalization procedures whose
12552 names depend on the library name (dummyinit and dummyfinal in the example
12553 above). The object corresponding to this package is included in the library.
12555 A dynamic or relocatable Stand-alone Library is automatically initialized
12556 if automatic initialization of Stand-alone Libraries is supported on the
12557 platform and if attribute @code{Library_Auto_Init} is not specified or
12558 is specified with the value "true". A static Stand-alone Library is never
12559 automatically initialized.
12561 Single string attribute @code{Library_Auto_Init} may be specified with only
12562 two possible values: "false" or "true" (case-insensitive). Specifying
12563 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12564 initialization of dynamic or relocatable libraries.
12566 When a non automatically initialized Stand-alone Library is used
12567 in an executable, its initialization procedure must be called before
12568 any service of the library is used.
12569 When the main subprogram is in Ada, it may mean that the initialization
12570 procedure has to be called during elaboration of another package.
12572 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12573 (those that are listed in attribute @code{Library_Interface}) are copied to
12574 the Library Directory. As a consequence, only the Interface Units may be
12575 imported from Ada units outside of the library. If other units are imported,
12576 the binding phase will fail.
12578 When a Stand-Alone Library is bound, the switches that are specified in
12579 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12580 used in the call to @command{gnatbind}.
12582 The string list attribute @code{Library_Options} may be used to specified
12583 additional switches to the call to @command{gcc} to link the library.
12585 The attribute @code{Library_Src_Dir}, may be specified for a
12586 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12587 single string value. Its value must be the path (absolute or relative to the
12588 project directory) of an existing directory. This directory cannot be the
12589 object directory or one of the source directories, but it can be the same as
12590 the library directory. The sources of the Interface
12591 Units of the library, necessary to an Ada client of the library, will be
12592 copied to the designated directory, called Interface Copy directory.
12593 These sources includes the specs of the Interface Units, but they may also
12594 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12595 are used, or when there is a generic units in the spec. Before the sources
12596 are copied to the Interface Copy directory, an attempt is made to delete all
12597 files in the Interface Copy directory.
12599 @c *************************************
12600 @c * Switches Related to Project Files *
12601 @c *************************************
12602 @node Switches Related to Project Files
12603 @section Switches Related to Project Files
12605 @noindent
12606 The following switches are used by GNAT tools that support project files:
12608 @table @option
12610 @item ^-P^/PROJECT_FILE=^@var{project}
12611 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12612 Indicates the name of a project file. This project file will be parsed with
12613 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12614 if any, and using the external references indicated
12615 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12616 @ifclear vms
12617 There may zero, one or more spaces between @option{-P} and @var{project}.
12618 @end ifclear
12620 @noindent
12621 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12623 @noindent
12624 Since the Project Manager parses the project file only after all the switches
12625 on the command line are checked, the order of the switches
12626 @option{^-P^/PROJECT_FILE^},
12627 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12628 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12630 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12631 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12632 Indicates that external variable @var{name} has the value @var{value}.
12633 The Project Manager will use this value for occurrences of
12634 @code{external(name)} when parsing the project file.
12636 @ifclear vms
12637 @noindent
12638 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12639 put between quotes.
12640 @smallexample
12641   -XOS=NT
12642   -X"user=John Doe"
12643 @end smallexample
12644 @end ifclear
12646 @noindent
12647 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12648 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12649 @var{name}, only the last one is used.
12651 @noindent
12652 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12653 takes precedence over the value of the same name in the environment.
12655 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12656 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12657 @c Previous line uses code vs option command, to stay less than 80 chars
12658 Indicates the verbosity of the parsing of GNAT project files.
12660 @ifclear vms
12661 @option{-vP0} means Default;
12662 @option{-vP1} means Medium;
12663 @option{-vP2} means High.
12664 @end ifclear
12666 @ifset vms
12667 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12668 HIGH.
12669 @end ifset
12671 @noindent
12672 The default is ^Default^DEFAULT^: no output for syntactically correct
12673 project files.
12674 @noindent
12675 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12676 only the last one is used.
12678 @end table
12680 @c **********************************
12681 @c * Tools Supporting Project Files *
12682 @c **********************************
12684 @node  Tools Supporting Project Files
12685 @section Tools Supporting Project Files
12687 @menu
12688 * gnatmake and Project Files::
12689 * The GNAT Driver and Project Files::
12690 @ifclear vms
12691 * Glide and Project Files::
12692 @end ifclear
12693 @end menu
12695 @node gnatmake and Project Files
12696 @subsection gnatmake and Project Files
12698 @noindent
12699 This section covers several topics related to @command{gnatmake} and
12700 project files: defining ^switches^switches^ for @command{gnatmake}
12701 and for the tools that it invokes; specifying configuration pragmas;
12702 the use of the @code{Main} attribute; building and rebuilding library project
12703 files.
12705 @menu
12706 * ^Switches^Switches^ and Project Files::
12707 * Specifying Configuration Pragmas::
12708 * Project Files and Main Subprograms::
12709 * Library Project Files::
12710 @end menu
12712 @node ^Switches^Switches^ and Project Files
12713 @subsubsection ^Switches^Switches^ and Project Files
12715 @ifset vms
12716 It is not currently possible to specify VMS style qualifiers in the project
12717 files; only Unix style ^switches^switches^ may be specified.
12718 @end ifset
12720 @noindent
12721 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12722 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12723 attribute, a @code{^Switches^Switches^} attribute, or both;
12724 as their names imply, these ^switch^switch^-related
12725 attributes affect the ^switches^switches^ that are used for each of these GNAT
12726 components when
12727 @command{gnatmake} is invoked.  As will be explained below, these
12728 component-specific ^switches^switches^ precede
12729 the ^switches^switches^ provided on the @command{gnatmake} command line.
12731 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12732 array indexed by language name (case insensitive) whose value is a string list.
12733 For example:
12735 @smallexample @c projectfile
12736 @group
12737 package Compiler is
12738   for ^Default_Switches^Default_Switches^ ("Ada")
12739       use ("^-gnaty^-gnaty^",
12740            "^-v^-v^");
12741 end Compiler;
12742 @end group
12743 @end smallexample
12745 @noindent
12746 The @code{^Switches^Switches^} attribute is also an associative array,
12747 indexed by a file name (which may or may not be case sensitive, depending
12748 on the operating system) whose value is a string list.  For example:
12750 @smallexample @c projectfile
12751 @group
12752 package Builder is
12753    for ^Switches^Switches^ ("main1.adb")
12754        use ("^-O2^-O2^");
12755    for ^Switches^Switches^ ("main2.adb")
12756        use ("^-g^-g^");
12757 end Builder;
12758 @end group
12759 @end smallexample
12761 @noindent
12762 For the @code{Builder} package, the file names must designate source files
12763 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12764 file names must designate @file{ALI} or source files for main subprograms.
12765 In each case just the file name without an explicit extension is acceptable.
12767 For each tool used in a program build (@command{gnatmake}, the compiler, the
12768 binder, and the linker), the corresponding package @dfn{contributes} a set of
12769 ^switches^switches^ for each file on which the tool is invoked, based on the
12770 ^switch^switch^-related attributes defined in the package.
12771 In particular, the ^switches^switches^
12772 that each of these packages contributes for a given file @var{f} comprise:
12774 @itemize @bullet
12775 @item
12776 the value of attribute @code{^Switches^Switches^ (@var{f})},
12777 if it is specified in the package for the given file,
12778 @item
12779 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12780 if it is specified in the package.
12781 @end itemize
12783 @noindent
12784 If neither of these attributes is defined in the package, then the package does
12785 not contribute any ^switches^switches^ for the given file.
12787 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12788 two sets, in the following order: those contributed for the file
12789 by the @code{Builder} package;
12790 and the switches passed on the command line.
12792 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12793 the ^switches^switches^ passed to the tool comprise three sets,
12794 in the following order:
12796 @enumerate
12797 @item
12798 the applicable ^switches^switches^ contributed for the file
12799 by the @code{Builder} package in the project file supplied on the command line;
12801 @item
12802 those contributed for the file by the package (in the relevant project file --
12803 see below) corresponding to the tool; and
12805 @item
12806 the applicable switches passed on the command line.
12807 @end enumerate
12809 @noindent
12810 The term @emph{applicable ^switches^switches^} reflects the fact that
12811 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12812 tools, depending on the individual ^switch^switch^.
12814 @command{gnatmake} may invoke the compiler on source files from different
12815 projects. The Project Manager will use the appropriate project file to
12816 determine the @code{Compiler} package for each source file being compiled.
12817 Likewise for the @code{Binder} and @code{Linker} packages.
12819 As an example, consider the following package in a project file:
12821 @smallexample @c projectfile
12822 @group
12823 project Proj1 is
12824    package Compiler is
12825       for ^Default_Switches^Default_Switches^ ("Ada")
12826           use ("^-g^-g^");
12827       for ^Switches^Switches^ ("a.adb")
12828           use ("^-O1^-O1^");
12829       for ^Switches^Switches^ ("b.adb")
12830           use ("^-O2^-O2^",
12831                "^-gnaty^-gnaty^");
12832    end Compiler;
12833 end Proj1;
12834 @end group
12835 @end smallexample
12837 @noindent
12838 If @command{gnatmake} is invoked with this project file, and it needs to
12839 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12840 @file{a.adb} will be compiled with the ^switch^switch^
12841 @option{^-O1^-O1^},
12842 @file{b.adb} with ^switches^switches^
12843 @option{^-O2^-O2^}
12844 and @option{^-gnaty^-gnaty^},
12845 and @file{c.adb} with @option{^-g^-g^}.
12847 The following example illustrates the ordering of the ^switches^switches^
12848 contributed by different packages:
12850 @smallexample @c projectfile
12851 @group
12852 project Proj2 is
12853    package Builder is
12854       for ^Switches^Switches^ ("main.adb")
12855           use ("^-g^-g^",
12856                "^-O1^-)1^",
12857                "^-f^-f^");
12858    end Builder;
12859 @end group
12861 @group
12862    package Compiler is
12863       for ^Switches^Switches^ ("main.adb")
12864           use ("^-O2^-O2^");
12865    end Compiler;
12866 end Proj2;
12867 @end group
12868 @end smallexample
12870 @noindent
12871 If you issue the command:
12873 @smallexample
12874     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12875 @end smallexample
12877 @noindent
12878 then the compiler will be invoked on @file{main.adb} with the following
12879 sequence of ^switches^switches^
12881 @smallexample
12882    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12883 @end smallexample
12885 with the last @option{^-O^-O^}
12886 ^switch^switch^ having precedence over the earlier ones;
12887 several other ^switches^switches^
12888 (such as @option{^-c^-c^}) are added implicitly.
12890 The ^switches^switches^
12891 @option{^-g^-g^}
12892 and @option{^-O1^-O1^} are contributed by package
12893 @code{Builder},  @option{^-O2^-O2^} is contributed
12894 by the package @code{Compiler}
12895 and @option{^-O0^-O0^} comes from the command line.
12897 The @option{^-g^-g^}
12898 ^switch^switch^ will also be passed in the invocation of
12899 @command{Gnatlink.}
12901 A final example illustrates switch contributions from packages in different
12902 project files:
12904 @smallexample @c projectfile
12905 @group
12906 project Proj3 is
12907    for Source_Files use ("pack.ads", "pack.adb");
12908    package Compiler is
12909       for ^Default_Switches^Default_Switches^ ("Ada")
12910           use ("^-gnata^-gnata^");
12911    end Compiler;
12912 end Proj3;
12913 @end group
12915 @group
12916 with "Proj3";
12917 project Proj4 is
12918    for Source_Files use ("foo_main.adb", "bar_main.adb");
12919    package Builder is
12920       for ^Switches^Switches^ ("foo_main.adb")
12921           use ("^-s^-s^",
12922                "^-g^-g^");
12923    end Builder;
12924 end Proj4;
12925 @end group
12927 @group
12928 -- Ada source file:
12929 with Pack;
12930 procedure Foo_Main is
12931    ...
12932 end Foo_Main;
12933 @end group
12934 @end smallexample
12936 If the command is
12937 @smallexample
12938 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12939 @end smallexample
12941 @noindent
12942 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12943 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12944 @option{^-gnato^-gnato^} (passed on the command line).
12945 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12946 are @option{^-g^-g^} from @code{Proj4.Builder},
12947 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12948 and @option{^-gnato^-gnato^} from the command line.
12950 @noindent
12951 When using @command{gnatmake} with project files, some ^switches^switches^ or
12952 arguments may be expressed as relative paths. As the working directory where
12953 compilation occurs may change, these relative paths are converted to absolute
12954 paths. For the ^switches^switches^ found in a project file, the relative paths
12955 are relative to the project file directory, for the switches on the command
12956 line, they are relative to the directory where @command{gnatmake} is invoked.
12957 The ^switches^switches^ for which this occurs are:
12958 ^-I^-I^,
12959 ^-A^-A^,
12960 ^-L^-L^,
12961 ^-aO^-aO^,
12962 ^-aL^-aL^,
12963 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12964 ^switch^switch^
12965 ^-o^-o^, object files specified in package @code{Linker} or after
12966 -largs on the command line). The exception to this rule is the ^switch^switch^
12967 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12969 @node Specifying Configuration Pragmas
12970 @subsubsection Specifying Configuration Pragmas
12972 When using @command{gnatmake} with project files, if there exists a file
12973 @file{gnat.adc} that contains configuration pragmas, this file will be
12974 ignored.
12976 Configuration pragmas can be defined by means of the following attributes in
12977 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12978 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12980 Both these attributes are single string attributes. Their values is the path
12981 name of a file containing configuration pragmas. If a path name is relative,
12982 then it is relative to the project directory of the project file where the
12983 attribute is defined.
12985 When compiling a source, the configuration pragmas used are, in order,
12986 those listed in the file designated by attribute
12987 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12988 project file, if it is specified, and those listed in the file designated by
12989 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12990 the project file of the source, if it exists.
12992 @node Project Files and Main Subprograms
12993 @subsubsection Project Files and Main Subprograms
12995 @noindent
12996 When using a project file, you can invoke @command{gnatmake}
12997 with one or several main subprograms, by specifying their source files on the
12998 command line.
13000 @smallexample
13001     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13002 @end smallexample
13004 @noindent
13005 Each of these needs to be a source file of the same project, except
13006 when the switch ^-u^/UNIQUE^ is used.
13008 @noindent
13009 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13010 same project, one of the project in the tree rooted at the project specified
13011 on the command line. The package @code{Builder} of this common project, the
13012 "main project" is the one that is considered by @command{gnatmake}.
13014 @noindent
13015 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13016 imported directly or indirectly by the project specified on the command line.
13017 Note that if such a source file is not part of the project specified on the
13018 command line, the ^switches^switches^ found in package @code{Builder} of the
13019 project specified on the command line, if any, that are transmitted
13020 to the compiler will still be used, not those found in the project file of
13021 the source file.
13023 @noindent
13024 When using a project file, you can also invoke @command{gnatmake} without
13025 explicitly specifying any main, and the effect depends on whether you have
13026 defined the @code{Main} attribute.  This attribute has a string list value,
13027 where each element in the list is the name of a source file (the file
13028 extension is optional) that contains a unit that can be a main subprogram.
13030 If the @code{Main} attribute is defined in a project file as a non-empty
13031 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13032 line, then invoking @command{gnatmake} with this project file but without any
13033 main on the command line is equivalent to invoking @command{gnatmake} with all
13034 the file names in the @code{Main} attribute on the command line.
13036 Example:
13037 @smallexample @c projectfile
13038 @group
13039    project Prj is
13040       for Main use ("main1", "main2", "main3");
13041    end Prj;
13042 @end group
13043 @end smallexample
13045 @noindent
13046 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13047 is equivalent to
13048 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13050 When the project attribute @code{Main} is not specified, or is specified
13051 as an empty string list, or when the switch @option{-u} is used on the command
13052 line, then invoking @command{gnatmake} with no main on the command line will
13053 result in all immediate sources of the project file being checked, and
13054 potentially recompiled. Depending on the presence of the switch @option{-u},
13055 sources from other project files on which the immediate sources of the main
13056 project file depend are also checked and potentially recompiled. In other
13057 words, the @option{-u} switch is applied to all of the immediate sources of the
13058 main project file.
13060 When no main is specified on the command line and attribute @code{Main} exists
13061 and includes several mains, or when several mains are specified on the
13062 command line, the default ^switches^switches^ in package @code{Builder} will
13063 be used for all mains, even if there are specific ^switches^switches^
13064 specified for one or several mains.
13066 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13067 the specific ^switches^switches^ for each main, if they are specified.
13069 @node Library Project Files
13070 @subsubsection Library Project Files
13072 @noindent
13073 When @command{gnatmake} is invoked with a main project file that is a library
13074 project file, it is not allowed to specify one or more mains on the command
13075 line.
13077 @noindent
13078 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13079 ^-l^/ACTION=LINK^ have special meanings.
13081 @itemize @bullet
13082 @item ^-b^/ACTION=BIND^ is only allwed for stand-alone libraries. It indicates
13083 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13084 library.
13086 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13087 to @command{gnatmake} that the binder generated file should be compiled
13088 (in the case of a stand-alone library) and that the library should be built.
13090 @end itemize
13092 @node The GNAT Driver and Project Files
13093 @subsection The GNAT Driver and Project Files
13095 @noindent
13096 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13097 are project-aware:
13098 @command{^gnatbind^gnatbind^},
13099 @command{^gnatfind^gnatfind^},
13100 @command{^gnatlink^gnatlink^},
13101 @command{^gnatls^gnatls^},
13102 @command{^gnatelim^gnatelim^},
13103 @command{^gnatpp^gnatpp^},
13104 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13105 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13106 They must be invoked through the @command{gnat} driver.
13108 The @command{gnat} driver is a front-end that accepts a number of commands and
13109 call the corresponding tool. It has been designed initially for VMS to convert
13110 VMS style qualifiers to Unix style switches, but it is now available to all
13111 the GNAT supported platforms.
13113 On non VMS platforms, the @command{gnat} driver accepts the following commands
13114 (case insensitive):
13116 @itemize @bullet
13117 @item
13118 BIND to invoke @command{^gnatbind^gnatbind^}
13119 @item
13120 CHOP to invoke @command{^gnatchop^gnatchop^}
13121 @item
13122 CLEAN to invoke @command{^gnatclean^gnatclean^}
13123 @item
13124 COMP or COMPILE to invoke the compiler
13125 @item
13126 ELIM to invoke @command{^gnatelim^gnatelim^}
13127 @item
13128 FIND to invoke @command{^gnatfind^gnatfind^}
13129 @item
13130 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13131 @item
13132 LINK to invoke @command{^gnatlink^gnatlink^}
13133 @item
13134 LS or LIST to invoke @command{^gnatls^gnatls^}
13135 @item
13136 MAKE to invoke @command{^gnatmake^gnatmake^}
13137 @item
13138 NAME to invoke @command{^gnatname^gnatname^}
13139 @item
13140 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13141 @item
13142 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13143 @item
13144 STUB to invoke @command{^gnatstub^gnatstub^}
13145 @item
13146 XREF to invoke @command{^gnatxref^gnatxref^}
13147 @end itemize
13149 @noindent
13150 Note that the compiler is invoked using the command
13151 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}.
13153 @noindent
13154 The command may be followed by switches and arguments for the invoked
13155 tool.
13157 @smallexample
13158   gnat bind -C main.ali
13159   gnat ls -a main
13160   gnat chop foo.txt
13161 @end smallexample
13163 @noindent
13164 Switches may also be put in text files, one switch per line, and the text
13165 files may be specified with their path name preceded by '@@'.
13167 @smallexample
13168    gnat bind @@args.txt main.ali
13169 @end smallexample
13171 @noindent
13172 In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13173 PP or PRETTY and XREF, the project file related switches
13174 (@option{^-P^/PROJECT_FILE^},
13175 @option{^-X^/EXTERNAL_REFERENCE^} and
13176 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13177 the switches of the invoking tool.
13179 @noindent
13180 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13181 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13182 the immediate sources of the specified project file.
13184 @noindent
13185 For each of these commands, there is optionally a corresponding  package
13186 in the main project.
13188 @itemize @bullet
13189 @item
13190 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13192 @item
13193 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13195 @item
13196 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13198 @item
13199 package @code{Eliminate} for command ELIM (invoking
13200 @code{^gnatelim^gnatelim^})
13202 @item
13203 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13205 @item
13206 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13208 @item
13209 package @code{Pretty_Printer} for command PP or PRETTY
13210 (invoking @code{^gnatpp^gnatpp^})
13212 @item
13213 package @code{Cross_Reference} for command XREF (invoking
13214 @code{^gnatxref^gnatxref^})
13216 @end itemize
13218 @noindent
13219 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13220 a simple variable with a string list value. It contains ^switches^switches^
13221 for the invocation of @code{^gnatls^gnatls^}.
13223 @smallexample @c projectfile
13224 @group
13225 project Proj1 is
13226    package gnatls is
13227       for ^Switches^Switches^
13228           use ("^-a^-a^",
13229                "^-v^-v^");
13230    end gnatls;
13231 end Proj1;
13232 @end group
13233 @end smallexample
13235 @noindent
13236 All other packages have two attribute @code{^Switches^Switches^} and
13237 @code{^Default_Switches^Default_Switches^}.
13239 @noindent
13240 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13241 source file name, that has a string list value: the ^switches^switches^ to be
13242 used when the tool corresponding to the package is invoked for the specific
13243 source file.
13245 @noindent
13246 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13247 indexed by  the programming language that has a string list value.
13248 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13249 ^switches^switches^ for the invocation of the tool corresponding
13250 to the package, except if a specific @code{^Switches^Switches^} attribute
13251 is specified for the source file.
13253 @smallexample @c projectfile
13254 @group
13255 project Proj is
13257    for Source_Dirs use ("./**");
13259    package gnatls is
13260       for ^Switches^Switches^ use
13261           ("^-a^-a^",
13262            "^-v^-v^");
13263    end gnatls;
13264 @end group
13265 @group
13267    package Compiler is
13268       for ^Default_Switches^Default_Switches^ ("Ada")
13269           use ("^-gnatv^-gnatv^",
13270                "^-gnatwa^-gnatwa^");
13271    end Binder;
13272 @end group
13273 @group
13275    package Binder is
13276       for ^Default_Switches^Default_Switches^ ("Ada")
13277           use ("^-C^-C^",
13278                "^-e^-e^");
13279    end Binder;
13280 @end group
13281 @group
13283    package Linker is
13284       for ^Default_Switches^Default_Switches^ ("Ada")
13285           use ("^-C^-C^");
13286       for ^Switches^Switches^ ("main.adb")
13287           use ("^-C^-C^",
13288                "^-v^-v^",
13289                "^-v^-v^");
13290    end Linker;
13291 @end group
13292 @group
13294    package Finder is
13295       for ^Default_Switches^Default_Switches^ ("Ada")
13296            use ("^-a^-a^",
13297                 "^-f^-f^");
13298    end Finder;
13299 @end group
13300 @group
13302    package Cross_Reference is
13303       for ^Default_Switches^Default_Switches^ ("Ada")
13304           use ("^-a^-a^",
13305                "^-f^-f^",
13306                "^-d^-d^",
13307                "^-u^-u^");
13308    end Cross_Reference;
13309 end Proj;
13310 @end group
13311 @end smallexample
13313 @noindent
13314 With the above project file, commands such as
13316 @smallexample
13317    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13318    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13319    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13320    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13321    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13322 @end smallexample
13324 @noindent
13325 will set up the environment properly and invoke the tool with the switches
13326 found in the package corresponding to the tool:
13327 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13328 except @code{^Switches^Switches^ ("main.adb")}
13329 for @code{^gnatlink^gnatlink^}.
13331 @ifclear vms
13332 @node Glide and Project Files
13333 @subsection Glide and Project Files
13335 @noindent
13336 Glide will automatically recognize the @file{.gpr} extension for
13337 project files, and will
13338 convert them to its own internal format automatically. However, it
13339 doesn't provide a syntax-oriented editor for modifying these
13340 files.
13341 The project file will be loaded as text when you select the menu item
13342 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13343 You can edit this text and save the @file{gpr} file;
13344 when you next select this project file in Glide it
13345 will be automatically reloaded.
13346 @end ifclear
13348 @c **********************
13349 @node An Extended Example
13350 @section An Extended Example
13352 @noindent
13353 Suppose that we have two programs, @var{prog1} and @var{prog2},
13354 whose sources are in corresponding directories. We would like
13355 to build them with a single @command{gnatmake} command, and we want to place
13356 their object files into @file{build} subdirectories of the source directories.
13357 Furthermore, we want to have to have two separate subdirectories
13358 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13359 the object files compiled with different set of compilation flags.
13361 In other words, we have the following structure:
13363 @smallexample
13364 @group
13365    main
13366      |- prog1
13367      |    |- build
13368      |         | debug
13369      |         | release
13370      |- prog2
13371           |- build
13372                | debug
13373                | release
13374 @end group
13375 @end smallexample
13377 @noindent
13378 Here are the project files that we must place in a directory @file{main}
13379 to maintain this structure:
13381 @enumerate
13383 @item We create a @code{Common} project with a package @code{Compiler} that
13384 specifies the compilation ^switches^switches^:
13386 @smallexample
13387 File "common.gpr":
13388 @group
13389 @b{project} Common @b{is}
13391    @b{for} Source_Dirs @b{use} (); -- No source files
13392 @end group
13394 @group
13395    @b{type} Build_Type @b{is} ("release", "debug");
13396    Build : Build_Type := External ("BUILD", "debug");
13397 @end group
13398 @group
13399    @b{package} Compiler @b{is}
13400       @b{case} Build @b{is}
13401          @b{when} "release" =>
13402            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13403                    @b{use} ("^-O2^-O2^");
13404          @b{when} "debug"   =>
13405            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13406                    @b{use} ("^-g^-g^");
13407       @b{end case};
13408    @b{end} Compiler;
13410 @b{end} Common;
13411 @end group
13412 @end smallexample
13414 @item We create separate projects for the two programs:
13416 @smallexample
13417 @group
13418 File "prog1.gpr":
13420 @b{with} "common";
13421 @b{project} Prog1 @b{is}
13423     @b{for} Source_Dirs @b{use} ("prog1");
13424     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13426     @b{package} Compiler @b{renames} Common.Compiler;
13428 @b{end} Prog1;
13429 @end group
13430 @end smallexample
13432 @smallexample
13433 @group
13434 File "prog2.gpr":
13436 @b{with} "common";
13437 @b{project} Prog2 @b{is}
13439     @b{for} Source_Dirs @b{use} ("prog2");
13440     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13442     @b{package} Compiler @b{renames} Common.Compiler;
13444 @end group
13445 @b{end} Prog2;
13446 @end smallexample
13448 @item We create a wrapping project @code{Main}:
13450 @smallexample
13451 @group
13452 File "main.gpr":
13454 @b{with} "common";
13455 @b{with} "prog1";
13456 @b{with} "prog2";
13457 @b{project} Main @b{is}
13459    @b{package} Compiler @b{renames} Common.Compiler;
13461 @b{end} Main;
13462 @end group
13463 @end smallexample
13465 @item Finally we need to create a dummy procedure that @code{with}s (either
13466 explicitly or implicitly) all the sources of our two programs.
13468 @end enumerate
13470 @noindent
13471 Now we can build the programs using the command
13473 @smallexample
13474    gnatmake ^-P^/PROJECT_FILE=^main dummy
13475 @end smallexample
13477 @noindent
13478 for the Debug mode, or
13480 @ifclear vms
13481 @smallexample
13482    gnatmake -Pmain -XBUILD=release
13483 @end smallexample
13484 @end ifclear
13486 @ifset vms
13487 @smallexample
13488    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13489 @end smallexample
13490 @end ifset
13492 @noindent
13493 for the Release mode.
13495 @c ********************************
13496 @c * Project File Complete Syntax *
13497 @c ********************************
13499 @node Project File Complete Syntax
13500 @section Project File Complete Syntax
13502 @smallexample
13503 project ::=
13504   context_clause project_declaration
13506 context_clause ::=
13507   @{with_clause@}
13509 with_clause ::=
13510   @b{with} path_name @{ , path_name @} ;
13512 path_name ::=
13513    string_literal
13515 project_declaration ::=
13516   simple_project_declaration | project_extension
13518 simple_project_declaration ::=
13519   @b{project} <project_>simple_name @b{is}
13520     @{declarative_item@}
13521   @b{end} <project_>simple_name;
13523 project_extension ::=
13524   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13525     @{declarative_item@}
13526   @b{end} <project_>simple_name;
13528 declarative_item ::=
13529   package_declaration |
13530   typed_string_declaration |
13531   other_declarative_item
13533 package_declaration ::=
13534   package_specification | package_renaming
13536 package_specification ::=
13537   @b{package} package_identifier @b{is}
13538     @{simple_declarative_item@}
13539   @b{end} package_identifier ;
13541 package_identifier ::=
13542   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13543   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13544   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13546 package_renaming ::==
13547   @b{package} package_identifier @b{renames}
13548        <project_>simple_name.package_identifier ;
13550 typed_string_declaration ::=
13551   @b{type} <typed_string_>_simple_name @b{is}
13552    ( string_literal @{, string_literal@} );
13554 other_declarative_item ::=
13555   attribute_declaration |
13556   typed_variable_declaration |
13557   variable_declaration |
13558   case_construction
13560 attribute_declaration ::=
13561   full_associative_array_declaration |
13562   @b{for} attribute_designator @b{use} expression ;
13564 full_associative_array_declaration ::=
13565   @b{for} <associative_array_attribute_>simple_name @b{use}
13566   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13568 attribute_designator ::=
13569   <simple_attribute_>simple_name |
13570   <associative_array_attribute_>simple_name ( string_literal )
13572 typed_variable_declaration ::=
13573   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13575 variable_declaration ::=
13576   <variable_>simple_name := expression;
13578 expression ::=
13579   term @{& term@}
13581 term ::=
13582   literal_string |
13583   string_list |
13584   <variable_>name |
13585   external_value |
13586   attribute_reference
13588 string_literal ::=
13589   (same as Ada)
13591 string_list ::=
13592   ( <string_>expression @{ , <string_>expression @} )
13594 external_value ::=
13595   @b{external} ( string_literal [, string_literal] )
13597 attribute_reference ::=
13598   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13600 attribute_prefix ::=
13601   @b{project} |
13602   <project_>simple_name | package_identifier |
13603   <project_>simple_name . package_identifier
13605 case_construction ::=
13606   @b{case} <typed_variable_>name @b{is}
13607     @{case_item@}
13608   @b{end case} ;
13610 case_item ::=
13611   @b{when} discrete_choice_list =>
13612       @{case_construction | attribute_declaration@}
13614 discrete_choice_list ::=
13615   string_literal @{| string_literal@} |
13616   @b{others}
13618 name ::=
13619   simple_name @{. simple_name@}
13621 simple_name ::=
13622   identifier (same as Ada)
13624 @end smallexample
13627 @node The Cross-Referencing Tools gnatxref and gnatfind
13628 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13629 @findex gnatxref
13630 @findex gnatfind
13632 @noindent
13633 The compiler generates cross-referencing information (unless
13634 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13635 This information indicates where in the source each entity is declared and
13636 referenced. Note that entities in package Standard are not included, but
13637 entities in all other predefined units are included in the output.
13639 Before using any of these two tools, you need to compile successfully your
13640 application, so that GNAT gets a chance to generate the cross-referencing
13641 information.
13643 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13644 information to provide the user with the capability to easily locate the
13645 declaration and references to an entity. These tools are quite similar,
13646 the difference being that @code{gnatfind} is intended for locating
13647 definitions and/or references to a specified entity or entities, whereas
13648 @code{gnatxref} is oriented to generating a full report of all
13649 cross-references.
13651 To use these tools, you must not compile your application using the
13652 @option{-gnatx} switch on the @file{gnatmake} command line
13653 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13654 information will not be generated.
13656 @menu
13657 * gnatxref Switches::
13658 * gnatfind Switches::
13659 * Project Files for gnatxref and gnatfind::
13660 * Regular Expressions in gnatfind and gnatxref::
13661 * Examples of gnatxref Usage::
13662 * Examples of gnatfind Usage::
13663 @end menu
13665 @node gnatxref Switches
13666 @section @code{gnatxref} Switches
13668 @noindent
13669 The command invocation for @code{gnatxref} is:
13670 @smallexample
13671 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13672 @end smallexample
13674 @noindent
13675 where
13677 @table @code
13678 @item sourcefile1, sourcefile2
13679 identifies the source files for which a report is to be generated. The
13680 ``with''ed units will be processed too. You must provide at least one file.
13682 These file names are considered to be regular expressions, so for instance
13683 specifying @file{source*.adb} is the same as giving every file in the current
13684 directory whose name starts with @file{source} and whose extension is
13685 @file{adb}.
13687 @end table
13689 @noindent
13690 The switches can be :
13691 @table @option
13692 @c !sort!
13693 @item ^-a^/ALL_FILES^
13694 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13695 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13696 the read-only files found in the library search path. Otherwise, these files
13697 will be ignored. This option can be used to protect Gnat sources or your own
13698 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13699 much faster, and their output much smaller. Read-only here refers to access
13700 or permissions status in the file system for the current user.
13702 @item -aIDIR
13703 @cindex @option{-aIDIR} (@command{gnatxref})
13704 When looking for source files also look in directory DIR. The order in which
13705 source file search is undertaken is the same as for @file{gnatmake}.
13707 @item -aODIR
13708 @cindex @option{-aODIR} (@command{gnatxref})
13709 When searching for library and object files, look in directory
13710 DIR. The order in which library files are searched is the same as for
13711 @file{gnatmake}.
13713 @item -nostdinc
13714 @cindex @option{-nostdinc} (@command{gnatxref})
13715 Do not look for sources in the system default directory.
13717 @item -nostdlib
13718 @cindex @option{-nostdlib} (@command{gnatxref})
13719 Do not look for library files in the system default directory.
13721 @item --RTS=@var{rts-path}
13722 @cindex @option{--RTS} (@command{gnatxref})
13723 Specifies the default location of the runtime library. Same meaning as the
13724 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13726 @item ^-d^/DERIVED_TYPES^
13727 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13728 If this switch is set @code{gnatxref} will output the parent type
13729 reference for each matching derived types.
13731 @item ^-f^/FULL_PATHNAME^
13732 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13733 If this switch is set, the output file names will be preceded by their
13734 directory (if the file was found in the search path). If this switch is
13735 not set, the directory will not be printed.
13737 @item ^-g^/IGNORE_LOCALS^
13738 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13739 If this switch is set, information is output only for library-level
13740 entities, ignoring local entities. The use of this switch may accelerate
13741 @code{gnatfind} and @code{gnatxref}.
13743 @item -IDIR
13744 @cindex @option{-IDIR} (@command{gnatxref})
13745 Equivalent to @samp{-aODIR -aIDIR}.
13747 @item -pFILE
13748 @cindex @option{-pFILE} (@command{gnatxref})
13749 Specify a project file to use @xref{Project Files}. These project files are
13750 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13751 project files, you should use gnatxref through the GNAT driver
13752 (@command{gnat xref -Pproject}).
13754 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13755 project file in the current directory.
13757 If a project file is either specified or found by the tools, then the content
13758 of the source directory and object directory lines are added as if they
13759 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13760 and @samp{^-aO^OBJECT_SEARCH^}.
13761 @item ^-u^/UNUSED^
13762 Output only unused symbols. This may be really useful if you give your
13763 main compilation unit on the command line, as @code{gnatxref} will then
13764 display every unused entity and 'with'ed package.
13766 @ifclear vms
13767 @item -v
13768 Instead of producing the default output, @code{gnatxref} will generate a
13769 @file{tags} file that can be used by vi. For examples how to use this
13770 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13771 to the standard output, thus you will have to redirect it to a file.
13772 @end ifclear
13774 @end table
13776 @noindent
13777 All these switches may be in any order on the command line, and may even
13778 appear after the file names. They need not be separated by spaces, thus
13779 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13780 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13782 @node gnatfind Switches
13783 @section @code{gnatfind} Switches
13785 @noindent
13786 The command line for @code{gnatfind} is:
13788 @smallexample
13789 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13790       [file1 file2 ...]
13791 @end smallexample
13793 @noindent
13794 where
13796 @table @code
13797 @item pattern
13798 An entity will be output only if it matches the regular expression found
13799 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13801 Omitting the pattern is equivalent to specifying @samp{*}, which
13802 will match any entity. Note that if you do not provide a pattern, you
13803 have to provide both a sourcefile and a line.
13805 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13806 for matching purposes. At the current time there is no support for
13807 8-bit codes other than Latin-1, or for wide characters in identifiers.
13809 @item sourcefile
13810 @code{gnatfind} will look for references, bodies or declarations
13811 of symbols referenced in @file{sourcefile}, at line @samp{line}
13812 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13813 for syntax examples.
13815 @item line
13816 is a decimal integer identifying the line number containing
13817 the reference to the entity (or entities) to be located.
13819 @item column
13820 is a decimal integer identifying the exact location on the
13821 line of the first character of the identifier for the
13822 entity reference. Columns are numbered from 1.
13824 @item file1 file2 ...
13825 The search will be restricted to these source files. If none are given, then
13826 the search will be done for every library file in the search path.
13827 These file must appear only after the pattern or sourcefile.
13829 These file names are considered to be regular expressions, so for instance
13830 specifying 'source*.adb' is the same as giving every file in the current
13831 directory whose name starts with 'source' and whose extension is 'adb'.
13833 The location of the spec of the entity will always be displayed, even if it
13834 isn't in one of file1, file2,... The occurrences of the entity in the
13835 separate units of the ones given on the command line will also be displayed.
13837 Note that if you specify at least one file in this part, @code{gnatfind} may
13838 sometimes not be able to find the body of the subprograms...
13840 @end table
13842 @noindent
13843 At least one of 'sourcefile' or 'pattern' has to be present on
13844 the command line.
13846 The following switches are available:
13847 @table @option
13848 @c !sort!
13850 @item ^-a^/ALL_FILES^
13851 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13852 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13853 the read-only files found in the library search path. Otherwise, these files
13854 will be ignored. This option can be used to protect Gnat sources or your own
13855 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13856 much faster, and their output much smaller. Read-only here refers to access
13857 or permission status in the file system for the current user.
13859 @item -aIDIR
13860 @cindex @option{-aIDIR} (@command{gnatfind})
13861 When looking for source files also look in directory DIR. The order in which
13862 source file search is undertaken is the same as for @file{gnatmake}.
13864 @item -aODIR
13865 @cindex @option{-aODIR} (@command{gnatfind})
13866 When searching for library and object files, look in directory
13867 DIR. The order in which library files are searched is the same as for
13868 @file{gnatmake}.
13870 @item -nostdinc
13871 @cindex @option{-nostdinc} (@command{gnatfind})
13872 Do not look for sources in the system default directory.
13874 @item -nostdlib
13875 @cindex @option{-nostdlib} (@command{gnatfind})
13876 Do not look for library files in the system default directory.
13878 @item --RTS=@var{rts-path}
13879 @cindex @option{--RTS} (@command{gnatfind})
13880 Specifies the default location of the runtime library. Same meaning as the
13881 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13883 @item ^-d^/DERIVED_TYPE_INFORMATION^
13884 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13885 If this switch is set, then @code{gnatfind} will output the parent type
13886 reference for each matching derived types.
13888 @item ^-e^/EXPRESSIONS^
13889 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13890 By default, @code{gnatfind} accept the simple regular expression set for
13891 @samp{pattern}. If this switch is set, then the pattern will be
13892 considered as full Unix-style regular expression.
13894 @item ^-f^/FULL_PATHNAME^
13895 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13896 If this switch is set, the output file names will be preceded by their
13897 directory (if the file was found in the search path). If this switch is
13898 not set, the directory will not be printed.
13900 @item ^-g^/IGNORE_LOCALS^
13901 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13902 If this switch is set, information is output only for library-level
13903 entities, ignoring local entities. The use of this switch may accelerate
13904 @code{gnatfind} and @code{gnatxref}.
13906 @item -IDIR
13907 @cindex @option{-IDIR} (@command{gnatfind})
13908 Equivalent to @samp{-aODIR -aIDIR}.
13910 @item -pFILE
13911 @cindex @option{-pFILE} (@command{gnatfind})
13912 Specify a project file (@pxref{Project Files}) to use.
13913 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13914 project file in the current directory.
13916 If a project file is either specified or found by the tools, then the content
13917 of the source directory and object directory lines are added as if they
13918 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13919 @samp{^-aO^/OBJECT_SEARCH^}.
13921 @item ^-r^/REFERENCES^
13922 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13923 By default, @code{gnatfind} will output only the information about the
13924 declaration, body or type completion of the entities. If this switch is
13925 set, the @code{gnatfind} will locate every reference to the entities in
13926 the files specified on the command line (or in every file in the search
13927 path if no file is given on the command line).
13929 @item ^-s^/PRINT_LINES^
13930 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13931 If this switch is set, then @code{gnatfind} will output the content
13932 of the Ada source file lines were the entity was found.
13934 @item ^-t^/TYPE_HIERARCHY^
13935 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13936 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13937 the specified type. It act like -d option but recursively from parent
13938 type to parent type. When this switch is set it is not possible to
13939 specify more than one file.
13941 @end table
13943 @noindent
13944 All these switches may be in any order on the command line, and may even
13945 appear after the file names. They need not be separated by spaces, thus
13946 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13947 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13949 As stated previously, gnatfind will search in every directory in the
13950 search path. You can force it to look only in the current directory if
13951 you specify @code{*} at the end of the command line.
13953 @node Project Files for gnatxref and gnatfind
13954 @section Project Files for @command{gnatxref} and @command{gnatfind}
13956 @noindent
13957 Project files allow a programmer to specify how to compile its
13958 application, where to find sources, etc.  These files are used
13959 @ifclear vms
13960 primarily by the Glide Ada mode, but they can also be used
13961 @end ifclear
13962 by the two tools
13963 @code{gnatxref} and @code{gnatfind}.
13965 A project file name must end with @file{.gpr}. If a single one is
13966 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13967 extract the information from it. If multiple project files are found, none of
13968 them is read, and you have to use the @samp{-p} switch to specify the one
13969 you want to use.
13971 The following lines can be included, even though most of them have default
13972 values which can be used in most cases.
13973 The lines can be entered in any order in the file.
13974 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13975 each line. If you have multiple instances, only the last one is taken into
13976 account.
13978 @table @code
13979 @item src_dir=DIR
13980 [default: @code{"^./^[]^"}]
13981 specifies a directory where to look for source files. Multiple @code{src_dir}
13982 lines can be specified and they will be searched in the order they
13983 are specified.
13985 @item obj_dir=DIR
13986 [default: @code{"^./^[]^"}]
13987 specifies a directory where to look for object and library files. Multiple
13988 @code{obj_dir} lines can be specified, and they will be searched in the order
13989 they are specified
13991 @item comp_opt=SWITCHES
13992 [default: @code{""}]
13993 creates a variable which can be referred to subsequently by using
13994 the @code{$@{comp_opt@}} notation. This is intended to store the default
13995 switches given to @command{gnatmake} and @command{gcc}.
13997 @item bind_opt=SWITCHES
13998 [default: @code{""}]
13999 creates a variable which can be referred to subsequently by using
14000 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14001 switches given to @command{gnatbind}.
14003 @item link_opt=SWITCHES
14004 [default: @code{""}]
14005 creates a variable which can be referred to subsequently by using
14006 the @samp{$@{link_opt@}} notation. This is intended to store the default
14007 switches given to @command{gnatlink}.
14009 @item main=EXECUTABLE
14010 [default: @code{""}]
14011 specifies the name of the executable for the application. This variable can
14012 be referred to in the following lines by using the @samp{$@{main@}} notation.
14014 @ifset vms
14015 @item comp_cmd=COMMAND
14016 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14017 @end ifset
14018 @ifclear vms
14019 @item comp_cmd=COMMAND
14020 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14021 @end ifclear
14022 specifies the command used to compile a single file in the application.
14024 @ifset vms
14025 @item make_cmd=COMMAND
14026 [default: @code{"GNAT MAKE $@{main@}
14027 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14028 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14029 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14030 @end ifset
14031 @ifclear vms
14032 @item make_cmd=COMMAND
14033 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14034  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14035  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14036 @end ifclear
14037 specifies the command used to recompile the whole application.
14039 @item run_cmd=COMMAND
14040 [default: @code{"$@{main@}"}]
14041 specifies the command used to run the application.
14043 @item debug_cmd=COMMAND
14044 [default: @code{"gdb $@{main@}"}]
14045 specifies the command used to debug the application
14047 @end table
14049 @noindent
14050 @command{gnatxref} and @command{gnatfind} only take into account the
14051 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14053 @node Regular Expressions in gnatfind and gnatxref
14054 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14056 @noindent
14057 As specified in the section about @command{gnatfind}, the pattern can be a
14058 regular expression. Actually, there are to set of regular expressions
14059 which are recognized by the program :
14061 @table @code
14062 @item globbing patterns
14063 These are the most usual regular expression. They are the same that you
14064 generally used in a Unix shell command line, or in a DOS session.
14066 Here is a more formal grammar :
14067 @smallexample
14068 @group
14069 @iftex
14070 @leftskip=.5cm
14071 @end iftex
14072 regexp ::= term
14073 term   ::= elmt            -- matches elmt
14074 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14075 term   ::= *               -- any string of 0 or more characters
14076 term   ::= ?               -- matches any character
14077 term   ::= [char @{char@}] -- matches any character listed
14078 term   ::= [char - char]   -- matches any character in range
14079 @end group
14080 @end smallexample
14082 @item full regular expression
14083 The second set of regular expressions is much more powerful. This is the
14084 type of regular expressions recognized by utilities such a @file{grep}.
14086 The following is the form of a regular expression, expressed in Ada
14087 reference manual style BNF is as follows
14089 @smallexample
14090 @iftex
14091 @leftskip=.5cm
14092 @end iftex
14093 @group
14094 regexp ::= term @{| term@} -- alternation (term or term ...)
14096 term ::= item @{item@}     -- concatenation (item then item)
14098 item ::= elmt              -- match elmt
14099 item ::= elmt *            -- zero or more elmt's
14100 item ::= elmt +            -- one or more elmt's
14101 item ::= elmt ?            -- matches elmt or nothing
14102 @end group
14103 @group
14104 elmt ::= nschar            -- matches given character
14105 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14106 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14107 elmt ::= [char - char]     -- matches chars in given range
14108 elmt ::= \ char            -- matches given character
14109 elmt ::= .                 -- matches any single character
14110 elmt ::= ( regexp )        -- parens used for grouping
14112 char ::= any character, including special characters
14113 nschar ::= any character except ()[].*+?^^^
14114 @end group
14115 @end smallexample
14117 Following are a few examples :
14119 @table @samp
14120 @item abcde|fghi
14121 will match any of the two strings 'abcde' and 'fghi'.
14123 @item abc*d
14124 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14126 @item [a-z]+
14127 will match any string which has only lowercase characters in it (and at
14128 least one character
14130 @end table
14131 @end table
14133 @node Examples of gnatxref Usage
14134 @section Examples of @code{gnatxref} Usage
14136 @subsection General Usage
14138 @noindent
14139 For the following examples, we will consider the following units :
14141 @smallexample @c ada
14142 @group
14143 @cartouche
14144 main.ads:
14145 1: with Bar;
14146 2: package Main is
14147 3:     procedure Foo (B : in Integer);
14148 4:     C : Integer;
14149 5: private
14150 6:     D : Integer;
14151 7: end Main;
14153 main.adb:
14154 1: package body Main is
14155 2:     procedure Foo (B : in Integer) is
14156 3:     begin
14157 4:        C := B;
14158 5:        D := B;
14159 6:        Bar.Print (B);
14160 7:        Bar.Print (C);
14161 8:     end Foo;
14162 9: end Main;
14164 bar.ads:
14165 1: package Bar is
14166 2:     procedure Print (B : Integer);
14167 3: end bar;
14168 @end cartouche
14169 @end group
14170 @end smallexample
14172 @table @code
14174 @noindent
14175 The first thing to do is to recompile your application (for instance, in
14176 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14177 the cross-referencing information.
14178 You can then issue any of the following commands:
14180 @item gnatxref main.adb
14181 @code{gnatxref} generates cross-reference information for main.adb
14182 and every unit 'with'ed by main.adb.
14184 The output would be:
14185 @smallexample
14186 @iftex
14187 @leftskip=0cm
14188 @end iftex
14189 B                                                      Type: Integer
14190   Decl: bar.ads           2:22
14191 B                                                      Type: Integer
14192   Decl: main.ads          3:20
14193   Body: main.adb          2:20
14194   Ref:  main.adb          4:13     5:13     6:19
14195 Bar                                                    Type: Unit
14196   Decl: bar.ads           1:9
14197   Ref:  main.adb          6:8      7:8
14198        main.ads           1:6
14199 C                                                      Type: Integer
14200   Decl: main.ads          4:5
14201   Modi: main.adb          4:8
14202   Ref:  main.adb          7:19
14203 D                                                      Type: Integer
14204   Decl: main.ads          6:5
14205   Modi: main.adb          5:8
14206 Foo                                                    Type: Unit
14207   Decl: main.ads          3:15
14208   Body: main.adb          2:15
14209 Main                                                    Type: Unit
14210   Decl: main.ads          2:9
14211   Body: main.adb          1:14
14212 Print                                                   Type: Unit
14213   Decl: bar.ads           2:15
14214   Ref:  main.adb          6:12     7:12
14215 @end smallexample
14217 @noindent
14218 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14219 its body is in main.adb, line 1, column 14 and is not referenced any where.
14221 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14222 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14224 @item gnatxref package1.adb package2.ads
14225 @code{gnatxref} will generates cross-reference information for
14226 package1.adb, package2.ads and any other package 'with'ed by any
14227 of these.
14229 @end table
14231 @ifclear vms
14232 @subsection Using gnatxref with vi
14234 @code{gnatxref} can generate a tags file output, which can be used
14235 directly from @file{vi}. Note that the standard version of @file{vi}
14236 will not work properly with overloaded symbols. Consider using another
14237 free implementation of @file{vi}, such as @file{vim}.
14239 @smallexample
14240 $ gnatxref -v gnatfind.adb > tags
14241 @end smallexample
14243 @noindent
14244 will generate the tags file for @code{gnatfind} itself (if the sources
14245 are in the search path!).
14247 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14248 (replacing @i{entity} by whatever you are looking for), and vi will
14249 display a new file with the corresponding declaration of entity.
14250 @end ifclear
14252 @node Examples of gnatfind Usage
14253 @section Examples of @code{gnatfind} Usage
14255 @table @code
14257 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14258 Find declarations for all entities xyz referenced at least once in
14259 main.adb. The references are search in every library file in the search
14260 path.
14262 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14263 switch is set)
14265 The output will look like:
14266 @smallexample
14267 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14268 ^directory/^[directory]^main.adb:24:10: xyz <= body
14269 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14270 @end smallexample
14272 @noindent
14273 that is to say, one of the entities xyz found in main.adb is declared at
14274 line 12 of main.ads (and its body is in main.adb), and another one is
14275 declared at line 45 of foo.ads
14277 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14278 This is the same command as the previous one, instead @code{gnatfind} will
14279 display the content of the Ada source file lines.
14281 The output will look like:
14283 @smallexample
14284 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14285    procedure xyz;
14286 ^directory/^[directory]^main.adb:24:10: xyz <= body
14287    procedure xyz is
14288 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14289    xyz : Integer;
14290 @end smallexample
14292 @noindent
14293 This can make it easier to find exactly the location your are looking
14294 for.
14296 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14297 Find references to all entities containing an x that are
14298 referenced on line 123 of main.ads.
14299 The references will be searched only in main.ads and foo.adb.
14301 @item gnatfind main.ads:123
14302 Find declarations and bodies for all entities that are referenced on
14303 line 123 of main.ads.
14305 This is the same as @code{gnatfind "*":main.adb:123}.
14307 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14308 Find the declaration for the entity referenced at column 45 in
14309 line 123 of file main.adb in directory mydir. Note that it
14310 is usual to omit the identifier name when the column is given,
14311 since the column position identifies a unique reference.
14313 The column has to be the beginning of the identifier, and should not
14314 point to any character in the middle of the identifier.
14316 @end table
14319 @c *********************************
14320 @node The GNAT Pretty-Printer gnatpp
14321 @chapter The GNAT Pretty-Printer @command{gnatpp}
14322 @findex gnatpp
14323 @cindex Pretty-Printer
14325 @noindent
14326 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14327 for source reformatting / pretty-printing.
14328 It takes an Ada source file as input and generates a reformatted
14329 version as output.
14330 You can specify various style directives via switches; e.g.,
14331 identifier case conventions, rules of indentation, and comment layout.
14333 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14334 tree for the input source and thus requires the input to be syntactically and
14335 semantically legal.
14336 If this condition is not met, @command{gnatpp} will terminate with an
14337 error message; no output file will be generated.
14339 If the compilation unit
14340 contained in the input source depends semantically upon units located
14341 outside the current directory, you have to provide the source search path
14342 when invoking @command{gnatpp}; see the description of the @command{gnatpp}
14343 switches below.
14345 The @command{gnatpp} command has the form
14347 @smallexample
14348 $ gnatpp [@var{switches}] @var{filename}
14349 @end smallexample
14351 @noindent
14352 where
14353 @itemize @bullet
14354 @item
14355 @var{switches} is an optional sequence of switches defining such properties as
14356 the formatting rules, the source search path, and the destination for the
14357 output source file
14359 @item
14360 @var{filename} is the name (including the extension) of the source file to
14361 reformat; ``wildcards'' or several file names on the same gnatpp command are
14362 allowed.  The file name may contain path information; it does not have to follow
14363 the GNAT file naming rules
14364 @end itemize
14367 @menu
14368 * Switches for gnatpp::
14369 * Formatting Rules::
14370 @end menu
14372 @node Switches for gnatpp
14373 @section Switches for @command{gnatpp}
14375 @noindent
14376 The following subsections describe the various switches accepted by
14377 @command{gnatpp}, organized by category.
14379 @ifclear vms
14380 You specify a switch by supplying a name and generally also a value.
14381 In many cases the values for a switch with a given name are incompatible with
14382 each other
14383 (for example the switch that controls the casing of a reserved word may have
14384 exactly one value: upper case, lower case, or
14385 mixed case) and thus exactly one such switch can be in effect for an
14386 invocation of @command{gnatpp}.
14387 If more than one is supplied, the last one is used.
14388 However, some values for the same switch are mutually compatible.
14389 You may supply several such switches to @command{gnatpp}, but then
14390 each must be specified in full, with both the name and the value.
14391 Abbreviated forms (the name appearing once, followed by each value) are
14392 not permitted.
14393 For example, to set
14394 the alignment of the assignment delimiter both in declarations and in
14395 assignment statements, you must write @option{-A2A3}
14396 (or @option{-A2 -A3}), but not @option{-A23}.
14397 @end ifclear
14399 @ifset vms
14400 In many cases the set of options for a given qualifier are incompatible with
14401 each other (for example the qualifier that controls the casing of a reserved
14402 word may have exactly one option, which specifies either upper case, lower
14403 case, or mixed case), and thus exactly one such option can be in effect for
14404 an invocation of @command{gnatpp}.
14405 If more than one is supplied, the last one is used.
14406 However, some qualifiers have options that are mutually compatible,
14407 and then you may then supply several such options when invoking
14408 @command{gnatpp}.
14409 @end ifset
14411 In most cases, it is obvious whether or not the
14412 ^values for a switch with a given name^options for a given qualifier^
14413 are compatible with each other.
14414 When the semantics might not be evident, the summaries below explicitly
14415 indicate the effect.
14417 @menu
14418 * Alignment Control::
14419 * Casing Control::
14420 * Construct Layout Control::
14421 * General Text Layout Control::
14422 * Other Formatting Options::
14423 * Setting the Source Search Path::
14424 * Output File Control::
14425 * Other gnatpp Switches::
14426 @end menu
14429 @node Alignment Control
14430 @subsection Alignment Control
14431 @cindex Alignment control in @command{gnatpp}
14433 @noindent
14434 Programs can be easier to read if certain constructs are vertically aligned.
14435 By default all alignments are set ON.
14436 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14437 OFF, and then use one or more of the other
14438 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14439 to activate alignment for specific constructs.
14441 @table @option
14442 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14444 @ifset vms
14445 @item /ALIGN=ON
14446 Set all alignments to ON
14447 @end ifset
14449 @item ^-A0^/ALIGN=OFF^
14450 Set all alignments to OFF
14452 @item ^-A1^/ALIGN=COLONS^
14453 Align @code{:} in declarations
14455 @item ^-A2^/ALIGN=DECLARATIONS^
14456 Align @code{:=} in initializations in declarations
14458 @item ^-A3^/ALIGN=STATEMENTS^
14459 Align @code{:=} in assignment statements
14461 @item ^-A4^/ALIGN=ARROWS^
14462 Align @code{=>} in associations
14463 @end table
14465 @noindent
14466 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14467 is allowed.
14470 @node Casing Control
14471 @subsection Casing Control
14472 @cindex Casing control in @command{gnatpp}
14474 @noindent
14475 @command{gnatpp} allows you to specify the casing for reserved words,
14476 pragma names, attribute designators and identifiers.
14477 For identifiers you may define a
14478 general rule for name casing but also override this rule
14479 via a set of dictionary files.
14481 Three types of casing are supported: lower case, upper case, and mixed case.
14482 Lower and upper case are self-explanatory (but since some letters in
14483 Latin1 and other GNAT-supported character sets
14484 exist only in lower-case form, an upper case conversion will have no
14485 effect on them.)
14486 ``Mixed case'' means that the first letter, and also each letter immediately
14487 following an underscore, are converted to their uppercase forms;
14488 all the other letters are converted to their lowercase forms.
14490 @table @option
14491 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14492 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14493 Attribute designators are lower case
14495 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14496 Attribute designators are upper case
14498 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14499 Attribute designators are mixed case (this is the default)
14501 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14502 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14503 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14504 lower case (this is the default)
14506 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14507 Keywords are upper case
14509 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14510 @item ^-nD^/NAME_CASING=AS_DECLARED^
14511 Name casing for defining occurrences are as they appear in the source file
14512 (this is the default)
14514 @item ^-nU^/NAME_CASING=UPPER_CASE^
14515 Names are in upper case
14517 @item ^-nL^/NAME_CASING=LOWER_CASE^
14518 Names are in lower case
14520 @item ^-nM^/NAME_CASING=MIXED_CASE^
14521 Names are in mixed case
14523 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14524 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14525 Pragma names are lower case
14527 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14528 Pragma names are upper case
14530 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14531 Pragma names are mixed case (this is the default)
14533 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14534 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14535 Use @var{file} as a @emph{dictionary file} that defines
14536 the casing for a set of specified names,
14537 thereby overriding the effect on these names by
14538 any explicit or implicit
14539 ^-n^/NAME_CASING^ switch.
14540 To supply more than one dictionary file,
14541 use ^several @option{-D} switches^a list of files as options^.
14543 @noindent
14544 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14545 to define the casing for the Ada predefined names and
14546 the names declared in the GNAT libraries.
14548 @item ^-D-^/SPECIFIC_CASING^
14549 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14550 Do not use the default dictionary file;
14551 instead, use the casing
14552 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14553 dictionary file(s)
14554 @end table
14556 @noindent
14557 The structure of a dictionary file, and details on the conventions
14558 used in the default dictionary file, are defined in @ref{Name Casing}.
14560 The @option{^-D-^/SPECIFIC_CASING^} and
14561 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14562 compatible.
14565 @node Construct Layout Control
14566 @subsection Construct Layout Control
14567 @cindex Layout control in @command{gnatpp}
14569 @noindent
14570 This group of @command{gnatpp} switches controls the layout of comments and
14571 complex syntactic constructs.  See @ref{Formatting Comments}, for details
14572 on their effect.
14574 @table @option
14575 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14576 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14577 GNAT-style comment line indentation (this is the default).
14579 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14580 Reference-manual comment line indentation.
14582 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14583 GNAT-style comment beginning
14585 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14586 Reformat comment blocks
14588 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14589 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14590 GNAT-style layout (this is the default)
14592 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14593 Compact layout
14595 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14596 Uncompact layout
14598 @item ^-notab^/NOTABS^
14599 All the VT characters are removed from the comment text. All the HT characters are
14600 expanded with the sequences of space characters to get to the next tab stops.
14602 @end table
14604 @ifclear vms
14605 @noindent
14606 The @option{-c1} and @option{-c2} switches are incompatible.
14607 The @option{-c3} and @option{-c4} switches are compatible with each other and
14608 also with @option{-c1} and @option{-c2}.
14610 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14611 @end ifclear
14613 @ifset vms
14614 @noindent
14615 For the @option{/COMMENTS_LAYOUT} qualifier:
14616 @itemize @bullet
14617 @item
14618 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14619 @item
14620 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14621 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14622 @end itemize
14624 @noindent
14625 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14626 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14627 @end ifset
14629 @node General Text Layout Control
14630 @subsection General Text Layout Control
14632 @noindent
14633 These switches allow control over line length and indentation.
14635 @table @option
14636 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14637 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14638 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14640 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14641 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14642 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14644 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14645 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14646 Indentation level for continuation lines (relative to the line being
14647 continued), @i{nnn} from 1 .. 9.
14648 The default
14649 value is one less then the (normal) indentation level, unless the
14650 indentation is set to 1 (in which case the default value for continuation
14651 line indentation is also 1)
14652 @end table
14655 @node Other Formatting Options
14656 @subsection Other Formatting Options
14658 @noindent
14659 These switches control the inclusion of missing end/exit labels, and
14660 the indentation level in @b{case} statements.
14662 @table @option
14663 @item ^-e^/NO_MISSED_LABELS^
14664 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14665 Do not insert missing end/exit labels. An end label is the name of
14666 a construct that may optionally be repeated at the end of the
14667 construct's declaration;
14668 e.g., the names of packages, subprograms, and tasks.
14669 An exit label is the name of a loop that may appear as target
14670 of an exit statement within the loop.
14671 By default, @command{gnatpp} inserts these end/exit labels when
14672 they are absent from the original source. This option suppresses such
14673 insertion, so that the formatted source reflects the original.
14675 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14676 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14677 Insert a Form Feed character after a pragma Page.
14679 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14680 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14681 Do not use an additional indentation level for @b{case} alternatives
14682 and variants if there are @i{nnn} or more (the default
14683 value is 10).
14684 If @i{nnn} is 0, an additional indentation level is
14685 used for @b{case} alternatives and variants regardless of their number.
14686 @end table
14688 @node Setting the Source Search Path
14689 @subsection Setting the Source Search Path
14691 @noindent
14692 To define the search path for the input source file, @command{gnatpp}
14693 uses the same switches as the GNAT compiler, with the same effects.
14695 @table @option
14696 @item ^-I^/SEARCH=^@var{dir}
14697 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14698 The same as the corresponding gcc switch
14700 @item ^-I-^/NOCURRENT_DIRECTORY^
14701 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14702 The same as the corresponding gcc switch
14704 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14705 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14706 The same as the corresponding gcc switch
14708 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14709 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14710 The same as the corresponding gcc switch
14712 @end table
14715 @node Output File Control
14716 @subsection Output File Control
14718 @noindent
14719 By default the output is sent to the file whose name is obtained by appending
14720 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14721 (if the file with this name already exists, it is unconditionally overwritten).
14722 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14723 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14724 as output file.
14725 The output may be redirected by the following switches:
14727 @table @option
14728 @item ^-pipe^/STANDARD_OUTPUT^
14729 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14730 Send the output to @code{Standard_Output}
14732 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14733 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14734 Write the output into @var{output_file}.
14735 If @var{output_file} already exists, @command{gnatpp} terminates without
14736 reading or processing the input file.
14738 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14739 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14740 Write the output into @var{output_file}, overwriting the existing file
14741 (if one is present).
14743 @item ^-r^/REPLACE^
14744 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14745 Replace the input source file with the reformatted output, and copy the
14746 original input source into the file whose name is obtained by appending the
14747 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14748 If a file with this name already exists, @command{gnatpp} terminates without
14749 reading or processing the input file.
14751 @item ^-rf^/OVERRIDING_REPLACE^
14752 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14753 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14754 already exists, it is overwritten.
14755 @end table
14757 @noindent
14758 Options @option{^-pipe^/STANDARD_OUTPUT^},
14759 @option{^-o^/OUTPUT^} and
14760 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14761 contains only one file to reformat
14763 @node Other gnatpp Switches
14764 @subsection Other @code{gnatpp} Switches
14766 @noindent
14767 The additional @command{gnatpp} switches are defined in this subsection.
14769 @table @option
14770 @item ^-v^/VERBOSE^
14771 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14772 Verbose mode;
14773 @command{gnatpp} generates version information and then
14774 a trace of the actions it takes to produce or obtain the ASIS tree.
14776 @item ^-w^/WARNINGS^
14777 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14778 Warning mode;
14779 @command{gnatpp} generates a warning whenever it can not provide
14780 a required layout in the result source.
14781 @end table
14784 @node Formatting Rules
14785 @section Formatting Rules
14787 @noindent
14788 The following subsections show how @command{gnatpp} treats ``white space'',
14789 comments, program layout, and name casing.
14790 They provide the detailed descriptions of the switches shown above.
14792 @menu
14793 * White Space and Empty Lines::
14794 * Formatting Comments::
14795 * Construct Layout::
14796 * Name Casing::
14797 @end menu
14800 @node White Space and Empty Lines
14801 @subsection White Space and Empty Lines
14803 @noindent
14804 @command{gnatpp} does not have an option to control space characters.
14805 It will add or remove spaces according to the style illustrated by the
14806 examples in the @cite{Ada Reference Manual}.
14808 The only format effectors
14809 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14810 that will appear in the output file are platform-specific line breaks,
14811 and also format effectors within (but not at the end of) comments.
14812 In particular, each horizontal tab character that is not inside
14813 a comment will be treated as a space and thus will appear in the
14814 output file as zero or more spaces depending on
14815 the reformatting of the line in which it appears.
14816 The only exception is a Form Feed character, which is inserted after a
14817 pragma @code{Page} when @option{-ff} is set.
14819 The output file will contain no lines with trailing ``white space'' (spaces,
14820 format effectors).
14822 Empty lines in the original source are preserved
14823 only if they separate declarations or statements.
14824 In such contexts, a
14825 sequence of two or more empty lines is replaced by exactly one empty line.
14826 Note that a blank line will be removed if it separates two ``comment blocks''
14827 (a comment block is a sequence of whole-line comments).
14828 In order to preserve a visual separation between comment blocks, use an
14829 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14830 Likewise, if for some reason you wish to have a sequence of empty lines,
14831 use a sequence of empty comments instead.
14834 @node Formatting Comments
14835 @subsection Formatting Comments
14837 @noindent
14838 Comments in Ada code are of two kinds:
14839 @itemize @bullet
14840 @item
14841 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14842 ``white space'') on a line
14844 @item
14845 an @emph{end-of-line comment}, which follows some other Ada lexical element
14846 on the same line.
14847 @end itemize
14849 @noindent
14850 The indentation of a whole-line comment is that of either
14851 the preceding or following line in
14852 the formatted source, depending on switch settings as will be described below.
14854 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14855 between the end of the preceding Ada lexical element and the beginning
14856 of the comment as appear in the original source,
14857 unless either the comment has to be split to
14858 satisfy the line length limitation, or else the next line contains a
14859 whole line comment that is considered a continuation of this end-of-line
14860 comment (because it starts at the same position).
14861 In the latter two
14862 cases, the start of the end-of-line comment is moved right to the nearest
14863 multiple of the indentation level.
14864 This may result in a ``line overflow'' (the right-shifted comment extending
14865 beyond the maximum line length), in which case the comment is split as
14866 described below.
14868 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14869 (GNAT-style comment line indentation)
14870 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14871 (reference-manual comment line indentation).
14872 With reference-manual style, a whole-line comment is indented as if it
14873 were a declaration or statement at the same place
14874 (i.e., according to the indentation of the preceding line(s)).
14875 With GNAT style, a whole-line comment that is immediately followed by an
14876 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14877 word @b{begin}, is indented based on the construct that follows it.
14879 For example:
14880 @smallexample @c ada
14881 @cartouche
14882 if A then
14883     null;
14884        -- some comment
14885 else
14886    null;
14887 end if;
14888 @end cartouche
14889 @end smallexample
14891 @noindent
14892 Reference-manual indentation produces:
14894 @smallexample @c ada
14895 @cartouche
14896 if A then
14897    null;
14898    --  some comment
14899 else
14900    null;
14901 end if;
14902 @end cartouche
14903 @end smallexample
14905 @noindent
14906 while GNAT-style indentation produces:
14908 @smallexample @c ada
14909 @cartouche
14910 if A then
14911    null;
14912 --  some comment
14913 else
14914    null;
14915 end if;
14916 @end cartouche
14917 @end smallexample
14919 @noindent
14920 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14921 (GNAT style comment beginning) has the following
14922 effect:
14924 @itemize @bullet
14925 @item
14926 For each whole-line comment that does not end with two hyphens,
14927 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14928 to ensure that there are at least two spaces between these hyphens and the
14929 first non-blank character of the comment.
14930 @end itemize
14932 @noindent
14933 For an end-of-line comment, if in the original source the next line is a
14934 whole-line comment that starts at the same position
14935 as the end-of-line comment,
14936 then the whole-line comment (and all whole-line comments
14937 that follow it and that start at the same position)
14938 will start at this position in the output file.
14940 @noindent
14941 That is, if in the original source we have:
14943 @smallexample @c ada
14944 @cartouche
14945 begin
14946 A := B + C;            --  B must be in the range Low1..High1
14947                        --  C must be in the range Low2..High2
14948              --B+C will be in the range Low1+Low2..High1+High2
14949 X := X + 1;
14950 @end cartouche
14951 @end smallexample
14953 @noindent
14954 Then in the formatted source we get
14956 @smallexample @c ada
14957 @cartouche
14958 begin
14959    A := B + C;            --  B must be in the range Low1..High1
14960                           --  C must be in the range Low2..High2
14961    --  B+C will be in the range Low1+Low2..High1+High2
14962    X := X + 1;
14963 @end cartouche
14964 @end smallexample
14966 @noindent
14967 A comment that exceeds the line length limit will be split.
14968 Unless switch
14969 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14970 the line belongs to a reformattable block, splitting the line generates a
14971 @command{gnatpp} warning.
14972 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14973 comments may be reformatted in typical
14974 word processor style (that is, moving words between lines and putting as
14975 many words in a line as possible).
14978 @node Construct Layout
14979 @subsection Construct Layout
14981 @noindent
14982 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14983 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14984 layout on the one hand, and uncompact layout
14985 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14986 can be illustrated by the following examples:
14988 @iftex
14989 @cartouche
14990 @multitable @columnfractions .5 .5
14991 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14993 @item
14994 @smallexample @c ada
14995 type q is record
14996    a : integer;
14997    b : integer;
14998 end record;
14999 @end smallexample
15000 @tab
15001 @smallexample @c ada
15002 type q is
15003    record
15004       a : integer;
15005       b : integer;
15006    end record;
15007 @end smallexample
15009 @item
15010 @smallexample @c ada
15011 Block : declare
15012    A : Integer := 3;
15013 begin
15014    Proc (A, A);
15015 end Block;
15016 @end smallexample
15017 @tab
15018 @smallexample @c ada
15019 Block :
15020    declare
15021       A : Integer := 3;
15022    begin
15023       Proc (A, A);
15024    end Block;
15025 @end smallexample
15027 @item
15028 @smallexample @c ada
15029 Clear : for J in 1 .. 10 loop
15030    A (J) := 0;
15031 end loop Clear;
15032 @end smallexample
15033 @tab
15034 @smallexample @c ada
15035 Clear :
15036    for J in 1 .. 10 loop
15037       A (J) := 0;
15038    end loop Clear;
15039 @end smallexample
15040 @end multitable
15041 @end cartouche
15042 @end iftex
15044 @ifnottex
15045 @smallexample
15046 @cartouche
15047 GNAT style, compact layout              Uncompact layout
15049 type q is record                        type q is
15050    a : integer;                            record
15051    b : integer;                               a : integer;
15052 end record;                                   b : integer;
15053                                            end record;
15056 Block : declare                         Block :
15057    A : Integer := 3;                       declare
15058 begin                                         A : Integer := 3;
15059    Proc (A, A);                            begin
15060 end Block;                                    Proc (A, A);
15061                                            end Block;
15063 Clear : for J in 1 .. 10 loop           Clear :
15064    A (J) := 0;                             for J in 1 .. 10 loop
15065 end loop Clear;                               A (J) := 0;
15066                                            end loop Clear;
15067 @end cartouche
15068 @end smallexample
15069 @end ifnottex
15071 @noindent
15072 A further difference between GNAT style layout and compact layout is that
15073 GNAT style layout inserts empty lines as separation for
15074 compound statements, return statements and bodies.
15077 @node Name Casing
15078 @subsection Name Casing
15080 @noindent
15081 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15082 the same casing as the corresponding defining identifier.
15084 You control the casing for defining occurrences via the
15085 @option{^-n^/NAME_CASING^} switch.
15086 @ifclear vms
15087 With @option{-nD} (``as declared'', which is the default),
15088 @end ifclear
15089 @ifset vms
15090 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15091 @end ifset
15092 defining occurrences appear exactly as in the source file
15093 where they are declared.
15094 The other ^values for this switch^options for this qualifier^ ---
15095 @option{^-nU^UPPER_CASE^},
15096 @option{^-nL^LOWER_CASE^},
15097 @option{^-nM^MIXED_CASE^} ---
15098 result in
15099 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15100 If @command{gnatpp} changes the casing of a defining
15101 occurrence, it analogously changes the casing of all the
15102 usage occurrences of this name.
15104 If the defining occurrence of a name is not in the source compilation unit
15105 currently being processed by @command{gnatpp}, the casing of each reference to
15106 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15107 switch (subject to the dictionary file mechanism described below).
15108 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15109 had affected the
15110 casing for the defining occurrence of the name.
15112 Some names may need to be spelled with casing conventions that are not
15113 covered by the upper-, lower-, and mixed-case transformations.
15114 You can arrange correct casing by placing such names in a
15115 @emph{dictionary file},
15116 and then supplying a @option{^-D^/DICTIONARY^} switch.
15117 The casing of names from dictionary files overrides
15118 any @option{^-n^/NAME_CASING^} switch.
15120 To handle the casing of Ada predefined names and the names from GNAT libraries,
15121 @command{gnatpp} assumes a default dictionary file.
15122 The name of each predefined entity is spelled with the same casing as is used
15123 for the entity in the @cite{Ada Reference Manual}.
15124 The name of each entity in the GNAT libraries is spelled with the same casing
15125 as is used in the declaration of that entity.
15127 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15128 default dictionary file.
15129 Instead, the casing for predefined and GNAT-defined names will be established
15130 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15131 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15132 will appear as just shown,
15133 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15134 To ensure that even such names are rendered in uppercase,
15135 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15136 (or else, less conveniently, place these names in upper case in a dictionary
15137 file).
15139 A dictionary file is
15140 a plain text file; each line in this file can be either a blank line
15141 (containing only space characters and ASCII.HT characters), an Ada comment
15142 line, or the specification of exactly one @emph{casing schema}.
15144 A casing schema is a string that has the following syntax:
15146 @smallexample
15147 @cartouche
15148   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15150   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15151 @end cartouche
15152 @end smallexample
15154 @noindent
15155 (The @code{[]} metanotation stands for an optional part;
15156 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15157 @var{identifier} lexical element and the @var{letter_or_digit} category).
15159 The casing schema string can be followed by white space and/or an Ada-style
15160 comment; any amount of white space is allowed before the string.
15162 If a dictionary file is passed as
15163 @ifclear vms
15164 the value of a @option{-D@var{file}} switch
15165 @end ifclear
15166 @ifset vms
15167 an option to the @option{/DICTIONARY} qualifier
15168 @end ifset
15169 then for every
15170 simple name and every identifier, @command{gnatpp} checks if the dictionary
15171 defines the casing for the name or for some of its parts (the term ``subword''
15172 is used below to denote the part of a name which is delimited by ``_'' or by
15173 the beginning or end of the word and which does not contain any ``_'' inside):
15175 @itemize @bullet
15176 @item
15177 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15178 the casing defined by the dictionary; no subwords are checked for this word
15180 @item
15181 for the first subword (that is, for the subword preceding the leftmost
15182 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15183 string of the form @code{@var{simple_identifier}*}, and if it does, the
15184 casing of this @var{simple_identifier} is used for this subword
15186 @item
15187 for the last subword (following the rightmost ``_'') @command{gnatpp}
15188 checks if the dictionary contains the corresponding string of the form
15189 @code{*@var{simple_identifier}}, and if it does, the casing of this
15190 @var{simple_identifier} is used for this subword
15192 @item
15193 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15194 if the dictionary contains the corresponding string of the form
15195 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15196 simple_identifier is used for this subword
15198 @item
15199 if more than one dictionary file is passed as @command{gnatpp} switches, each
15200 dictionary adds new casing exceptions and overrides all the existing casing
15201 exceptions set by the previous dictionaries
15203 @item
15204 when @command{gnatpp} checks if the word or subword is in the dictionary,
15205 this check is not case sensitive
15206 @end itemize
15208 @noindent
15209 For example, suppose we have the following source to reformat:
15211 @smallexample @c ada
15212 @cartouche
15213 procedure test is
15214    name1 : integer := 1;
15215    name4_name3_name2 : integer := 2;
15216    name2_name3_name4 : Boolean;
15217    name1_var : Float;
15218 begin
15219    name2_name3_name4 := name4_name3_name2 > name1;
15220 end;
15221 @end cartouche
15222 @end smallexample
15224 @noindent
15225 And suppose we have two dictionaries:
15227 @smallexample
15228 @cartouche
15229 @i{dict1:}
15230    NAME1
15231    *NaMe3*
15232    *NAME2
15233 @end cartouche
15235 @cartouche
15236 @i{dict2:}
15237   *NAME3*
15238 @end cartouche
15239 @end smallexample
15241 @noindent
15242 If @command{gnatpp} is called with the following switches:
15244 @smallexample
15245 @ifclear vms
15246 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15247 @end ifclear
15248 @ifset vms
15249 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15250 @end ifset
15251 @end smallexample
15253 @noindent
15254 then we will get the following name casing in the @command{gnatpp} output:
15256 @smallexample @c ada
15257 @cartouche
15258 procedure Test is
15259    NAME1             : Integer := 1;
15260    Name4_NAME3_NAME2 : integer := 2;
15261    Name2_NAME3_Name4 : Boolean;
15262    Name1_Var         : Float;
15263 begin
15264    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15265 end Test;
15266 @end cartouche
15267 @end smallexample
15271 @c ***********************************
15272 @node File Name Krunching Using gnatkr
15273 @chapter File Name Krunching Using @code{gnatkr}
15274 @findex gnatkr
15276 @noindent
15277 This chapter discusses the method used by the compiler to shorten
15278 the default file names chosen for Ada units so that they do not
15279 exceed the maximum length permitted. It also describes the
15280 @code{gnatkr} utility that can be used to determine the result of
15281 applying this shortening.
15282 @menu
15283 * About gnatkr::
15284 * Using gnatkr::
15285 * Krunching Method::
15286 * Examples of gnatkr Usage::
15287 @end menu
15289 @node About gnatkr
15290 @section About @code{gnatkr}
15292 @noindent
15293 The default file naming rule in GNAT
15294 is that the file name must be derived from
15295 the unit name. The exact default rule is as follows:
15296 @itemize @bullet
15297 @item
15298 Take the unit name and replace all dots by hyphens.
15299 @item
15300 If such a replacement occurs in the
15301 second character position of a name, and the first character is
15302 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15303 ^~ (tilde)^$ (dollar sign)^
15304 instead of a minus.
15305 @end itemize
15306 The reason for this exception is to avoid clashes
15307 with the standard names for children of System, Ada, Interfaces,
15308 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15309 respectively.
15311 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15312 switch of the compiler activates a ``krunching''
15313 circuit that limits file names to nn characters (where nn is a decimal
15314 integer). For example, using OpenVMS,
15315 where the maximum file name length is
15316 39, the value of nn is usually set to 39, but if you want to generate
15317 a set of files that would be usable if ported to a system with some
15318 different maximum file length, then a different value can be specified.
15319 The default value of 39 for OpenVMS need not be specified.
15321 The @code{gnatkr} utility can be used to determine the krunched name for
15322 a given file, when krunched to a specified maximum length.
15324 @node Using gnatkr
15325 @section Using @code{gnatkr}
15327 @noindent
15328 The @code{gnatkr} command has the form
15330 @ifclear vms
15331 @smallexample
15332 $ gnatkr @var{name} [@var{length}]
15333 @end smallexample
15334 @end ifclear
15336 @ifset vms
15337 @smallexample
15338 $ gnatkr @var{name} /COUNT=nn
15339 @end smallexample
15340 @end ifset
15342 @noindent
15343 @var{name} is the uncrunched file name, derived from the name of the unit
15344 in the standard manner described in the previous section (i.e. in particular
15345 all dots are replaced by hyphens). The file name may or may not have an
15346 extension (defined as a suffix of the form period followed by arbitrary
15347 characters other than period). If an extension is present then it will
15348 be preserved in the output. For example, when krunching @file{hellofile.ads}
15349 to eight characters, the result will be hellofil.ads.
15351 Note: for compatibility with previous versions of @code{gnatkr} dots may
15352 appear in the name instead of hyphens, but the last dot will always be
15353 taken as the start of an extension. So if @code{gnatkr} is given an argument
15354 such as @file{Hello.World.adb} it will be treated exactly as if the first
15355 period had been a hyphen, and for example krunching to eight characters
15356 gives the result @file{hellworl.adb}.
15358 Note that the result is always all lower case (except on OpenVMS where it is
15359 all upper case). Characters of the other case are folded as required.
15361 @var{length} represents the length of the krunched name. The default
15362 when no argument is given is ^8^39^ characters. A length of zero stands for
15363 unlimited, in other words do not chop except for system files where the
15364 impled crunching length is always eight characters.
15366 @noindent
15367 The output is the krunched name. The output has an extension only if the
15368 original argument was a file name with an extension.
15370 @node Krunching Method
15371 @section Krunching Method
15373 @noindent
15374 The initial file name is determined by the name of the unit that the file
15375 contains. The name is formed by taking the full expanded name of the
15376 unit and replacing the separating dots with hyphens and
15377 using ^lowercase^uppercase^
15378 for all letters, except that a hyphen in the second character position is
15379 replaced by a ^tilde^dollar sign^ if the first character is
15380 ^a, i, g, or s^A, I, G, or S^.
15381 The extension is @code{.ads} for a
15382 specification and @code{.adb} for a body.
15383 Krunching does not affect the extension, but the file name is shortened to
15384 the specified length by following these rules:
15386 @itemize @bullet
15387 @item
15388 The name is divided into segments separated by hyphens, tildes or
15389 underscores and all hyphens, tildes, and underscores are
15390 eliminated. If this leaves the name short enough, we are done.
15392 @item
15393 If the name is too long, the longest segment is located (left-most
15394 if there are two of equal length), and shortened by dropping
15395 its last character. This is repeated until the name is short enough.
15397 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15398 to fit the name into 8 characters as required by some operating systems.
15400 @smallexample
15401 our-strings-wide_fixed 22
15402 our strings wide fixed 19
15403 our string  wide fixed 18
15404 our strin   wide fixed 17
15405 our stri    wide fixed 16
15406 our stri    wide fixe  15
15407 our str     wide fixe  14
15408 our str     wid  fixe  13
15409 our str     wid  fix   12
15410 ou  str     wid  fix   11
15411 ou  st      wid  fix   10
15412 ou  st      wi   fix   9
15413 ou  st      wi   fi    8
15414 Final file name: oustwifi.adb
15415 @end smallexample
15417 @item
15418 The file names for all predefined units are always krunched to eight
15419 characters. The krunching of these predefined units uses the following
15420 special prefix replacements:
15422 @table @file
15423 @item ada-
15424 replaced by @file{^a^A^-}
15426 @item gnat-
15427 replaced by @file{^g^G^-}
15429 @item interfaces-
15430 replaced by @file{^i^I^-}
15432 @item system-
15433 replaced by @file{^s^S^-}
15434 @end table
15436 These system files have a hyphen in the second character position. That
15437 is why normal user files replace such a character with a
15438 ^tilde^dollar sign^, to
15439 avoid confusion with system file names.
15441 As an example of this special rule, consider
15442 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15444 @smallexample
15445 ada-strings-wide_fixed 22
15446 a-  strings wide fixed 18
15447 a-  string  wide fixed 17
15448 a-  strin   wide fixed 16
15449 a-  stri    wide fixed 15
15450 a-  stri    wide fixe  14
15451 a-  str     wide fixe  13
15452 a-  str     wid  fixe  12
15453 a-  str     wid  fix   11
15454 a-  st      wid  fix   10
15455 a-  st      wi   fix   9
15456 a-  st      wi   fi    8
15457 Final file name: a-stwifi.adb
15458 @end smallexample
15459 @end itemize
15461 Of course no file shortening algorithm can guarantee uniqueness over all
15462 possible unit names, and if file name krunching is used then it is your
15463 responsibility to ensure that no name clashes occur. The utility
15464 program @code{gnatkr} is supplied for conveniently determining the
15465 krunched name of a file.
15467 @node Examples of gnatkr Usage
15468 @section Examples of @code{gnatkr} Usage
15470 @smallexample
15471 @iftex
15472 @leftskip=0cm
15473 @end iftex
15474 @ifclear vms
15475 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15476 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15477 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15478 $ gnatkr grandparent-parent-child     --> grparchi
15479 @end ifclear
15480 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15481 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15482 @end smallexample
15484 @node Preprocessing Using gnatprep
15485 @chapter Preprocessing Using @code{gnatprep}
15486 @findex gnatprep
15488 @noindent
15489 The @code{gnatprep} utility provides
15490 a simple preprocessing capability for Ada programs.
15491 It is designed for use with GNAT, but is not dependent on any special
15492 features of GNAT.
15494 @menu
15495 * Using gnatprep::
15496 * Switches for gnatprep::
15497 * Form of Definitions File::
15498 * Form of Input Text for gnatprep::
15499 @end menu
15501 @node Using gnatprep
15502 @section Using @code{gnatprep}
15504 @noindent
15505 To call @code{gnatprep} use
15507 @smallexample
15508 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
15509 @end smallexample
15511 @noindent
15512 where
15513 @table @code
15514 @item infile
15515 is the full name of the input file, which is an Ada source
15516 file containing preprocessor directives.
15518 @item outfile
15519 is the full name of the output file, which is an Ada source
15520 in standard Ada form. When used with GNAT, this file name will
15521 normally have an ads or adb suffix.
15523 @item deffile
15524 is the full name of a text file containing definitions of
15525 symbols to be referenced by the preprocessor. This argument is
15526 optional, and can be replaced by the use of the @option{-D} switch.
15528 @item switches
15529 is an optional sequence of switches as described in the next section.
15530 @end table
15532 @node Switches for gnatprep
15533 @section Switches for @code{gnatprep}
15535 @table @option
15536 @c !sort!
15538 @item ^-b^/BLANK_LINES^
15539 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15540 Causes both preprocessor lines and the lines deleted by
15541 preprocessing to be replaced by blank lines in the output source file,
15542 preserving line numbers in the output file.
15544 @item ^-c^/COMMENTS^
15545 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15546 Causes both preprocessor lines and the lines deleted
15547 by preprocessing to be retained in the output source as comments marked
15548 with the special string @code{"--! "}. This option will result in line numbers
15549 being preserved in the output file.
15551 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15552 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15553 Defines a new symbol, associated with value. If no value is given on the
15554 command line, then symbol is considered to be @code{True}. This switch
15555 can be used in place of a definition file.
15557 @ifset vms
15558 @item /REMOVE
15559 @cindex @option{/REMOVE} (@command{gnatprep})
15560 This is the default setting which causes lines deleted by preprocessing
15561 to be entirely removed from the output file.
15562 @end ifset
15564 @item ^-r^/REFERENCE^
15565 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15566 Causes a @code{Source_Reference} pragma to be generated that
15567 references the original input file, so that error messages will use
15568 the file name of this original file. The use of this switch implies
15569 that preprocessor lines are not to be removed from the file, so its
15570 use will force @option{^-b^/BLANK_LINES^} mode if
15571 @option{^-c^/COMMENTS^}
15572 has not been specified explicitly.
15574 Note that if the file to be preprocessed contains multiple units, then
15575 it will be necessary to @code{gnatchop} the output file from
15576 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15577 in the preprocessed file, it will be respected by
15578 @code{gnatchop ^-r^/REFERENCE^}
15579 so that the final chopped files will correctly refer to the original
15580 input source file for @code{gnatprep}.
15582 @item ^-s^/SYMBOLS^
15583 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15584 Causes a sorted list of symbol names and values to be
15585 listed on the standard output file.
15587 @item ^-u^/UNDEFINED^
15588 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15589 Causes undefined symbols to be treated as having the value FALSE in the context
15590 of a preprocessor test. In the absence of this option, an undefined symbol in
15591 a @code{#if} or @code{#elsif} test will be treated as an error.
15593 @end table
15595 @ifclear vms
15596 @noindent
15597 Note: if neither @option{-b} nor @option{-c} is present,
15598 then preprocessor lines and
15599 deleted lines are completely removed from the output, unless -r is
15600 specified, in which case -b is assumed.
15601 @end ifclear
15603 @node Form of Definitions File
15604 @section Form of Definitions File
15606 @noindent
15607 The definitions file contains lines of the form
15609 @smallexample
15610 symbol := value
15611 @end smallexample
15613 @noindent
15614 where symbol is an identifier, following normal Ada (case-insensitive)
15615 rules for its syntax, and value is one of the following:
15617 @itemize @bullet
15618 @item
15619 Empty, corresponding to a null substitution
15620 @item
15621 A string literal using normal Ada syntax
15622 @item
15623 Any sequence of characters from the set
15624 (letters, digits, period, underline).
15625 @end itemize
15627 @noindent
15628 Comment lines may also appear in the definitions file, starting with
15629 the usual @code{--},
15630 and comments may be added to the definitions lines.
15632 @node Form of Input Text for gnatprep
15633 @section Form of Input Text for @code{gnatprep}
15635 @noindent
15636 The input text may contain preprocessor conditional inclusion lines,
15637 as well as general symbol substitution sequences.
15639 The preprocessor conditional inclusion commands have the form
15641 @smallexample
15642 @group
15643 @cartouche
15644 #if @i{expression} [then]
15645    lines
15646 #elsif @i{expression} [then]
15647    lines
15648 #elsif @i{expression} [then]
15649    lines
15651 #else
15652    lines
15653 #end if;
15654 @end cartouche
15655 @end group
15656 @end smallexample
15658 @noindent
15659 In this example, @i{expression} is defined by the following grammar:
15660 @smallexample
15661 @i{expression} ::=  <symbol>
15662 @i{expression} ::=  <symbol> = "<value>"
15663 @i{expression} ::=  <symbol> = <symbol>
15664 @i{expression} ::=  <symbol> 'Defined
15665 @i{expression} ::=  not @i{expression}
15666 @i{expression} ::=  @i{expression} and @i{expression}
15667 @i{expression} ::=  @i{expression} or @i{expression}
15668 @i{expression} ::=  @i{expression} and then @i{expression}
15669 @i{expression} ::=  @i{expression} or else @i{expression}
15670 @i{expression} ::=  ( @i{expression} )
15671 @end smallexample
15673 @noindent
15674 For the first test (@i{expression} ::= <symbol>) the symbol must have
15675 either the value true or false, that is to say the right-hand of the
15676 symbol definition must be one of the (case-insensitive) literals
15677 @code{True} or @code{False}. If the value is true, then the
15678 corresponding lines are included, and if the value is false, they are
15679 excluded.
15681 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15682 the symbol has been defined in the definition file or by a @option{-D}
15683 switch on the command line. Otherwise, the test is false.
15685 The equality tests are case insensitive, as are all the preprocessor lines.
15687 If the symbol referenced is not defined in the symbol definitions file,
15688 then the effect depends on whether or not switch @option{-u}
15689 is specified. If so, then the symbol is treated as if it had the value
15690 false and the test fails. If this switch is not specified, then
15691 it is an error to reference an undefined symbol. It is also an error to
15692 reference a symbol that is defined with a value other than @code{True}
15693 or @code{False}.
15695 The use of the @code{not} operator inverts the sense of this logical test, so
15696 that the lines are included only if the symbol is not defined.
15697 The @code{then} keyword is optional as shown
15699 The @code{#} must be the first non-blank character on a line, but
15700 otherwise the format is free form. Spaces or tabs may appear between
15701 the @code{#} and the keyword. The keywords and the symbols are case
15702 insensitive as in normal Ada code. Comments may be used on a
15703 preprocessor line, but other than that, no other tokens may appear on a
15704 preprocessor line. Any number of @code{elsif} clauses can be present,
15705 including none at all. The @code{else} is optional, as in Ada.
15707 The @code{#} marking the start of a preprocessor line must be the first
15708 non-blank character on the line, i.e. it must be preceded only by
15709 spaces or horizontal tabs.
15711 Symbol substitution outside of preprocessor lines is obtained by using
15712 the sequence
15714 @smallexample
15715 $symbol
15716 @end smallexample
15718 @noindent
15719 anywhere within a source line, except in a comment or within a
15720 string literal. The identifier
15721 following the @code{$} must match one of the symbols defined in the symbol
15722 definition file, and the result is to substitute the value of the
15723 symbol in place of @code{$symbol} in the output file.
15725 Note that although the substitution of strings within a string literal
15726 is not possible, it is possible to have a symbol whose defined value is
15727 a string literal. So instead of setting XYZ to @code{hello} and writing:
15729 @smallexample
15730 Header : String := "$XYZ";
15731 @end smallexample
15733 @noindent
15734 you should set XYZ to @code{"hello"} and write:
15736 @smallexample
15737 Header : String := $XYZ;
15738 @end smallexample
15740 @noindent
15741 and then the substitution will occur as desired.
15743 @ifset vms
15744 @node The GNAT Run-Time Library Builder gnatlbr
15745 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
15746 @findex gnatlbr
15747 @cindex Library builder
15749 @noindent
15750 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
15751 supplied configuration pragmas.
15753 @menu
15754 * Running gnatlbr::
15755 * Switches for gnatlbr::
15756 * Examples of gnatlbr Usage::
15757 @end menu
15759 @node Running gnatlbr
15760 @section Running @code{gnatlbr}
15762 @noindent
15763 The @code{gnatlbr} command has the form
15765 @smallexample
15766 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
15767 @end smallexample
15769 @node Switches for gnatlbr
15770 @section Switches for @code{gnatlbr}
15772 @noindent
15773 @code{gnatlbr} recognizes the following switches:
15775 @table @option
15776 @c !sort!
15777 @item /CREATE=directory
15778 @cindex @code{/CREATE} (@code{gnatlbr})
15779      Create the new run-time library in the specified directory.
15781 @item /SET=directory
15782 @cindex @code{/SET} (@code{gnatlbr})
15783      Make the library in the specified directory the current run-time
15784      library.
15786 @item /DELETE=directory
15787 @cindex @code{/DELETE} (@code{gnatlbr})
15788      Delete the run-time library in the specified directory.
15790 @item /CONFIG=file
15791 @cindex @code{/CONFIG} (@code{gnatlbr})
15792      With /CREATE:
15793      Use the configuration pragmas in the specified file when building
15794      the library.
15796      With /SET:
15797      Use the configuration pragmas in the specified file when compiling.
15799 @end table
15801 @node Examples of gnatlbr Usage
15802 @section Example of @code{gnatlbr} Usage
15804 @smallexample
15805 Contents of VAXFLOAT.ADC:
15806 pragma Float_Representation (VAX_Float);
15808 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15810 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15812 @end smallexample
15813 @end ifset
15815 @node The GNAT Library Browser gnatls
15816 @chapter The GNAT Library Browser @code{gnatls}
15817 @findex gnatls
15818 @cindex Library browser
15820 @noindent
15821 @code{gnatls} is a tool that outputs information about compiled
15822 units. It gives the relationship between objects, unit names and source
15823 files. It can also be used to check the source dependencies of a unit
15824 as well as various characteristics.
15826 @menu
15827 * Running gnatls::
15828 * Switches for gnatls::
15829 * Examples of gnatls Usage::
15830 @end menu
15832 @node Running gnatls
15833 @section Running @code{gnatls}
15835 @noindent
15836 The @code{gnatls} command has the form
15838 @smallexample
15839 $ gnatls switches @var{object_or_ali_file}
15840 @end smallexample
15842 @noindent
15843 The main argument is the list of object or @file{ali} files
15844 (@pxref{The Ada Library Information Files})
15845 for which information is requested.
15847 In normal mode, without additional option, @code{gnatls} produces a
15848 four-column listing. Each line represents information for a specific
15849 object. The first column gives the full path of the object, the second
15850 column gives the name of the principal unit in this object, the third
15851 column gives the status of the source and the fourth column gives the
15852 full path of the source representing this unit.
15853 Here is a simple example of use:
15855 @smallexample
15856 $ gnatls *.o
15857 ^./^[]^demo1.o            demo1            DIF demo1.adb
15858 ^./^[]^demo2.o            demo2             OK demo2.adb
15859 ^./^[]^hello.o            h1                OK hello.adb
15860 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15861 ^./^[]^instr.o            instr             OK instr.adb
15862 ^./^[]^tef.o              tef              DIF tef.adb
15863 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15864 ^./^[]^tgef.o             tgef             DIF tgef.adb
15865 @end smallexample
15867 @noindent
15868 The first line can be interpreted as follows: the main unit which is
15869 contained in
15870 object file @file{demo1.o} is demo1, whose main source is in
15871 @file{demo1.adb}. Furthermore, the version of the source used for the
15872 compilation of demo1 has been modified (DIF). Each source file has a status
15873 qualifier which can be:
15875 @table @code
15876 @item OK (unchanged)
15877 The version of the source file used for the compilation of the
15878 specified unit corresponds exactly to the actual source file.
15880 @item MOK (slightly modified)
15881 The version of the source file used for the compilation of the
15882 specified unit differs from the actual source file but not enough to
15883 require recompilation. If you use gnatmake with the qualifier
15884 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15885 MOK will not be recompiled.
15887 @item DIF (modified)
15888 No version of the source found on the path corresponds to the source
15889 used to build this object.
15891 @item ??? (file not found)
15892 No source file was found for this unit.
15894 @item HID (hidden,  unchanged version not first on PATH)
15895 The version of the source that corresponds exactly to the source used
15896 for compilation has been found on the path but it is hidden by another
15897 version of the same source that has been modified.
15899 @end table
15901 @node Switches for gnatls
15902 @section Switches for @code{gnatls}
15904 @noindent
15905 @code{gnatls} recognizes the following switches:
15907 @table @option
15908 @c !sort!
15909 @item ^-a^/ALL_UNITS^
15910 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15911 Consider all units, including those of the predefined Ada library.
15912 Especially useful with @option{^-d^/DEPENDENCIES^}.
15914 @item ^-d^/DEPENDENCIES^
15915 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15916 List sources from which specified units depend on.
15918 @item ^-h^/OUTPUT=OPTIONS^
15919 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15920 Output the list of options.
15922 @item ^-o^/OUTPUT=OBJECTS^
15923 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15924 Only output information about object files.
15926 @item ^-s^/OUTPUT=SOURCES^
15927 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15928 Only output information about source files.
15930 @item ^-u^/OUTPUT=UNITS^
15931 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15932 Only output information about compilation units.
15934 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15935 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15936 @itemx ^-I^/SEARCH=^@var{dir}
15937 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15938 @itemx -nostdinc
15939 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15940 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15941 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15942 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15943 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
15944 (see @ref{Switches for gnatmake}).
15946 @item --RTS=@var{rts-path}
15947 @cindex @option{--RTS} (@code{gnatls})
15948 Specifies the default location of the runtime library. Same meaning as the
15949 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
15951 @item ^-v^/OUTPUT=VERBOSE^
15952 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15953 Verbose mode. Output the complete source and object paths. Do not use
15954 the default column layout but instead use long format giving as much as
15955 information possible on each requested units, including special
15956 characteristics such as:
15958 @table @code
15959 @item  Preelaborable
15960 The unit is preelaborable in the Ada 95 sense.
15962 @item No_Elab_Code
15963 No elaboration code has been produced by the compiler for this unit.
15965 @item Pure
15966 The unit is pure in the Ada 95 sense.
15968 @item Elaborate_Body
15969 The unit contains a pragma Elaborate_Body.
15971 @item Remote_Types
15972 The unit contains a pragma Remote_Types.
15974 @item Shared_Passive
15975 The unit contains a pragma Shared_Passive.
15977 @item Predefined
15978 This unit is part of the predefined environment and cannot be modified
15979 by the user.
15981 @item Remote_Call_Interface
15982 The unit contains a pragma Remote_Call_Interface.
15984 @end table
15986 @end table
15988 @node Examples of gnatls Usage
15989 @section Example of @code{gnatls} Usage
15990 @ifclear vms
15992 @noindent
15993 Example of using the verbose switch. Note how the source and
15994 object paths are affected by the -I switch.
15996 @smallexample
15997 $ gnatls -v -I.. demo1.o
15999 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
16001 Source Search Path:
16002    <Current_Directory>
16003    ../
16004    /home/comar/local/adainclude/
16006 Object Search Path:
16007    <Current_Directory>
16008    ../
16009    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16011 ./demo1.o
16012    Unit =>
16013      Name   => demo1
16014      Kind   => subprogram body
16015      Flags  => No_Elab_Code
16016      Source => demo1.adb    modified
16017 @end smallexample
16019 @noindent
16020 The following is an example of use of the dependency list.
16021 Note the use of the -s switch
16022 which gives a straight list of source files. This can be useful for
16023 building specialized scripts.
16025 @smallexample
16026 $ gnatls -d demo2.o
16027 ./demo2.o   demo2        OK demo2.adb
16028                          OK gen_list.ads
16029                          OK gen_list.adb
16030                          OK instr.ads
16031                          OK instr-child.ads
16033 $ gnatls -d -s -a demo1.o
16034 demo1.adb
16035 /home/comar/local/adainclude/ada.ads
16036 /home/comar/local/adainclude/a-finali.ads
16037 /home/comar/local/adainclude/a-filico.ads
16038 /home/comar/local/adainclude/a-stream.ads
16039 /home/comar/local/adainclude/a-tags.ads
16040 gen_list.ads
16041 gen_list.adb
16042 /home/comar/local/adainclude/gnat.ads
16043 /home/comar/local/adainclude/g-io.ads
16044 instr.ads
16045 /home/comar/local/adainclude/system.ads
16046 /home/comar/local/adainclude/s-exctab.ads
16047 /home/comar/local/adainclude/s-finimp.ads
16048 /home/comar/local/adainclude/s-finroo.ads
16049 /home/comar/local/adainclude/s-secsta.ads
16050 /home/comar/local/adainclude/s-stalib.ads
16051 /home/comar/local/adainclude/s-stoele.ads
16052 /home/comar/local/adainclude/s-stratt.ads
16053 /home/comar/local/adainclude/s-tasoli.ads
16054 /home/comar/local/adainclude/s-unstyp.ads
16055 /home/comar/local/adainclude/unchconv.ads
16056 @end smallexample
16057 @end ifclear
16059 @ifset vms
16060 @smallexample
16061 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16063 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16064 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16065 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16066 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16067 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16068 demo1.adb
16069 gen_list.ads
16070 gen_list.adb
16071 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16072 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16073 instr.ads
16074 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16075 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16076 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16077 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16078 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16079 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16080 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16081 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16082 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16083 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16084 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16085 @end smallexample
16086 @end ifset
16088 @node Cleaning Up Using gnatclean
16089 @chapter Cleaning Up Using @code{gnatclean}
16090 @findex gnatclean
16091 @cindex Cleaning tool
16093 @noindent
16094 @code{gnatclean} is a tool that allows the deletion of files produced by the
16095 compiler, binder and linker, including ALI files, object files, tree files,
16096 expanded source files, library files, interface copy source files, binder
16097 generated files and executable files.
16099 @menu
16100 * Running gnatclean::
16101 * Switches for gnatclean::
16102 * Examples of gnatclean Usage::
16103 @end menu
16105 @node Running gnatclean
16106 @section Running @code{gnatclean}
16108 @noindent
16109 The @code{gnatclean} command has the form:
16111 @smallexample
16112 $ gnatclean switches @var{names}
16113 @end smallexample
16115 @noindent
16116 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16117 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16118 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16120 @noindent
16121 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16122 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16123 the linker. In informative-only mode, specified by switch
16124 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16125 normal mode is listed, but no file is actually deleted.
16127 @node Switches for gnatclean
16128 @section Switches for @code{gnatclean}
16130 @noindent
16131 @code{gnatclean} recognizes the following switches:
16133 @table @option
16134 @c !sort!
16135 @item ^-c^/COMPILER_FILES_ONLY^
16136 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16137 Only attempt to delete the files produced by the compiler, not those produced
16138 by the binder or the linker. The files that are not to be deleted are library
16139 files, interface copy files, binder generated files and executable files.
16141 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16142 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16143 Indicate that ALI and object files should normally be found in directory
16144 @var{dir}.
16146 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16147 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16148 When using project files, if some errors or warnings are detected during
16149 parsing and verbose mode is not in effect (no use of switch
16150 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16151 file, rather than its simple file name.
16153 @item ^-h^/HELP^
16154 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16155 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16157 @item ^-n^/NODELETE^
16158 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16159 Informative-only mode. Do not delete any files. Output the list of the files
16160 that would have been deleted if this switch was not specified.
16162 @item ^-P^/PROJECT_FILE=^@var{project}
16163 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16164 Use project file @var{project}. Only one such switch can be used.
16165 When cleaning a project file, the files produced by the compilation of the
16166 immediate sources or inherited sources of the project files are to be
16167 deleted. This is not depending on the presence or not of executable names
16168 on the command line.
16170 @item ^-q^/QUIET^
16171 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16172 Quiet output. If there are no error, do not ouuput anything, except in
16173 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16174 (switch ^-n^/NODELETE^).
16176 @item ^-r^/RECURSIVE^
16177 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16178 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16179 clean all imported and extended project files, recursively. If this switch
16180 is not specified, only the files related to the main project file are to be
16181 deleted. This switch has no effect if no project file is specified.
16183 @item ^-v^/VERBOSE^
16184 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16185 Verbose mode.
16187 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16188 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16189 Indicates the verbosity of the parsing of GNAT project files.
16190 See @ref{Switches Related to Project Files}.
16192 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16193 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16194 Indicates that external variable @var{name} has the value @var{value}.
16195 The Project Manager will use this value for occurrences of
16196 @code{external(name)} when parsing the project file.
16197 See @ref{Switches Related to Project Files}.
16199 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16200 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16201 When searching for ALI and object files, look in directory
16202 @var{dir}.
16204 @item ^-I^/SEARCH=^@var{dir}
16205 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16206 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16208 @item ^-I-^/NOCURRENT_DIRECTORY^
16209 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16210 @cindex Source files, suppressing search
16211 Do not look for ALI or object files in the directory
16212 where @code{gnatclean} was invoked.
16214 @end table
16216 @node Examples of gnatclean Usage
16217 @section Examples of @code{gnatclean} Usage
16219 @ifclear vms
16220 @node GNAT and Libraries
16221 @chapter GNAT and Libraries
16222 @cindex Library, building, installing
16224 @noindent
16225 This chapter addresses some of the issues related to building and using
16226 a library with GNAT. It also shows how the GNAT run-time library can be
16227 recompiled.
16229 @menu
16230 * Creating an Ada Library::
16231 * Installing an Ada Library::
16232 * Using an Ada Library::
16233 * Creating an Ada Library to be Used in a Non-Ada Context::
16234 * Rebuilding the GNAT Run-Time Library::
16235 @end menu
16237 @node Creating an Ada Library
16238 @section Creating an Ada Library
16240 @noindent
16241 In the GNAT environment, a library has two components:
16242 @itemize @bullet
16243 @item
16244 Source files.
16245 @item
16246 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
16247 @end itemize
16249 @noindent
16250 In order to use other packages @ref{The GNAT Compilation Model}
16251 requires a certain number of sources to be available to the compiler.
16252 The minimal set of
16253 sources required includes the specs of all the packages that make up the
16254 visible part of the library as well as all the sources upon which they
16255 depend. The bodies of all visible generic units must also be provided.
16256 @noindent
16257 Although it is not strictly mandatory, it is recommended that all sources
16258 needed to recompile the library be provided, so that the user can make
16259 full use of inter-unit inlining and source-level debugging. This can also
16260 make the situation easier for users that need to upgrade their compilation
16261 toolchain and thus need to recompile the library from sources.
16263 @noindent
16264 The compiled code can be provided in different ways. The simplest way is
16265 to provide directly the set of objects produced by the compiler during
16266 the compilation of the library. It is also possible to group the objects
16267 into an archive using whatever commands are provided by the operating
16268 system. Finally, it is also possible to create a shared library (see
16269 option -shared in the GCC manual).
16271 @noindent
16272 There are various possibilities for compiling the units that make up the
16273 library: for example with a Makefile @ref{Using the GNU make Utility},
16274 or with a conventional script.
16275 For simple libraries, it is also possible to create a
16276 dummy main program which depends upon all the packages that comprise the
16277 interface of the library. This dummy main program can then be given to
16278 gnatmake, in order to build all the necessary objects. Here is an example
16279 of such a dummy program and the generic commands used to build an
16280 archive or a shared library.
16282 @smallexample @c ada
16283 @iftex
16284 @leftskip=.7cm
16285 @end iftex
16286 with My_Lib.Service1;
16287 with My_Lib.Service2;
16288 with My_Lib.Service3;
16289 procedure My_Lib_Dummy is
16290 begin
16291    null;
16292 end;
16293 @end smallexample
16295 @smallexample
16296 # compiling the library
16297 $ gnatmake -c my_lib_dummy.adb
16299 # we don't need the dummy object itself
16300 $ rm my_lib_dummy.o my_lib_dummy.ali
16302 # create an archive with the remaining objects
16303 $ ar rc libmy_lib.a *.o
16304 # some systems may require "ranlib" to be run as well
16306 # or create a shared library
16307 $ gcc -shared -o libmy_lib.so *.o
16308 # some systems may require the code to have been compiled with -fPIC
16310 # remove the object files that are now in the library
16311 $ rm *.o
16313 # Make the ALI files read-only so that gnatmake will not try to
16314 # regenerate the objects that are in the library
16315 $ chmod -w *.ali
16317 @end smallexample
16319 @noindent
16320 When the objects are grouped in an archive or a shared library, the user
16321 needs to specify the desired library at link time, unless a pragma
16322 linker_options has been used in one of the sources:
16323 @smallexample @c ada
16324 pragma Linker_Options ("-lmy_lib");
16325 @end smallexample
16327 @noindent
16328 Please note that the library must have a name of the form libxxx.a or
16329 libxxx.so in order to be accessed by the directive -lxxx at link
16330 time.
16332 @node Installing an Ada Library
16333 @section Installing an Ada Library
16335 @noindent
16336 In the GNAT model, installing a library consists in copying into a specific
16337 location the files that make up this library. It is possible to install
16338 the sources in a different directory from the other files (ALI, objects,
16339 archives) since the source path and the object path can easily be
16340 specified separately.
16342 @noindent
16343 For general purpose libraries, it is possible for the system
16344 administrator to put those libraries in the default compiler paths. To
16345 achieve this, he must specify their location in the configuration files
16346 @file{ada_source_path} and @file{ada_object_path} that must be located in
16347 the GNAT
16348 installation tree at the same place as the gcc spec file. The location of
16349 the gcc spec file can be determined as follows:
16350 @smallexample
16351 $ gcc -v
16352 @end smallexample
16354 @noindent
16355 The configuration files mentioned above have simple format: each line in them
16356 must contain one unique
16357 directory name. Those names are added to the corresponding path
16358 in their order of appearance in the file. The names can be either absolute
16359 or relative, in the latter case, they are relative to where theses files
16360 are located.
16362 @noindent
16363 @file{ada_source_path} and @file{ada_object_path} might actually not be
16364 present in a
16365 GNAT installation, in which case, GNAT will look for its run-time library in
16366 he directories @file{adainclude} for the sources and @file{adalib} for the
16367 objects and @file{ALI} files. When the files exist, the compiler does not
16368 look in @file{adainclude} and @file{adalib} at all, and thus the
16369 @file{ada_source_path} file
16370 must contain the location for the GNAT run-time sources (which can simply
16371 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16372 contain the location for the GNAT run-time objects (which can simply
16373 be @file{adalib}).
16375 @noindent
16376 You can also specify a new default path to the runtime library at compilation
16377 time with the switch @option{--RTS=rts-path}. You can easily choose and change
16378 the runtime you want your program to be compiled with. This switch is
16379 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
16381 @noindent
16382 It is possible to install a library before or after the standard GNAT
16383 library, by reordering the lines in the configuration files. In general, a
16384 library must be installed before the GNAT library if it redefines
16385 any part of it.
16387 @node Using an Ada Library
16388 @section Using an Ada Library
16390 @noindent
16391 In order to use a Ada library, you need to make sure that this
16392 library is on both your source and object path
16393 @ref{Search Paths and the Run-Time Library (RTL)}
16394 and @ref{Search Paths for gnatbind}. For
16395 instance, you can use the library @file{mylib} installed in
16396 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16398 @smallexample
16399 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16400   -largs -lmy_lib
16401 @end smallexample
16403 @noindent
16404 This can be simplified down to the following:
16405 @smallexample
16406 $ gnatmake my_appl
16407 @end smallexample
16408 when the following conditions are met:
16409 @itemize @bullet
16410 @item
16411 @file{/dir/my_lib_src} has been added by the user to the environment
16412 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
16413 @file{ada_source_path}
16414 @item
16415 @file{/dir/my_lib_obj} has been added by the user to the environment
16416 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
16417 @file{ada_object_path}
16418 @item
16419 a pragma @code{Linker_Options}, as mentioned in @ref{Creating an Ada Library},
16420 has been added to the sources.
16421 @end itemize
16422 @noindent
16424 @node Creating an Ada Library to be Used in a Non-Ada Context
16425 @section Creating an Ada Library to be Used in a Non-Ada Context
16427 @noindent
16428 The previous sections detailed how to create and install a library that
16429 was usable from an Ada main program. Using this library in a non-Ada
16430 context is not possible, because the elaboration of the library is
16431 automatically done as part of the main program elaboration.
16433 GNAT also provides the ability to build libraries that can be used both
16434 in an Ada and non-Ada context.  This section describes how to build such
16435 a library, and then how to use it from a C program. The method for
16436 interfacing with the library from other languages such as Fortran for
16437 instance remains the same.
16439 @subsection Creating the Library
16441 @itemize @bullet
16442 @item Identify the units representing the interface of the library.
16444 Here is an example of simple library interface:
16446 @smallexample @c ada
16447 package Interface is
16449    procedure Do_Something;
16451    procedure Do_Something_Else;
16453 end Interface;
16454 @end smallexample
16456 @item Use @code{pragma Export} or @code{pragma Convention} for the
16457 exported entities.
16459 Our package @code{Interface} is then updated as follow:
16460 @smallexample @c ada
16461 package Interface is
16463    procedure Do_Something;
16464    pragma Export (C, Do_Something, "do_something");
16466    procedure Do_Something_Else;
16467    pragma Export (C, Do_Something_Else, "do_something_else");
16469 end Interface;
16470 @end smallexample
16472 @item Compile all the units composing the library.
16474 @item Bind the library objects.
16476 This step is performed by invoking gnatbind with the @option{-L<prefix>}
16477 switch. @code{gnatbind} will then generate the library elaboration
16478 procedure (named @code{<prefix>init}) and the run-time finalization
16479 procedure (named @code{<prefix>final}).
16481 @smallexample
16482 # generate the binder file in Ada
16483 $ gnatbind -Lmylib interface
16485 # generate the binder file in C
16486 $ gnatbind -C -Lmylib interface
16487 @end smallexample
16489 @item Compile the files generated by the binder
16491 @smallexample
16492 $ gcc -c b~interface.adb
16493 @end smallexample
16495 @item Create the library;
16497 The procedure is identical to the procedure explained in
16498 @ref{Creating an Ada Library},
16499 except that @file{b~interface.o} needs to be added to
16500 the list of objects.
16502 @smallexample
16503 # create an archive file
16504 $ ar cr libmylib.a b~interface.o <other object files>
16506 # create a shared library
16507 $ gcc -shared -o libmylib.so b~interface.o <other object files>
16508 @end smallexample
16510 @item Provide a ``foreign'' view of the library interface;
16512 The example below shows the content of @code{mylib_interface.h} (note
16513 that there is no rule for the naming of this file, any name can be used)
16514 @smallexample
16515 /* the library elaboration procedure */
16516 extern void mylibinit (void);
16518 /* the library finalization procedure */
16519 extern void mylibfinal (void);
16521 /* the interface exported by the library */
16522 extern void do_something (void);
16523 extern void do_something_else (void);
16524 @end smallexample
16525 @end itemize
16527 @subsection Using the Library
16529 @noindent
16530 Libraries built as explained above can be used from any program, provided
16531 that the elaboration procedures (named @code{mylibinit} in the previous
16532 example) are called before the library services are used. Any number of
16533 libraries can be used simultaneously, as long as the elaboration
16534 procedure of each library is called.
16536 Below is an example of C program that uses our @code{mylib} library.
16538 @smallexample
16539 #include "mylib_interface.h"
16542 main (void)
16544    /* First, elaborate the library before using it */
16545    mylibinit ();
16547    /* Main program, using the library exported entities */
16548    do_something ();
16549    do_something_else ();
16551    /* Library finalization at the end of the program */
16552    mylibfinal ();
16553    return 0;
16555 @end smallexample
16557 @noindent
16558 Note that this same library can be used from an equivalent Ada main
16559 program. In addition, if the libraries are installed as detailed in
16560 @ref{Installing an Ada Library}, it is not necessary to invoke the
16561 library elaboration and finalization routines. The binder will ensure
16562 that this is done as part of the main program elaboration and
16563 finalization phases.
16565 @subsection The Finalization Phase
16567 @noindent
16568 Invoking any library finalization procedure generated by @code{gnatbind}
16569 shuts down the Ada run time permanently. Consequently, the finalization
16570 of all Ada libraries must be performed at the end of the program. No
16571 call to these libraries nor the Ada run time should be made past the
16572 finalization phase.
16574 @subsection Restrictions in Libraries
16576 @noindent
16577 The pragmas listed below should be used with caution inside libraries,
16578 as they can create incompatibilities with other Ada libraries:
16579 @itemize @bullet
16580 @item pragma @code{Locking_Policy}
16581 @item pragma @code{Queuing_Policy}
16582 @item pragma @code{Task_Dispatching_Policy}
16583 @item pragma @code{Unreserve_All_Interrupts}
16584 @end itemize
16585 When using a library that contains such pragmas, the user must make sure
16586 that all libraries use the same pragmas with the same values. Otherwise,
16587 a @code{Program_Error} will
16588 be raised during the elaboration of the conflicting
16589 libraries. The usage of these pragmas and its consequences for the user
16590 should therefore be well documented.
16592 Similarly, the traceback in exception occurrences mechanism should be
16593 enabled or disabled in a consistent manner across all libraries.
16594 Otherwise, a Program_Error will be raised during the elaboration of the
16595 conflicting libraries.
16597 If the @code{'Version} and @code{'Body_Version}
16598 attributes are used inside a library, then it is necessary to
16599 perform a @code{gnatbind} step that mentions all @file{ALI} files in all
16600 libraries, so that version identifiers can be properly computed.
16601 In practice these attributes are rarely used, so this is unlikely
16602 to be a consideration.
16604 @node  Rebuilding the GNAT Run-Time Library
16605 @section Rebuilding the GNAT Run-Time Library
16607 @noindent
16608 It may be useful to recompile the GNAT library in various contexts, the
16609 most important one being the use of partition-wide configuration pragmas
16610 such as Normalize_Scalar. A special Makefile called
16611 @code{Makefile.adalib} is provided to that effect and can be found in
16612 the directory containing the GNAT library. The location of this
16613 directory depends on the way the GNAT environment has been installed and can
16614 be determined by means of the command:
16616 @smallexample
16617 $ gnatls -v
16618 @end smallexample
16620 @noindent
16621 The last entry in the object search path usually contains the
16622 gnat library. This Makefile contains its own documentation and in
16623 particular the set of instructions needed to rebuild a new library and
16624 to use it.
16626 @node Using the GNU make Utility
16627 @chapter Using the GNU @code{make} Utility
16628 @findex make
16630 @noindent
16631 This chapter offers some examples of makefiles that solve specific
16632 problems. It does not explain how to write a makefile (see the GNU make
16633 documentation), nor does it try to replace the @code{gnatmake} utility
16634 (@pxref{The GNAT Make Program gnatmake}).
16636 All the examples in this section are specific to the GNU version of
16637 make. Although @code{make} is a standard utility, and the basic language
16638 is the same, these examples use some advanced features found only in
16639 @code{GNU make}.
16641 @menu
16642 * Using gnatmake in a Makefile::
16643 * Automatically Creating a List of Directories::
16644 * Generating the Command Line Switches::
16645 * Overcoming Command Line Length Limits::
16646 @end menu
16648 @node Using gnatmake in a Makefile
16649 @section Using gnatmake in a Makefile
16650 @findex makefile
16651 @cindex GNU make
16653 @noindent
16654 Complex project organizations can be handled in a very powerful way by
16655 using GNU make combined with gnatmake. For instance, here is a Makefile
16656 which allows you to build each subsystem of a big project into a separate
16657 shared library. Such a makefile allows you to significantly reduce the link
16658 time of very big applications while maintaining full coherence at
16659 each step of the build process.
16661 The list of dependencies are handled automatically by
16662 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16663 the appropriate directories.
16665 Note that you should also read the example on how to automatically
16666 create the list of directories
16667 (@pxref{Automatically Creating a List of Directories})
16668 which might help you in case your project has a lot of subdirectories.
16670 @smallexample
16671 @iftex
16672 @leftskip=0cm
16673 @font@heightrm=cmr8
16674 @heightrm
16675 @end iftex
16676 ## This Makefile is intended to be used with the following directory
16677 ## configuration:
16678 ##  - The sources are split into a series of csc (computer software components)
16679 ##    Each of these csc is put in its own directory.
16680 ##    Their name are referenced by the directory names.
16681 ##    They will be compiled into shared library (although this would also work
16682 ##    with static libraries
16683 ##  - The main program (and possibly other packages that do not belong to any
16684 ##    csc is put in the top level directory (where the Makefile is).
16685 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16686 ##                    \_ second_csc (sources) __ lib (will contain the library)
16687 ##                    \_ ...
16688 ## Although this Makefile is build for shared library, it is easy to modify
16689 ## to build partial link objects instead (modify the lines with -shared and
16690 ## gnatlink below)
16692 ## With this makefile, you can change any file in the system or add any new
16693 ## file, and everything will be recompiled correctly (only the relevant shared
16694 ## objects will be recompiled, and the main program will be re-linked).
16696 # The list of computer software component for your project. This might be
16697 # generated automatically.
16698 CSC_LIST=aa bb cc
16700 # Name of the main program (no extension)
16701 MAIN=main
16703 # If we need to build objects with -fPIC, uncomment the following line
16704 #NEED_FPIC=-fPIC
16706 # The following variable should give the directory containing libgnat.so
16707 # You can get this directory through 'gnatls -v'. This is usually the last
16708 # directory in the Object_Path.
16709 GLIB=...
16711 # The directories for the libraries
16712 # (This macro expands the list of CSC to the list of shared libraries, you
16713 # could simply use the expanded form :
16714 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16715 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16717 $@{MAIN@}: objects $@{LIB_DIR@}
16718     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16719     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16721 objects::
16722     # recompile the sources
16723     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16725 # Note: In a future version of GNAT, the following commands will be simplified
16726 # by a new tool, gnatmlib
16727 $@{LIB_DIR@}:
16728     mkdir -p $@{dir $@@ @}
16729     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16730     cd $@{dir $@@ @}; cp -f ../*.ali .
16732 # The dependencies for the modules
16733 # Note that we have to force the expansion of *.o, since in some cases
16734 # make won't be able to do it itself.
16735 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16736 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16737 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16739 # Make sure all of the shared libraries are in the path before starting the
16740 # program
16741 run::
16742     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16744 clean::
16745     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16746     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16747     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16748     $@{RM@} *.o *.ali $@{MAIN@}
16749 @end smallexample
16751 @node Automatically Creating a List of Directories
16752 @section Automatically Creating a List of Directories
16754 @noindent
16755 In most makefiles, you will have to specify a list of directories, and
16756 store it in a variable. For small projects, it is often easier to
16757 specify each of them by hand, since you then have full control over what
16758 is the proper order for these directories, which ones should be
16759 included...
16761 However, in larger projects, which might involve hundreds of
16762 subdirectories, it might be more convenient to generate this list
16763 automatically.
16765 The example below presents two methods. The first one, although less
16766 general, gives you more control over the list. It involves wildcard
16767 characters, that are automatically expanded by @code{make}. Its
16768 shortcoming is that you need to explicitly specify some of the
16769 organization of your project, such as for instance the directory tree
16770 depth, whether some directories are found in a separate tree,...
16772 The second method is the most general one. It requires an external
16773 program, called @code{find}, which is standard on all Unix systems. All
16774 the directories found under a given root directory will be added to the
16775 list.
16777 @smallexample
16778 @iftex
16779 @leftskip=0cm
16780 @font@heightrm=cmr8
16781 @heightrm
16782 @end iftex
16783 # The examples below are based on the following directory hierarchy:
16784 # All the directories can contain any number of files
16785 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16786 #                       ->  ab
16787 #                       ->  ac
16788 #                ->  b  ->  ba  ->  baa
16789 #                       ->  bb
16790 #                       ->  bc
16791 # This Makefile creates a variable called DIRS, that can be reused any time
16792 # you need this list (see the other examples in this section)
16794 # The root of your project's directory hierarchy
16795 ROOT_DIRECTORY=.
16797 ####
16798 # First method: specify explicitly the list of directories
16799 # This allows you to specify any subset of all the directories you need.
16800 ####
16802 DIRS := a/aa/ a/ab/ b/ba/
16804 ####
16805 # Second method: use wildcards
16806 # Note that the argument(s) to wildcard below should end with a '/'.
16807 # Since wildcards also return file names, we have to filter them out
16808 # to avoid duplicate directory names.
16809 # We thus use make's @code{dir} and @code{sort} functions.
16810 # It sets DIRs to the following value (note that the directories aaa and baa
16811 # are not given, unless you change the arguments to wildcard).
16812 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16813 ####
16815 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16816                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16818 ####
16819 # Third method: use an external program
16820 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16821 # This is the most complete command: it sets DIRs to the following value:
16822 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16823 ####
16825 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16827 @end smallexample
16829 @node Generating the Command Line Switches
16830 @section Generating the Command Line Switches
16832 @noindent
16833 Once you have created the list of directories as explained in the
16834 previous section (@pxref{Automatically Creating a List of Directories}),
16835 you can easily generate the command line arguments to pass to gnatmake.
16837 For the sake of completeness, this example assumes that the source path
16838 is not the same as the object path, and that you have two separate lists
16839 of directories.
16841 @smallexample
16842 # see "Automatically creating a list of directories" to create
16843 # these variables
16844 SOURCE_DIRS=
16845 OBJECT_DIRS=
16847 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16848 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16850 all:
16851         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16852 @end smallexample
16854 @node Overcoming Command Line Length Limits
16855 @section Overcoming Command Line Length Limits
16857 @noindent
16858 One problem that might be encountered on big projects is that many
16859 operating systems limit the length of the command line. It is thus hard to give
16860 gnatmake the list of source and object directories.
16862 This example shows how you can set up environment variables, which will
16863 make @code{gnatmake} behave exactly as if the directories had been
16864 specified on the command line, but have a much higher length limit (or
16865 even none on most systems).
16867 It assumes that you have created a list of directories in your Makefile,
16868 using one of the methods presented in
16869 @ref{Automatically Creating a List of Directories}.
16870 For the sake of completeness, we assume that the object
16871 path (where the ALI files are found) is different from the sources patch.
16873 Note a small trick in the Makefile below: for efficiency reasons, we
16874 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16875 expanded immediately by @code{make}. This way we overcome the standard
16876 make behavior which is to expand the variables only when they are
16877 actually used.
16879 On Windows, if you are using the standard Windows command shell, you must
16880 replace colons with semicolons in the assignments to these variables.
16882 @smallexample
16883 @iftex
16884 @leftskip=0cm
16885 @font@heightrm=cmr8
16886 @heightrm
16887 @end iftex
16888 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16889 # This is the same thing as putting the -I arguments on the command line.
16890 # (the equivalent of using -aI on the command line would be to define
16891 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16892 # You can of course have different values for these variables.
16894 # Note also that we need to keep the previous values of these variables, since
16895 # they might have been set before running 'make' to specify where the GNAT
16896 # library is installed.
16898 # see "Automatically creating a list of directories" to create these
16899 # variables
16900 SOURCE_DIRS=
16901 OBJECT_DIRS=
16903 empty:=
16904 space:=$@{empty@} $@{empty@}
16905 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16906 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16907 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16908 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16909 export ADA_INCLUDE_PATH
16910 export ADA_OBJECT_PATH
16912 all:
16913         gnatmake main_unit
16914 @end smallexample
16915 @end ifclear
16918 @node Finding Memory Problems
16919 @chapter Finding Memory Problems
16921 @noindent
16922 This chapter describes
16923 @ifclear vms
16924 the @command{gnatmem} tool, which can be used to track down
16925 ``memory leaks'', and
16926 @end ifclear
16927 the GNAT Debug Pool facility, which can be used to detect incorrect uses of
16928 access values (including ``dangling references'').
16930 @menu
16931 @ifclear vms
16932 * The gnatmem Tool::
16933 @end ifclear
16934 * The GNAT Debug Pool Facility::
16935 @end menu
16938 @ifclear vms
16939 @node The gnatmem Tool
16940 @section The @command{gnatmem} Tool
16941 @findex gnatmem
16943 @noindent
16944 The @code{gnatmem} utility monitors dynamic allocation and
16945 deallocation activity in a program, and displays information about
16946 incorrect deallocations and possible sources of memory leaks.
16947 It provides three type of information:
16948 @itemize @bullet
16949 @item
16950 General information concerning memory management, such as the total
16951 number of allocations and deallocations, the amount of allocated
16952 memory and the high water mark, i.e. the largest amount of allocated
16953 memory in the course of program execution.
16955 @item
16956 Backtraces for all incorrect deallocations, that is to say deallocations
16957 which do not correspond to a valid allocation.
16959 @item
16960 Information on each allocation that is potentially the origin of a memory
16961 leak.
16962 @end itemize
16964 @menu
16965 * Running gnatmem::
16966 * Switches for gnatmem::
16967 * Example of gnatmem Usage::
16968 @end menu
16970 @node Running gnatmem
16971 @subsection Running @code{gnatmem}
16973 @noindent
16974 @code{gnatmem} makes use of the output created by the special version of
16975 allocation and deallocation routines that record call information. This
16976 allows to obtain accurate dynamic memory usage history at a minimal cost to
16977 the execution speed. Note however, that @code{gnatmem} is not supported on
16978 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
16979 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
16981 @noindent
16982 The @code{gnatmem} command has the form
16984 @smallexample
16985    $ gnatmem [switches] user_program
16986 @end smallexample
16988 @noindent
16989 The program must have been linked with the instrumented version of the
16990 allocation and deallocation routines. This is done by linking with the
16991 @file{libgmem.a} library. For correct symbolic backtrace information,
16992 the user program should be compiled with debugging options
16993 @ref{Switches for gcc}. For example to build @file{my_program}:
16995 @smallexample
16996 $ gnatmake -g my_program -largs -lgmem
16997 @end smallexample
16999 @noindent
17000 When running @file{my_program} the file @file{gmem.out} is produced. This file
17001 contains information about all allocations and deallocations done by the
17002 program. It is produced by the instrumented allocations and
17003 deallocations routines and will be used by @code{gnatmem}.
17005 @noindent
17006 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17007 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17008 @code{-i} switch, gnatmem will assume that this file can be found in the
17009 current directory. For example, after you have executed @file{my_program},
17010 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17012 @smallexample
17013 $ gnatmem my_program
17014 @end smallexample
17016 @noindent
17017 This will produce the output with the following format:
17019 *************** debut cc
17020 @smallexample
17021 $ gnatmem my_program
17023 Global information
17024 ------------------
17025    Total number of allocations        :  45
17026    Total number of deallocations      :   6
17027    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17028    High Water Mark                    :  11.40 Kilobytes
17033 Allocation Root # 2
17034 -------------------
17035  Number of non freed allocations    :  11
17036  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17037  High Water Mark                    :   1.27 Kilobytes
17038  Backtrace                          :
17039    my_program.adb:23 my_program.alloc
17043 @end smallexample
17045 The first block of output gives general information. In this case, the
17046 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17047 Unchecked_Deallocation routine occurred.
17049 @noindent
17050 Subsequent paragraphs display  information on all allocation roots.
17051 An allocation root is a specific point in the execution of the program
17052 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17053 construct. This root is represented by an execution backtrace (or subprogram
17054 call stack). By default the backtrace depth for allocations roots is 1, so
17055 that a root corresponds exactly to a source location. The backtrace can
17056 be made deeper, to make the root more specific.
17058 @node Switches for gnatmem
17059 @subsection Switches for @code{gnatmem}
17061 @noindent
17062 @code{gnatmem} recognizes the following switches:
17064 @table @option
17066 @item -q
17067 @cindex @option{-q} (@code{gnatmem})
17068 Quiet. Gives the minimum output needed to identify the origin of the
17069 memory leaks. Omits statistical information.
17071 @item @var{N}
17072 @cindex @var{N} (@code{gnatmem})
17073 N is an integer literal (usually between 1 and 10) which controls the
17074 depth of the backtraces defining allocation root. The default value for
17075 N is 1. The deeper the backtrace, the more precise the localization of
17076 the root. Note that the total number of roots can depend on this
17077 parameter. This parameter must be specified @emph{before} the name of the
17078 executable to be analyzed, to avoid ambiguity.
17080 @item -b n
17081 @cindex @option{-b} (@code{gnatmem})
17082 This switch has the same effect as just depth parameter.
17084 @item -i @var{file}
17085 @cindex @option{-i} (@code{gnatmem})
17086 Do the @code{gnatmem} processing starting from @file{file}, rather than
17087 @file{gmem.out} in the current directory.
17089 @item -m n
17090 @cindex @option{-m} (@code{gnatmem})
17091 This switch causes @code{gnatmem} to mask the allocation roots that have less
17092 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17093 examine even the roots that didn't result in leaks.
17095 @item -s order
17096 @cindex @option{-s} (@code{gnatmem})
17097 This switch causes @code{gnatmem} to sort the allocation roots according to the
17098 specified order of sort criteria, each identified by a single letter. The
17099 currently supported criteria are @code{n, h, w} standing respectively for
17100 number of unfreed allocations, high watermark, and final watermark
17101 corresponding to a specific root. The default order is @code{nwh}.
17103 @end table
17105 @node Example of gnatmem Usage
17106 @subsection Example of @code{gnatmem} Usage
17108 @noindent
17109 The following example shows the use of @code{gnatmem}
17110 on a simple memory-leaking program.
17111 Suppose that we have the following Ada program:
17113 @smallexample @c ada
17114 @group
17115 @cartouche
17116 with Unchecked_Deallocation;
17117 procedure Test_Gm is
17119    type T is array (1..1000) of Integer;
17120    type Ptr is access T;
17121    procedure Free is new Unchecked_Deallocation (T, Ptr);
17122    A : Ptr;
17124    procedure My_Alloc is
17125    begin
17126       A := new T;
17127    end My_Alloc;
17129    procedure My_DeAlloc is
17130       B : Ptr := A;
17131    begin
17132       Free (B);
17133    end My_DeAlloc;
17135 begin
17136    My_Alloc;
17137    for I in 1 .. 5 loop
17138       for J in I .. 5 loop
17139          My_Alloc;
17140       end loop;
17141       My_Dealloc;
17142    end loop;
17143 end;
17144 @end cartouche
17145 @end group
17146 @end smallexample
17148 @noindent
17149 The program needs to be compiled with debugging option and linked with
17150 @code{gmem} library:
17152 @smallexample
17153 $ gnatmake -g test_gm -largs -lgmem
17154 @end smallexample
17156 @noindent
17157 Then we execute the program as usual:
17159 @smallexample
17160 $ test_gm
17161 @end smallexample
17163 @noindent
17164 Then @code{gnatmem} is invoked simply with
17165 @smallexample
17166 $ gnatmem test_gm
17167 @end smallexample
17169 @noindent
17170 which produces the following output (result may vary on different platforms):
17172 @smallexample
17173 Global information
17174 ------------------
17175    Total number of allocations        :  18
17176    Total number of deallocations      :   5
17177    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17178    High Water Mark                    :  56.90 Kilobytes
17180 Allocation Root # 1
17181 -------------------
17182  Number of non freed allocations    :  11
17183  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17184  High Water Mark                    :  46.88 Kilobytes
17185  Backtrace                          :
17186    test_gm.adb:11 test_gm.my_alloc
17188 Allocation Root # 2
17189 -------------------
17190  Number of non freed allocations    :   1
17191  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17192  High Water Mark                    :  10.02 Kilobytes
17193  Backtrace                          :
17194    s-secsta.adb:81 system.secondary_stack.ss_init
17196 Allocation Root # 3
17197 -------------------
17198  Number of non freed allocations    :   1
17199  Final Water Mark (non freed mem)   :  12 Bytes
17200  High Water Mark                    :  12 Bytes
17201  Backtrace                          :
17202    s-secsta.adb:181 system.secondary_stack.ss_init
17203 @end smallexample
17205 @noindent
17206 Note that the GNAT run time contains itself a certain number of
17207 allocations that have no  corresponding deallocation,
17208 as shown here for root #2 and root
17209 #3. This is a normal behavior when the number of non freed allocations
17210 is one, it allocates dynamic data structures that the run time needs for
17211 the complete lifetime of the program. Note also that there is only one
17212 allocation root in the user program with a single line back trace:
17213 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17214 program shows that 'My_Alloc' is called at 2 different points in the
17215 source (line 21 and line 24). If those two allocation roots need to be
17216 distinguished, the backtrace depth parameter can be used:
17218 @smallexample
17219 $ gnatmem 3 test_gm
17220 @end smallexample
17222 @noindent
17223 which will give the following output:
17225 @smallexample
17226 Global information
17227 ------------------
17228    Total number of allocations        :  18
17229    Total number of deallocations      :   5
17230    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17231    High Water Mark                    :  56.90 Kilobytes
17233 Allocation Root # 1
17234 -------------------
17235  Number of non freed allocations    :  10
17236  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17237  High Water Mark                    :  42.97 Kilobytes
17238  Backtrace                          :
17239    test_gm.adb:11 test_gm.my_alloc
17240    test_gm.adb:24 test_gm
17241    b_test_gm.c:52 main
17243 Allocation Root # 2
17244 -------------------
17245  Number of non freed allocations    :   1
17246  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17247  High Water Mark                    :  10.02 Kilobytes
17248  Backtrace                          :
17249    s-secsta.adb:81  system.secondary_stack.ss_init
17250    s-secsta.adb:283 <system__secondary_stack___elabb>
17251    b_test_gm.c:33   adainit
17253 Allocation Root # 3
17254 -------------------
17255  Number of non freed allocations    :   1
17256  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17257  High Water Mark                    :   3.91 Kilobytes
17258  Backtrace                          :
17259    test_gm.adb:11 test_gm.my_alloc
17260    test_gm.adb:21 test_gm
17261    b_test_gm.c:52 main
17263 Allocation Root # 4
17264 -------------------
17265  Number of non freed allocations    :   1
17266  Final Water Mark (non freed mem)   :  12 Bytes
17267  High Water Mark                    :  12 Bytes
17268  Backtrace                          :
17269    s-secsta.adb:181 system.secondary_stack.ss_init
17270    s-secsta.adb:283 <system__secondary_stack___elabb>
17271    b_test_gm.c:33   adainit
17272 @end smallexample
17274 @noindent
17275 The allocation root #1 of the first example has been split in 2 roots #1
17276 and #3 thanks to the more precise associated backtrace.
17278 @end ifclear
17281 @node The GNAT Debug Pool Facility
17282 @section The GNAT Debug Pool Facility
17283 @findex Debug Pool
17284 @cindex storage, pool, memory corruption
17286 @noindent
17287 The use of unchecked deallocation and unchecked conversion can easily
17288 lead to incorrect memory references. The problems generated by such
17289 references are usually difficult to tackle because the symptoms can be
17290 very remote from the origin of the problem. In such cases, it is
17291 very helpful to detect the problem as early as possible. This is the
17292 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17294 In order to use the GNAT specific debugging pool, the user must
17295 associate a debug pool object with each of the access types that may be
17296 related to suspected memory problems. See Ada Reference Manual 13.11.
17297 @smallexample @c ada
17298 type Ptr is access Some_Type;
17299 Pool : GNAT.Debug_Pools.Debug_Pool;
17300 for Ptr'Storage_Pool use Pool;
17301 @end smallexample
17303 @noindent
17304 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17305 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17306 allow the user to redefine allocation and deallocation strategies. They
17307 also provide a checkpoint for each dereference, through the use of
17308 the primitive operation @code{Dereference} which is implicitly called at
17309 each dereference of an access value.
17311 Once an access type has been associated with a debug pool, operations on
17312 values of the type may raise four distinct exceptions,
17313 which correspond to four potential kinds of memory corruption:
17314 @itemize @bullet
17315 @item
17316 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17317 @item
17318 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17319 @item
17320 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17321 @item
17322 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17323 @end itemize
17325 @noindent
17326 For types associated with a Debug_Pool, dynamic allocation is performed using
17327 the standard
17328 GNAT allocation routine. References to all allocated chunks of memory
17329 are kept in an internal dictionary.
17330 Several deallocation strategies are provided, whereupon the user can choose
17331 to release the memory to the system, keep it allocated for further invalid
17332 access checks, or fill it with an easily recognizable pattern for debug
17333 sessions.
17334 The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}.
17336 See the documentation in the file g-debpoo.ads for more information on the
17337 various strategies.
17339 Upon each dereference, a check is made that the access value denotes a
17340 properly allocated memory location. Here is a complete example of use of
17341 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17342 @smallexample @c ada
17343 @iftex
17344 @leftskip=0cm
17345 @end iftex
17346 with Gnat.Io; use Gnat.Io;
17347 with Unchecked_Deallocation;
17348 with Unchecked_Conversion;
17349 with GNAT.Debug_Pools;
17350 with System.Storage_Elements;
17351 with Ada.Exceptions; use Ada.Exceptions;
17352 procedure Debug_Pool_Test is
17354    type T is access Integer;
17355    type U is access all T;
17357    P : GNAT.Debug_Pools.Debug_Pool;
17358    for T'Storage_Pool use P;
17360    procedure Free is new Unchecked_Deallocation (Integer, T);
17361    function UC is new Unchecked_Conversion (U, T);
17362    A, B : aliased T;
17364    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17366 begin
17367    Info (P);
17368    A := new Integer;
17369    B := new Integer;
17370    B := A;
17371    Info (P);
17372    Free (A);
17373    begin
17374       Put_Line (Integer'Image(B.all));
17375    exception
17376       when E : others => Put_Line ("raised: " & Exception_Name (E));
17377    end;
17378    begin
17379       Free (B);
17380    exception
17381       when E : others => Put_Line ("raised: " & Exception_Name (E));
17382    end;
17383    B := UC(A'Access);
17384    begin
17385       Put_Line (Integer'Image(B.all));
17386    exception
17387       when E : others => Put_Line ("raised: " & Exception_Name (E));
17388    end;
17389    begin
17390       Free (B);
17391    exception
17392       when E : others => Put_Line ("raised: " & Exception_Name (E));
17393    end;
17394    Info (P);
17395 end Debug_Pool_Test;
17396 @end smallexample
17398 @noindent
17399 The debug pool mechanism provides the following precise diagnostics on the
17400 execution of this erroneous program:
17401 @smallexample
17402 Debug Pool info:
17403   Total allocated bytes :  0
17404   Total deallocated bytes :  0
17405   Current Water Mark:  0
17406   High Water Mark:  0
17408 Debug Pool info:
17409   Total allocated bytes :  8
17410   Total deallocated bytes :  0
17411   Current Water Mark:  8
17412   High Water Mark:  8
17414 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17415 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17416 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17417 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17418 Debug Pool info:
17419   Total allocated bytes :  8
17420   Total deallocated bytes :  4
17421   Current Water Mark:  4
17422   High Water Mark:  8
17423 @end smallexample
17426 @node Creating Sample Bodies Using gnatstub
17427 @chapter Creating Sample Bodies Using @command{gnatstub}
17428 @findex gnatstub
17430 @noindent
17431 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17432 for library unit declarations.
17434 To create a body stub, @command{gnatstub} has to compile the library
17435 unit declaration. Therefore, bodies can be created only for legal
17436 library units. Moreover, if a library unit depends semantically upon
17437 units located outside the current directory, you have to provide
17438 the source search path when calling @command{gnatstub}, see the description
17439 of @command{gnatstub} switches below.
17441 @menu
17442 * Running gnatstub::
17443 * Switches for gnatstub::
17444 @end menu
17446 @node Running gnatstub
17447 @section Running @command{gnatstub}
17449 @noindent
17450 @command{gnatstub} has the command-line interface of the form
17452 @smallexample
17453 $ gnatstub [switches] filename [directory]
17454 @end smallexample
17456 @noindent
17457 where
17458 @table @emph
17459 @item filename
17460 is the name of the source file that contains a library unit declaration
17461 for which a body must be created. The file name may contain the path
17462 information.
17463 The file name does not have to follow the GNAT file name conventions. If the
17464 name
17465 does not follow GNAT file naming conventions, the name of the body file must
17466 be provided
17467 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17468 If the file name follows the GNAT file naming
17469 conventions and the name of the body file is not provided,
17470 @command{gnatstub}
17471 creates the name
17472 of the body file from the argument file name by replacing the @file{.ads}
17473 suffix
17474 with the @file{.adb} suffix.
17476 @item directory
17477 indicates the directory in which the body stub is to be placed (the default
17478 is the
17479 current directory)
17481 @item switches
17482 is an optional sequence of switches as described in the next section
17483 @end table
17485 @node Switches for gnatstub
17486 @section Switches for @command{gnatstub}
17488 @table @option
17489 @c !sort!
17491 @item ^-f^/FULL^
17492 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17493 If the destination directory already contains a file with the name of the
17494 body file
17495 for the argument spec file, replace it with the generated body stub.
17497 @item ^-hs^/HEADER=SPEC^
17498 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17499 Put the comment header (i.e., all the comments preceding the
17500 compilation unit) from the source of the library unit declaration
17501 into the body stub.
17503 @item ^-hg^/HEADER=GENERAL^
17504 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17505 Put a sample comment header into the body stub.
17507 @ifclear vms
17508 @item -IDIR
17509 @cindex @option{-IDIR} (@command{gnatstub})
17510 @itemx -I-
17511 @cindex @option{-I-} (@command{gnatstub})
17512 @end ifclear
17513 @ifset vms
17514 @item /NOCURRENT_DIRECTORY
17515 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17516 @end ifset
17517 ^These switches have ^This switch has^ the same meaning as in calls to
17518 @command{gcc}.
17519 ^They define ^It defines ^ the source search path in the call to
17520 @command{gcc} issued
17521 by @command{gnatstub} to compile an argument source file.
17523 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17524 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17525 This switch has the same meaning as in calls to @command{gcc}.
17526 It defines the additional configuration file to be passed to the call to
17527 @command{gcc} issued
17528 by @command{gnatstub} to compile an argument source file.
17530 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17531 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17532 (@var{n} is a non-negative integer). Set the maximum line length in the
17533 body stub to @var{n}; the default is 79. The maximum value that can be
17534 specified is 32767.
17536 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17537 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17538 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17539 the generated body sample to @var{n}.
17540 The default indentation is 3.
17542 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17543 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17544 Order local bodies alphabetically. (By default local bodies are ordered
17545 in the same way as the corresponding local specs in the argument spec file.)
17547 @item ^-i^/INDENTATION=^@var{n}
17548 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17549 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17551 @item ^-k^/TREE_FILE=SAVE^
17552 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17553 Do not remove the tree file (i.e., the snapshot of the compiler internal
17554 structures used by @command{gnatstub}) after creating the body stub.
17556 @item ^-l^/LINE_LENGTH=^@var{n}
17557 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17558 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17560 @item ^-o^/BODY=^@var{body-name}
17561 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17562 Body file name.  This should be set if the argument file name does not
17563 follow
17564 the GNAT file naming
17565 conventions. If this switch is omitted the default name for the body will be
17566 obtained
17567 from the argument file name according to the GNAT file naming conventions.
17569 @item ^-q^/QUIET^
17570 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17571 Quiet mode: do not generate a confirmation when a body is
17572 successfully created, and do not generate a message when a body is not
17573 required for an
17574 argument unit.
17576 @item ^-r^/TREE_FILE=REUSE^
17577 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17578 Reuse the tree file (if it exists) instead of creating it.  Instead of
17579 creating the tree file for the library unit declaration, @command{gnatstub}
17580 tries to find it in the current directory and use it for creating
17581 a body. If the tree file is not found, no body is created. This option
17582 also implies @option{^-k^/SAVE^}, whether or not
17583 the latter is set explicitly.
17585 @item ^-t^/TREE_FILE=OVERWRITE^
17586 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17587 Overwrite the existing tree file.  If the current directory already
17588 contains the file which, according to the GNAT file naming rules should
17589 be considered as a tree file for the argument source file,
17590 @command{gnatstub}
17591 will refuse to create the tree file needed to create a sample body
17592 unless this option is set.
17594 @item ^-v^/VERBOSE^
17595 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17596 Verbose mode: generate version information.
17598 @end table
17601 @node Other Utility Programs
17602 @chapter Other Utility Programs
17604 @noindent
17605 This chapter discusses some other utility programs available in the Ada
17606 environment.
17608 @menu
17609 * Using Other Utility Programs with GNAT::
17610 * The External Symbol Naming Scheme of GNAT::
17611 @ifclear vms
17612 * Ada Mode for Glide::
17613 @end ifclear
17614 * Converting Ada Files to html with gnathtml::
17615 * Installing gnathtml::
17616 @ifset vms
17617 * LSE::
17618 * Profiling::
17619 @end ifset
17620 @end menu
17622 @node Using Other Utility Programs with GNAT
17623 @section Using Other Utility Programs with GNAT
17625 @noindent
17626 The object files generated by GNAT are in standard system format and in
17627 particular the debugging information uses this format. This means
17628 programs generated by GNAT can be used with existing utilities that
17629 depend on these formats.
17631 @ifclear vms
17632 In general, any utility program that works with C will also often work with
17633 Ada programs generated by GNAT. This includes software utilities such as
17634 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17635 as Purify.
17636 @end ifclear
17638 @node The External Symbol Naming Scheme of GNAT
17639 @section The External Symbol Naming Scheme of GNAT
17641 @noindent
17642 In order to interpret the output from GNAT, when using tools that are
17643 originally intended for use with other languages, it is useful to
17644 understand the conventions used to generate link names from the Ada
17645 entity names.
17647 All link names are in all lowercase letters. With the exception of library
17648 procedure names, the mechanism used is simply to use the full expanded
17649 Ada name with dots replaced by double underscores. For example, suppose
17650 we have the following package spec:
17652 @smallexample @c ada
17653 @group
17654 @cartouche
17655 package QRS is
17656    MN : Integer;
17657 end QRS;
17658 @end cartouche
17659 @end group
17660 @end smallexample
17662 @noindent
17663 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17664 the corresponding link name is @code{qrs__mn}.
17665 @findex Export
17666 Of course if a @code{pragma Export} is used this may be overridden:
17668 @smallexample @c ada
17669 @group
17670 @cartouche
17671 package Exports is
17672    Var1 : Integer;
17673    pragma Export (Var1, C, External_Name => "var1_name");
17674    Var2 : Integer;
17675    pragma Export (Var2, C, Link_Name => "var2_link_name");
17676 end Exports;
17677 @end cartouche
17678 @end group
17679 @end smallexample
17681 @noindent
17682 In this case, the link name for @var{Var1} is whatever link name the
17683 C compiler would assign for the C function @var{var1_name}. This typically
17684 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17685 system conventions, but other possibilities exist. The link name for
17686 @var{Var2} is @var{var2_link_name}, and this is not operating system
17687 dependent.
17689 @findex _main
17690 One exception occurs for library level procedures. A potential ambiguity
17691 arises between the required name @code{_main} for the C main program,
17692 and the name we would otherwise assign to an Ada library level procedure
17693 called @code{Main} (which might well not be the main program).
17695 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17696 names. So if we have a library level procedure such as
17698 @smallexample @c ada
17699 @group
17700 @cartouche
17701 procedure Hello (S : String);
17702 @end cartouche
17703 @end group
17704 @end smallexample
17706 @noindent
17707 the external name of this procedure will be @var{_ada_hello}.
17709 @ifclear vms
17710 @node Ada Mode for Glide
17711 @section Ada Mode for @code{Glide}
17712 @cindex Ada mode (for Glide)
17714 @noindent
17715 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
17716 user to understand and navigate existing code, and facilitates writing
17717 new code. It furthermore provides some utility functions for easier
17718 integration of standard Emacs features when programming in Ada.
17720 Its general features include:
17722 @itemize @bullet
17723 @item
17724 An Integrated Development Environment with functionality such as the
17725 following
17727 @itemize @bullet
17728 @item
17729 ``Project files'' for configuration-specific aspects
17730 (e.g. directories and compilation options)
17732 @item
17733 Compiling and stepping through error messages.
17735 @item
17736 Running and debugging an applications within Glide.
17737 @end itemize
17739 @item
17740 Pull-down menus
17742 @item
17743 User configurability
17744 @end itemize
17746 Some of the specific Ada mode features are:
17748 @itemize @bullet
17749 @item
17750 Functions for easy and quick stepping through Ada code
17752 @item
17753 Getting cross reference information for identifiers (e.g., finding a
17754 defining occurrence)
17756 @item
17757 Displaying an index menu of types and subprograms, allowing
17758 direct selection for browsing
17760 @item
17761 Automatic color highlighting of the various Ada entities
17762 @end itemize
17764 Glide directly supports writing Ada code, via several facilities:
17766 @itemize @bullet
17767 @item
17768 Switching between spec and body files with possible
17769 autogeneration of body files
17771 @item
17772 Automatic formating of subprogram parameter lists
17774 @item
17775 Automatic indentation according to Ada syntax
17777 @item
17778 Automatic completion of identifiers
17780 @item
17781 Automatic (and configurable) casing of identifiers, keywords, and attributes
17783 @item
17784 Insertion of syntactic templates
17786 @item
17787 Block commenting / uncommenting
17788 @end itemize
17790 @noindent
17791 For more information, please refer to the online documentation
17792 available in the @code{Glide} @result{} @code{Help} menu.
17793 @end ifclear
17796 @node Converting Ada Files to html with gnathtml
17797 @section Converting Ada Files to HTML with @code{gnathtml}
17799 @noindent
17800 This @code{Perl} script allows Ada source files to be browsed using
17801 standard Web browsers. For installation procedure, see the section
17802 @xref{Installing gnathtml}.
17804 Ada reserved keywords are highlighted in a bold font and Ada comments in
17805 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17806 switch to suppress the generation of cross-referencing information, user
17807 defined variables and types will appear in a different color; you will
17808 be able to click on any identifier and go to its declaration.
17810 The command line is as follow:
17811 @smallexample
17812 $ perl gnathtml.pl [switches] ada-files
17813 @end smallexample
17815 @noindent
17816 You can pass it as many Ada files as you want. @code{gnathtml} will generate
17817 an html file for every ada file, and a global file called @file{index.htm}.
17818 This file is an index of every identifier defined in the files.
17820 The available switches are the following ones :
17822 @table @option
17823 @item -83
17824 @cindex @option{-83} (@code{gnathtml})
17825 Only the subset on the Ada 83 keywords will be highlighted, not the full
17826 Ada 95 keywords set.
17828 @item -cc @var{color}
17829 @cindex @option{-cc} (@code{gnathtml})
17830 This option allows you to change the color used for comments. The default
17831 value is green. The color argument can be any name accepted by html.
17833 @item -d
17834 @cindex @option{-d} (@code{gnathtml})
17835 If the ada files depend on some other files (using for instance the
17836 @code{with} command, the latter will also be converted to html.
17837 Only the files in the user project will be converted to html, not the files
17838 in the run-time library itself.
17840 @item -D
17841 @cindex @option{-D} (@code{gnathtml})
17842 This command is the same as @option{-d} above, but @command{gnathtml} will
17843 also look for files in the run-time library, and generate html files for them.
17845 @item -ext @var{extension}
17846 @cindex @option{-ext} (@code{gnathtml})
17847 This option allows you to change the extension of the generated HTML files.
17848 If you do not specify an extension, it will default to @file{htm}.
17850 @item -f
17851 @cindex @option{-f} (@code{gnathtml})
17852 By default, gnathtml will generate html links only for global entities
17853 ('with'ed units, global variables and types,...). If you specify the
17854 @option{-f} on the command line, then links will be generated for local
17855 entities too.
17857 @item -l @var{number}
17858 @cindex @option{-l} (@code{gnathtml})
17859 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
17860 will number the html files every @var{number} line.
17862 @item -I @var{dir}
17863 @cindex @option{-I} (@code{gnathtml})
17864 Specify a directory to search for library files (@file{.ALI} files) and
17865 source files. You can provide several -I switches on the command line,
17866 and the directories will be parsed in the order of the command line.
17868 @item -o @var{dir}
17869 @cindex @option{-o} (@code{gnathtml})
17870 Specify the output directory for html files. By default, gnathtml will
17871 saved the generated html files in a subdirectory named @file{html/}.
17873 @item -p @var{file}
17874 @cindex @option{-p} (@code{gnathtml})
17875 If you are using Emacs and the most recent Emacs Ada mode, which provides
17876 a full Integrated Development Environment for compiling, checking,
17877 running and debugging applications, you may use @file{.gpr} files
17878 to give the directories where Emacs can find sources and object files.
17880 Using this switch, you can tell gnathtml to use these files. This allows
17881 you to get an html version of your application, even if it is spread
17882 over multiple directories.
17884 @item -sc @var{color}
17885 @cindex @option{-sc} (@code{gnathtml})
17886 This option allows you to change the color used for symbol definitions.
17887 The default value is red. The color argument can be any name accepted by html.
17889 @item -t @var{file}
17890 @cindex @option{-t} (@code{gnathtml})
17891 This switch provides the name of a file. This file contains a list of
17892 file names to be converted, and the effect is exactly as though they had
17893 appeared explicitly on the command line. This
17894 is the recommended way to work around the command line length limit on some
17895 systems.
17897 @end table
17899 @node Installing gnathtml
17900 @section Installing @code{gnathtml}
17902 @noindent
17903 @code{Perl} needs to be installed on your machine to run this script.
17904 @code{Perl} is freely available for almost every architecture and
17905 Operating System via the Internet.
17907 On Unix systems, you  may want to modify  the  first line of  the script
17908 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
17909 is. The syntax of this line is :
17910 @smallexample
17911 #!full_path_name_to_perl
17912 @end smallexample
17914 @noindent
17915 Alternatively, you may run the script using the following command line:
17917 @smallexample
17918 $ perl gnathtml.pl [switches] files
17919 @end smallexample
17921 @ifset vms
17922 @node LSE
17923 @section LSE
17924 @findex LSE
17926 @noindent
17927 The GNAT distribution provides an Ada 95 template for the Digital Language
17928 Sensitive Editor (LSE), a component of DECset. In order to
17929 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
17931 @node Profiling
17932 @section Profiling
17933 @findex PCA
17935 @noindent
17936 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
17937 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
17938 the collection phase with the /DEBUG qualifier.
17940 @smallexample
17941 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
17942 $ DEFINE LIB$DEBUG PCA$COLLECTOR
17943 $ RUN/DEBUG <PROGRAM_NAME>
17944 @end smallexample
17945 @noindent
17946 @end ifset
17948 @node Running and Debugging Ada Programs
17949 @chapter Running and Debugging Ada Programs
17950 @cindex Debugging
17952 @noindent
17953 This chapter discusses how to debug Ada programs. An incorrect Ada program
17954 may be handled in three ways by the GNAT compiler:
17956 @enumerate
17957 @item
17958 The illegality may be a violation of the static semantics of Ada. In
17959 that case GNAT diagnoses the constructs in the program that are illegal.
17960 It is then a straightforward matter for the user to modify those parts of
17961 the program.
17963 @item
17964 The illegality may be a violation of the dynamic semantics of Ada. In
17965 that case the program compiles and executes, but may generate incorrect
17966 results, or may terminate abnormally with some exception.
17968 @item
17969 When presented with a program that contains convoluted errors, GNAT
17970 itself may terminate abnormally without providing full diagnostics on
17971 the incorrect user program.
17972 @end enumerate
17974 @menu
17975 * The GNAT Debugger GDB::
17976 * Running GDB::
17977 * Introduction to GDB Commands::
17978 * Using Ada Expressions::
17979 * Calling User-Defined Subprograms::
17980 * Using the Next Command in a Function::
17981 * Ada Exceptions::
17982 * Ada Tasks::
17983 * Debugging Generic Units::
17984 * GNAT Abnormal Termination or Failure to Terminate::
17985 * Naming Conventions for GNAT Source Files::
17986 * Getting Internal Debugging Information::
17987 * Stack Traceback::
17988 @end menu
17990 @cindex Debugger
17991 @findex gdb
17993 @node The GNAT Debugger GDB
17994 @section The GNAT Debugger GDB
17996 @noindent
17997 @code{GDB} is a general purpose, platform-independent debugger that
17998 can be used to debug mixed-language programs compiled with @code{GCC},
17999 and in particular is capable of debugging Ada programs compiled with
18000 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18001 complex Ada data structures.
18003 The manual @cite{Debugging with GDB}
18004 @ifset vms
18005 , located in the GNU:[DOCS] directory,
18006 @end ifset
18007 contains full details on the usage of @code{GDB}, including a section on
18008 its usage on programs. This manual should be consulted for full
18009 details. The section that follows is a brief introduction to the
18010 philosophy and use of @code{GDB}.
18012 When GNAT programs are compiled, the compiler optionally writes debugging
18013 information into the generated object file, including information on
18014 line numbers, and on declared types and variables. This information is
18015 separate from the generated code. It makes the object files considerably
18016 larger, but it does not add to the size of the actual executable that
18017 will be loaded into memory, and has no impact on run-time performance. The
18018 generation of debug information is triggered by the use of the
18019 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18020 the compilations. It is important to emphasize that the use of these
18021 options does not change the generated code.
18023 The debugging information is written in standard system formats that
18024 are used by many tools, including debuggers and profilers. The format
18025 of the information is typically designed to describe C types and
18026 semantics, but GNAT implements a translation scheme which allows full
18027 details about Ada types and variables to be encoded into these
18028 standard C formats. Details of this encoding scheme may be found in
18029 the file exp_dbug.ads in the GNAT source distribution. However, the
18030 details of this encoding are, in general, of no interest to a user,
18031 since @code{GDB} automatically performs the necessary decoding.
18033 When a program is bound and linked, the debugging information is
18034 collected from the object files, and stored in the executable image of
18035 the program. Again, this process significantly increases the size of
18036 the generated executable file, but it does not increase the size of
18037 the executable program itself. Furthermore, if this program is run in
18038 the normal manner, it runs exactly as if the debug information were
18039 not present, and takes no more actual memory.
18041 However, if the program is run under control of @code{GDB}, the
18042 debugger is activated.  The image of the program is loaded, at which
18043 point it is ready to run.  If a run command is given, then the program
18044 will run exactly as it would have if @code{GDB} were not present. This
18045 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18046 entirely non-intrusive until a breakpoint is encountered.  If no
18047 breakpoint is ever hit, the program will run exactly as it would if no
18048 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18049 the debugging information and can respond to user commands to inspect
18050 variables, and more generally to report on the state of execution.
18052 @c **************
18053 @node Running GDB
18054 @section Running GDB
18056 @noindent
18057 The debugger can be launched directly and simply from @code{glide} or
18058 through its graphical interface: @code{gvd}. It can also be used
18059 directly in text mode. Here is described the basic use of @code{GDB}
18060 in text mode. All the commands described below can be used in the
18061 @code{gvd} console window even though there is usually other more
18062 graphical ways to achieve the same goals.
18064 @ifclear vms
18065 @noindent
18066 The command to run the graphical interface of the debugger is
18067 @smallexample
18068 $ gvd program
18069 @end smallexample
18070 @end ifclear
18072 @noindent
18073 The command to run @code{GDB} in text mode is
18075 @smallexample
18076 $ ^gdb program^$ GDB PROGRAM^
18077 @end smallexample
18079 @noindent
18080 where @code{^program^PROGRAM^} is the name of the executable file. This
18081 activates the debugger and results in a prompt for debugger commands.
18082 The simplest command is simply @code{run}, which causes the program to run
18083 exactly as if the debugger were not present. The following section
18084 describes some of the additional commands that can be given to @code{GDB}.
18087 @c *******************************
18088 @node Introduction to GDB Commands
18089 @section Introduction to GDB Commands
18091 @noindent
18092 @code{GDB} contains a large repertoire of commands. The manual
18093 @cite{Debugging with GDB}
18094 @ifset vms
18095 , located in the GNU:[DOCS] directory,
18096 @end ifset
18097 includes extensive documentation on the use
18098 of these commands, together with examples of their use. Furthermore,
18099 the command @var{help} invoked from within @code{GDB} activates a simple help
18100 facility which summarizes the available commands and their options.
18101 In this section we summarize a few of the most commonly
18102 used commands to give an idea of what @code{GDB} is about. You should create
18103 a simple program with debugging information and experiment with the use of
18104 these @code{GDB} commands on the program as you read through the
18105 following section.
18107 @table @code
18108 @item set args @var{arguments}
18109 The @var{arguments} list above is a list of arguments to be passed to
18110 the program on a subsequent run command, just as though the arguments
18111 had been entered on a normal invocation of the program. The @code{set args}
18112 command is not needed if the program does not require arguments.
18114 @item run
18115 The @code{run} command causes execution of the program to start from
18116 the beginning. If the program is already running, that is to say if
18117 you are currently positioned at a breakpoint, then a prompt will ask
18118 for confirmation that you want to abandon the current execution and
18119 restart.
18121 @item breakpoint @var{location}
18122 The breakpoint command sets a breakpoint, that is to say a point at which
18123 execution will halt and @code{GDB} will await further
18124 commands. @var{location} is
18125 either a line number within a file, given in the format @code{file:linenumber},
18126 or it is the name of a subprogram. If you request that a breakpoint be set on
18127 a subprogram that is overloaded, a prompt will ask you to specify on which of
18128 those subprograms you want to breakpoint. You can also
18129 specify that all of them should be breakpointed. If the program is run
18130 and execution encounters the breakpoint, then the program
18131 stops and @code{GDB} signals that the breakpoint was encountered by
18132 printing the line of code before which the program is halted.
18134 @item breakpoint exception @var{name}
18135 A special form of the breakpoint command which breakpoints whenever
18136 exception @var{name} is raised.
18137 If @var{name} is omitted,
18138 then a breakpoint will occur when any exception is raised.
18140 @item print @var{expression}
18141 This will print the value of the given expression. Most simple
18142 Ada expression formats are properly handled by @code{GDB}, so the expression
18143 can contain function calls, variables, operators, and attribute references.
18145 @item continue
18146 Continues execution following a breakpoint, until the next breakpoint or the
18147 termination of the program.
18149 @item step
18150 Executes a single line after a breakpoint. If the next statement
18151 is a subprogram call, execution continues into (the first statement of)
18152 the called subprogram.
18154 @item next
18155 Executes a single line. If this line is a subprogram call, executes and
18156 returns from the call.
18158 @item list
18159 Lists a few lines around the current source location. In practice, it
18160 is usually more convenient to have a separate edit window open with the
18161 relevant source file displayed. Successive applications of this command
18162 print subsequent lines. The command can be given an argument which is a
18163 line number, in which case it displays a few lines around the specified one.
18165 @item backtrace
18166 Displays a backtrace of the call chain. This command is typically
18167 used after a breakpoint has occurred, to examine the sequence of calls that
18168 leads to the current breakpoint. The display includes one line for each
18169 activation record (frame) corresponding to an active subprogram.
18171 @item up
18172 At a breakpoint, @code{GDB} can display the values of variables local
18173 to the current frame. The command @code{up} can be used to
18174 examine the contents of other active frames, by moving the focus up
18175 the stack, that is to say from callee to caller, one frame at a time.
18177 @item down
18178 Moves the focus of @code{GDB} down from the frame currently being
18179 examined to the frame of its callee (the reverse of the previous command),
18181 @item frame @var{n}
18182 Inspect the frame with the given number. The value 0 denotes the frame
18183 of the current breakpoint, that is to say the top of the call stack.
18185 @end table
18187 The above list is a very short introduction to the commands that
18188 @code{GDB} provides. Important additional capabilities, including conditional
18189 breakpoints, the ability to execute command sequences on a breakpoint,
18190 the ability to debug at the machine instruction level and many other
18191 features are described in detail in @cite{Debugging with GDB}.
18192 Note that most commands can be abbreviated
18193 (for example, c for continue, bt for backtrace).
18195 @node Using Ada Expressions
18196 @section Using Ada Expressions
18197 @cindex Ada expressions
18199 @noindent
18200 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18201 extensions. The philosophy behind the design of this subset is
18203 @itemize @bullet
18204 @item
18205 That @code{GDB} should provide basic literals and access to operations for
18206 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18207 leaving more sophisticated computations to subprograms written into the
18208 program (which therefore may be called from @code{GDB}).
18210 @item
18211 That type safety and strict adherence to Ada language restrictions
18212 are not particularly important to the @code{GDB} user.
18214 @item
18215 That brevity is important to the @code{GDB} user.
18216 @end itemize
18218 Thus, for brevity, the debugger acts as if there were
18219 implicit @code{with} and @code{use} clauses in effect for all user-written
18220 packages, thus making it unnecessary to fully qualify most names with
18221 their packages, regardless of context. Where this causes ambiguity,
18222 @code{GDB} asks the user's intent.
18224 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18226 @node Calling User-Defined Subprograms
18227 @section Calling User-Defined Subprograms
18229 @noindent
18230 An important capability of @code{GDB} is the ability to call user-defined
18231 subprograms while debugging. This is achieved simply by entering
18232 a subprogram call statement in the form:
18234 @smallexample
18235 call subprogram-name (parameters)
18236 @end smallexample
18238 @noindent
18239 The keyword @code{call} can be omitted in the normal case where the
18240 @code{subprogram-name} does not coincide with any of the predefined
18241 @code{GDB} commands.
18243 The effect is to invoke the given subprogram, passing it the
18244 list of parameters that is supplied. The parameters can be expressions and
18245 can include variables from the program being debugged. The
18246 subprogram must be defined
18247 at the library level within your program, and @code{GDB} will call the
18248 subprogram within the environment of your program execution (which
18249 means that the subprogram is free to access or even modify variables
18250 within your program).
18252 The most important use of this facility is in allowing the inclusion of
18253 debugging routines that are tailored to particular data structures
18254 in your program. Such debugging routines can be written to provide a suitably
18255 high-level description of an abstract type, rather than a low-level dump
18256 of its physical layout. After all, the standard
18257 @code{GDB print} command only knows the physical layout of your
18258 types, not their abstract meaning. Debugging routines can provide information
18259 at the desired semantic level and are thus enormously useful.
18261 For example, when debugging GNAT itself, it is crucial to have access to
18262 the contents of the tree nodes used to represent the program internally.
18263 But tree nodes are represented simply by an integer value (which in turn
18264 is an index into a table of nodes).
18265 Using the @code{print} command on a tree node would simply print this integer
18266 value, which is not very useful. But the PN routine (defined in file
18267 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18268 a useful high level representation of the tree node, which includes the
18269 syntactic category of the node, its position in the source, the integers
18270 that denote descendant nodes and parent node, as well as varied
18271 semantic information. To study this example in more detail, you might want to
18272 look at the body of the PN procedure in the stated file.
18274 @node Using the Next Command in a Function
18275 @section Using the Next Command in a Function
18277 @noindent
18278 When you use the @code{next} command in a function, the current source
18279 location will advance to the next statement as usual. A special case
18280 arises in the case of a @code{return} statement.
18282 Part of the code for a return statement is the ``epilog'' of the function.
18283 This is the code that returns to the caller. There is only one copy of
18284 this epilog code, and it is typically associated with the last return
18285 statement in the function if there is more than one return. In some
18286 implementations, this epilog is associated with the first statement
18287 of the function.
18289 The result is that if you use the @code{next} command from a return
18290 statement that is not the last return statement of the function you
18291 may see a strange apparent jump to the last return statement or to
18292 the start of the function. You should simply ignore this odd jump.
18293 The value returned is always that from the first return statement
18294 that was stepped through.
18296 @node Ada Exceptions
18297 @section Breaking on Ada Exceptions
18298 @cindex Exceptions
18300 @noindent
18301 You can set breakpoints that trip when your program raises
18302 selected exceptions.
18304 @table @code
18305 @item break exception
18306 Set a breakpoint that trips whenever (any task in the) program raises
18307 any exception.
18309 @item break exception @var{name}
18310 Set a breakpoint that trips whenever (any task in the) program raises
18311 the exception @var{name}.
18313 @item break exception unhandled
18314 Set a breakpoint that trips whenever (any task in the) program raises an
18315 exception for which there is no handler.
18317 @item info exceptions
18318 @itemx info exceptions @var{regexp}
18319 The @code{info exceptions} command permits the user to examine all defined
18320 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18321 argument, prints out only those exceptions whose name matches @var{regexp}.
18322 @end table
18324 @node Ada Tasks
18325 @section Ada Tasks
18326 @cindex Tasks
18328 @noindent
18329 @code{GDB} allows the following task-related commands:
18331 @table @code
18332 @item info tasks
18333 This command shows a list of current Ada tasks, as in the following example:
18335 @smallexample
18336 @iftex
18337 @leftskip=0cm
18338 @end iftex
18339 (gdb) info tasks
18340   ID       TID P-ID   Thread Pri State                 Name
18341    1   8088000   0   807e000  15 Child Activation Wait main_task
18342    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18343    3   809a800   1   80a4800  15 Child Activation Wait a
18344 *  4   80ae800   3   80b8000  15 Running               c
18345 @end smallexample
18347 @noindent
18348 In this listing, the asterisk before the first task indicates it to be the
18349 currently running task. The first column lists the task ID that is used
18350 to refer to tasks in the following commands.
18352 @item break @var{linespec} task @var{taskid}
18353 @itemx break @var{linespec} task @var{taskid} if @dots{}
18354 @cindex Breakpoints and tasks
18355 These commands are like the @code{break @dots{} thread @dots{}}.
18356 @var{linespec} specifies source lines.
18358 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18359 to specify that you only want @code{GDB} to stop the program when a
18360 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18361 numeric task identifiers assigned by @code{GDB}, shown in the first
18362 column of the @samp{info tasks} display.
18364 If you do not specify @samp{task @var{taskid}} when you set a
18365 breakpoint, the breakpoint applies to @emph{all} tasks of your
18366 program.
18368 You can use the @code{task} qualifier on conditional breakpoints as
18369 well; in this case, place @samp{task @var{taskid}} before the
18370 breakpoint condition (before the @code{if}).
18372 @item task @var{taskno}
18373 @cindex Task switching
18375 This command allows to switch to the task referred by @var{taskno}. In
18376 particular, This allows to browse the backtrace of the specified
18377 task. It is advised to switch back to the original task before
18378 continuing execution otherwise the scheduling of the program may be
18379 perturbated.
18380 @end table
18382 @noindent
18383 For more detailed information on the tasking support,
18384 see @cite{Debugging with GDB}.
18386 @node Debugging Generic Units
18387 @section Debugging Generic Units
18388 @cindex Debugging Generic Units
18389 @cindex Generics
18391 @noindent
18392 GNAT always uses code expansion for generic instantiation. This means that
18393 each time an instantiation occurs, a complete copy of the original code is
18394 made, with appropriate substitutions of formals by actuals.
18396 It is not possible to refer to the original generic entities in
18397 @code{GDB}, but it is always possible to debug a particular instance of
18398 a generic, by using the appropriate expanded names. For example, if we have
18400 @smallexample @c ada
18401 @group
18402 @cartouche
18403 procedure g is
18405    generic package k is
18406       procedure kp (v1 : in out integer);
18407    end k;
18409    package body k is
18410       procedure kp (v1 : in out integer) is
18411       begin
18412          v1 := v1 + 1;
18413       end kp;
18414    end k;
18416    package k1 is new k;
18417    package k2 is new k;
18419    var : integer := 1;
18421 begin
18422    k1.kp (var);
18423    k2.kp (var);
18424    k1.kp (var);
18425    k2.kp (var);
18426 end;
18427 @end cartouche
18428 @end group
18429 @end smallexample
18431 @noindent
18432 Then to break on a call to procedure kp in the k2 instance, simply
18433 use the command:
18435 @smallexample
18436 (gdb) break g.k2.kp
18437 @end smallexample
18439 @noindent
18440 When the breakpoint occurs, you can step through the code of the
18441 instance in the normal manner and examine the values of local variables, as for
18442 other units.
18444 @node GNAT Abnormal Termination or Failure to Terminate
18445 @section GNAT Abnormal Termination or Failure to Terminate
18446 @cindex GNAT Abnormal Termination or Failure to Terminate
18448 @noindent
18449 When presented with programs that contain serious errors in syntax
18450 or semantics,
18451 GNAT may on rare occasions  experience problems in operation, such
18452 as aborting with a
18453 segmentation fault or illegal memory access, raising an internal
18454 exception, terminating abnormally, or failing to terminate at all.
18455 In such cases, you can activate
18456 various features of GNAT that can help you pinpoint the construct in your
18457 program that is the likely source of the problem.
18459 The following strategies are presented in increasing order of
18460 difficulty, corresponding to your experience in using GNAT and your
18461 familiarity with compiler internals.
18463 @enumerate
18464 @item
18465 Run @code{gcc} with the @option{-gnatf}. This first
18466 switch causes all errors on a given line to be reported. In its absence,
18467 only the first error on a line is displayed.
18469 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18470 are encountered, rather than after compilation is terminated. If GNAT
18471 terminates prematurely or goes into an infinite loop, the last error
18472 message displayed may help to pinpoint the culprit.
18474 @item
18475 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
18476 @code{gcc} produces ongoing information about the progress of the
18477 compilation and provides the name of each procedure as code is
18478 generated. This switch allows you to find which Ada procedure was being
18479 compiled when it encountered a code generation problem.
18481 @item
18482 @cindex @option{-gnatdc} switch
18483 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18484 switch that does for the front-end what @option{^-v^VERBOSE^} does
18485 for the back end. The system prints the name of each unit,
18486 either a compilation unit or nested unit, as it is being analyzed.
18487 @item
18488 Finally, you can start
18489 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18490 front-end of GNAT, and can be run independently (normally it is just
18491 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18492 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18493 @code{where} command is the first line of attack; the variable
18494 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18495 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18496 which the execution stopped, and @code{input_file name} indicates the name of
18497 the source file.
18498 @end enumerate
18500 @node Naming Conventions for GNAT Source Files
18501 @section Naming Conventions for GNAT Source Files
18503 @noindent
18504 In order to examine the workings of the GNAT system, the following
18505 brief description of its organization may be helpful:
18507 @itemize @bullet
18508 @item
18509 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18511 @item
18512 All files prefixed with @file{^par^PAR^} are components of the parser. The
18513 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
18514 parsing of select statements can be found in @file{par-ch9.adb}.
18516 @item
18517 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18518 numbers correspond to chapters of the Ada standard. For example, all
18519 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18520 addition, some features of the language require sufficient special processing
18521 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18522 dynamic dispatching, etc.
18524 @item
18525 All files prefixed with @file{^exp^EXP^} perform normalization and
18526 expansion of the intermediate representation (abstract syntax tree, or AST).
18527 these files use the same numbering scheme as the parser and semantics files.
18528 For example, the construction of record initialization procedures is done in
18529 @file{exp_ch3.adb}.
18531 @item
18532 The files prefixed with @file{^bind^BIND^} implement the binder, which
18533 verifies the consistency of the compilation, determines an order of
18534 elaboration, and generates the bind file.
18536 @item
18537 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18538 data structures used by the front-end.
18540 @item
18541 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18542 the abstract syntax tree as produced by the parser.
18544 @item
18545 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18546 all entities, computed during semantic analysis.
18548 @item
18549 Library management issues are dealt with in files with prefix
18550 @file{^lib^LIB^}.
18552 @item
18553 @findex Ada
18554 @cindex Annex A
18555 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18556 defined in Annex A.
18558 @item
18559 @findex Interfaces
18560 @cindex Annex B
18561 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18562 defined in Annex B.
18564 @item
18565 @findex System
18566 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18567 both language-defined children and GNAT run-time routines.
18569 @item
18570 @findex GNAT
18571 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18572 general-purpose packages, fully documented in their specifications. All
18573 the other @file{.c} files are modifications of common @code{gcc} files.
18574 @end itemize
18576 @node Getting Internal Debugging Information
18577 @section Getting Internal Debugging Information
18579 @noindent
18580 Most compilers have internal debugging switches and modes. GNAT
18581 does also, except GNAT internal debugging switches and modes are not
18582 secret. A summary and full description of all the compiler and binder
18583 debug flags are in the file @file{debug.adb}. You must obtain the
18584 sources of the compiler to see the full detailed effects of these flags.
18586 The switches that print the source of the program (reconstructed from
18587 the internal tree) are of general interest for user programs, as are the
18588 options to print
18589 the full internal tree, and the entity table (the symbol table
18590 information). The reconstructed source provides a readable version of the
18591 program after the front-end has completed analysis and  expansion,
18592 and is useful when studying the performance of specific constructs.
18593 For example, constraint checks are indicated, complex aggregates
18594 are replaced with loops and assignments, and tasking primitives
18595 are replaced with run-time calls.
18597 @node Stack Traceback
18598 @section Stack Traceback
18599 @cindex traceback
18600 @cindex stack traceback
18601 @cindex stack unwinding
18603 @noindent
18604 Traceback is a mechanism to display the sequence of subprogram calls that
18605 leads to a specified execution point in a program. Often (but not always)
18606 the execution point is an instruction at which an exception has been raised.
18607 This mechanism is also known as @i{stack unwinding} because it obtains
18608 its information by scanning the run-time stack and recovering the activation
18609 records of all active subprograms. Stack unwinding is one of the most
18610 important tools for program debugging.
18612 The first entry stored in traceback corresponds to the deepest calling level,
18613 that is to say the subprogram currently executing the instruction
18614 from which we want to obtain the traceback.
18616 Note that there is no runtime performance penalty when stack traceback
18617 is enabled, and no exception is raised during program execution.
18619 @menu
18620 * Non-Symbolic Traceback::
18621 * Symbolic Traceback::
18622 @end menu
18624 @node Non-Symbolic Traceback
18625 @subsection Non-Symbolic Traceback
18626 @cindex traceback, non-symbolic
18628 @noindent
18629 Note: this feature is not supported on all platforms. See
18630 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
18631 platforms.
18633 @menu
18634 * Tracebacks From an Unhandled Exception::
18635 * Tracebacks From Exception Occurrences (non-symbolic)::
18636 * Tracebacks From Anywhere in a Program (non-symbolic)::
18637 @end menu
18639 @node Tracebacks From an Unhandled Exception
18640 @subsubsection Tracebacks From an Unhandled Exception
18642 @noindent
18643 A runtime non-symbolic traceback is a list of addresses of call instructions.
18644 To enable this feature you must use the @option{-E}
18645 @code{gnatbind}'s option. With this option a stack traceback is stored as part
18646 of exception information. You can retrieve this information using the
18647 @code{addr2line} tool.
18649 Here is a simple example:
18651 @smallexample @c ada
18652 @cartouche
18653 procedure STB is
18655    procedure P1 is
18656    begin
18657       raise Constraint_Error;
18658    end P1;
18660    procedure P2 is
18661    begin
18662       P1;
18663    end P2;
18665 begin
18666    P2;
18667 end STB;
18668 @end cartouche
18669 @end smallexample
18671 @smallexample
18672 $ gnatmake stb -bargs -E
18673 $ stb
18675 Execution terminated by unhandled exception
18676 Exception name: CONSTRAINT_ERROR
18677 Message: stb.adb:5
18678 Call stack traceback locations:
18679 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18680 @end smallexample
18682 @noindent
18683 As we see the traceback lists a sequence of addresses for the unhandled
18684 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18685 guess that this exception come from procedure P1. To translate these
18686 addresses into the source lines where the calls appear, the
18687 @code{addr2line} tool, described below, is invaluable. The use of this tool
18688 requires the program to be compiled with debug information.
18690 @smallexample
18691 $ gnatmake -g stb -bargs -E
18692 $ stb
18694 Execution terminated by unhandled exception
18695 Exception name: CONSTRAINT_ERROR
18696 Message: stb.adb:5
18697 Call stack traceback locations:
18698 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18700 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
18701    0x4011f1 0x77e892a4
18703 00401373 at d:/stb/stb.adb:5
18704 0040138B at d:/stb/stb.adb:10
18705 0040139C at d:/stb/stb.adb:14
18706 00401335 at d:/stb/b~stb.adb:104
18707 004011C4 at /build/.../crt1.c:200
18708 004011F1 at /build/.../crt1.c:222
18709 77E892A4 in ?? at ??:0
18710 @end smallexample
18712 @noindent
18713 The @code{addr2line} tool has several other useful options:
18715 @table @code
18716 @item --functions
18717 to get the function name corresponding to any location
18719 @item --demangle=gnat
18720 to use the gnat decoding mode for the function names. Note that
18721 for binutils version 2.9.x the option is simply @option{--demangle}.
18722 @end table
18724 @smallexample
18725 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
18726    0x40139c 0x401335 0x4011c4 0x4011f1
18728 00401373 in stb.p1 at d:/stb/stb.adb:5
18729 0040138B in stb.p2 at d:/stb/stb.adb:10
18730 0040139C in stb at d:/stb/stb.adb:14
18731 00401335 in main at d:/stb/b~stb.adb:104
18732 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
18733 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
18734 @end smallexample
18736 @noindent
18737 From this traceback we can see that the exception was raised in
18738 @file{stb.adb} at line 5, which was reached from a procedure call in
18739 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
18740 which contains the call to the main program.
18741 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
18742 and the output will vary from platform to platform.
18744 It is also possible to use @code{GDB} with these traceback addresses to debug
18745 the program. For example, we can break at a given code location, as reported
18746 in the stack traceback:
18748 @smallexample
18749 $ gdb -nw stb
18750 @ifclear vms
18751 @noindent
18752 Furthermore, this feature is not implemented inside Windows DLL. Only
18753 the non-symbolic traceback is reported in this case.
18754 @end ifclear
18756 (gdb) break *0x401373
18757 Breakpoint 1 at 0x401373: file stb.adb, line 5.
18758 @end smallexample
18760 @noindent
18761 It is important to note that the stack traceback addresses
18762 do not change when debug information is included. This is particularly useful
18763 because it makes it possible to release software without debug information (to
18764 minimize object size), get a field report that includes a stack traceback
18765 whenever an internal bug occurs, and then be able to retrieve the sequence
18766 of calls with the same program compiled with debug information.
18768 @node Tracebacks From Exception Occurrences (non-symbolic)
18769 @subsubsection Tracebacks From Exception Occurrences
18771 @noindent
18772 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
18773 The stack traceback is attached to the exception information string, and can
18774 be retrieved in an exception handler within the Ada program, by means of the
18775 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
18777 @smallexample @c ada
18778 with Ada.Text_IO;
18779 with Ada.Exceptions;
18781 procedure STB is
18783    use Ada;
18784    use Ada.Exceptions;
18786    procedure P1 is
18787       K : Positive := 1;
18788    begin
18789       K := K - 1;
18790    exception
18791       when E : others =>
18792          Text_IO.Put_Line (Exception_Information (E));
18793    end P1;
18795    procedure P2 is
18796    begin
18797       P1;
18798    end P2;
18800 begin
18801    P2;
18802 end STB;
18803 @end smallexample
18805 @noindent
18806 This program will output:
18808 @smallexample
18809 $ stb
18811 Exception name: CONSTRAINT_ERROR
18812 Message: stb.adb:12
18813 Call stack traceback locations:
18814 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
18815 @end smallexample
18817 @node Tracebacks From Anywhere in a Program (non-symbolic)
18818 @subsubsection Tracebacks From Anywhere in a Program
18820 @noindent
18821 It is also possible to retrieve a stack traceback from anywhere in a
18822 program. For this you need to
18823 use the @code{GNAT.Traceback} API. This package includes a procedure called
18824 @code{Call_Chain} that computes a complete stack traceback, as well as useful
18825 display procedures described below. It is not necessary to use the
18826 @option{-E gnatbind} option in this case, because the stack traceback mechanism
18827 is invoked explicitly.
18829 @noindent
18830 In the following example we compute a traceback at a specific location in
18831 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
18832 convert addresses to strings:
18834 @smallexample @c ada
18835 with Ada.Text_IO;
18836 with GNAT.Traceback;
18837 with GNAT.Debug_Utilities;
18839 procedure STB is
18841    use Ada;
18842    use GNAT;
18843    use GNAT.Traceback;
18845    procedure P1 is
18846       TB  : Tracebacks_Array (1 .. 10);
18847       --  We are asking for a maximum of 10 stack frames.
18848       Len : Natural;
18849       --  Len will receive the actual number of stack frames returned.
18850    begin
18851       Call_Chain (TB, Len);
18853       Text_IO.Put ("In STB.P1 : ");
18855       for K in 1 .. Len loop
18856          Text_IO.Put (Debug_Utilities.Image (TB (K)));
18857          Text_IO.Put (' ');
18858       end loop;
18860       Text_IO.New_Line;
18861    end P1;
18863    procedure P2 is
18864    begin
18865       P1;
18866    end P2;
18868 begin
18869    P2;
18870 end STB;
18871 @end smallexample
18873 @smallexample
18874 $ gnatmake -g stb
18875 $ stb
18877 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
18878 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
18879 @end smallexample
18881 @noindent
18882 You can then get further information by invoking the @code{addr2line}
18883 tool as described earlier (note that the hexadecimal addresses
18884 need to be specified in C format, with a leading ``0x'').
18887 @node Symbolic Traceback
18888 @subsection Symbolic Traceback
18889 @cindex traceback, symbolic
18891 @noindent
18892 A symbolic traceback is a stack traceback in which procedure names are
18893 associated with each code location.
18895 @noindent
18896 Note that this feature is not supported on all platforms. See
18897 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
18898 list of currently supported platforms.
18900 @noindent
18901 Note that the symbolic traceback requires that the program be compiled
18902 with debug information. If it is not compiled with debug information
18903 only the non-symbolic information will be valid.
18905 @menu
18906 * Tracebacks From Exception Occurrences (symbolic)::
18907 * Tracebacks From Anywhere in a Program (symbolic)::
18908 @end menu
18910 @node Tracebacks From Exception Occurrences (symbolic)
18911 @subsubsection Tracebacks From Exception Occurrences
18913 @smallexample @c ada
18914 with Ada.Text_IO;
18915 with GNAT.Traceback.Symbolic;
18917 procedure STB is
18919    procedure P1 is
18920    begin
18921       raise Constraint_Error;
18922    end P1;
18924    procedure P2 is
18925    begin
18926       P1;
18927    end P2;
18929    procedure P3 is
18930    begin
18931       P2;
18932    end P3;
18934 begin
18935    P3;
18936 exception
18937    when E : others =>
18938       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
18939 end STB;
18940 @end smallexample
18942 @smallexample
18943 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
18944 $ stb
18946 0040149F in stb.p1 at stb.adb:8
18947 004014B7 in stb.p2 at stb.adb:13
18948 004014CF in stb.p3 at stb.adb:18
18949 004015DD in ada.stb at stb.adb:22
18950 00401461 in main at b~stb.adb:168
18951 004011C4 in __mingw_CRTStartup at crt1.c:200
18952 004011F1 in mainCRTStartup at crt1.c:222
18953 77E892A4 in ?? at ??:0
18954 @end smallexample
18956 @noindent
18957 In the above example the ``.\'' syntax in the @command{gnatmake} command
18958 is currently required by @command{addr2line} for files that are in
18959 the current working directory.
18960 Moreover, the exact sequence of linker options may vary from platform
18961 to platform.
18962 The above @option{-largs} section is for Windows platforms. By contrast,
18963 under Unix there is no need for the @option{-largs} section.
18964 Differences across platforms are due to details of linker implementation.
18966 @node Tracebacks From Anywhere in a Program (symbolic)
18967 @subsubsection Tracebacks From Anywhere in a Program
18969 @noindent
18970 It is possible to get a symbolic stack traceback
18971 from anywhere in a program, just as for non-symbolic tracebacks.
18972 The first step is to obtain a non-symbolic
18973 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
18974 information. Here is an example:
18976 @smallexample @c ada
18977 with Ada.Text_IO;
18978 with GNAT.Traceback;
18979 with GNAT.Traceback.Symbolic;
18981 procedure STB is
18983    use Ada;
18984    use GNAT.Traceback;
18985    use GNAT.Traceback.Symbolic;
18987    procedure P1 is
18988       TB  : Tracebacks_Array (1 .. 10);
18989       --  We are asking for a maximum of 10 stack frames.
18990       Len : Natural;
18991       --  Len will receive the actual number of stack frames returned.
18992    begin
18993       Call_Chain (TB, Len);
18994       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
18995    end P1;
18997    procedure P2 is
18998    begin
18999       P1;
19000    end P2;
19002 begin
19003    P2;
19004 end STB;
19005 @end smallexample
19007 @ifset vms
19008 @node Compatibility with DEC Ada
19009 @chapter Compatibility with DEC Ada
19010 @cindex Compatibility
19012 @noindent
19013 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19014 OpenVMS Alpha. GNAT achieves a high level of compatibility
19015 with DEC Ada, and it should generally be straightforward to port code
19016 from the DEC Ada environment to GNAT. However, there are a few language
19017 and implementation differences of which the user must be aware. These
19018 differences are discussed in this section. In
19019 addition, the operating environment and command structure for the
19020 compiler are different, and these differences are also discussed.
19022 Note that this discussion addresses specifically the implementation
19023 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19024 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19025 GNAT always follows the Alpha implementation.
19027 @menu
19028 * Ada 95 Compatibility::
19029 * Differences in the Definition of Package System::
19030 * Language-Related Features::
19031 * The Package STANDARD::
19032 * The Package SYSTEM::
19033 * Tasking and Task-Related Features::
19034 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19035 * Pragmas and Pragma-Related Features::
19036 * Library of Predefined Units::
19037 * Bindings::
19038 * Main Program Definition::
19039 * Implementation-Defined Attributes::
19040 * Compiler and Run-Time Interfacing::
19041 * Program Compilation and Library Management::
19042 * Input-Output::
19043 * Implementation Limits::
19044 * Tools::
19045 @end menu
19047 @node Ada 95 Compatibility
19048 @section Ada 95 Compatibility
19050 @noindent
19051 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19052 compiler. Ada 95 is almost completely upwards compatible
19053 with Ada 83, and therefore Ada 83 programs will compile
19054 and run under GNAT with
19055 no changes or only minor changes. The Ada 95 Reference
19056 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19057 incompatibilities.
19059 GNAT provides the switch /83 on the GNAT COMPILE command,
19060 as well as the pragma ADA_83, to force the compiler to
19061 operate in Ada 83 mode. This mode does not guarantee complete
19062 conformance to Ada 83, but in practice is sufficient to
19063 eliminate most sources of incompatibilities.
19064 In particular, it eliminates the recognition of the
19065 additional Ada 95 keywords, so that their use as identifiers
19066 in Ada83 program is legal, and handles the cases of packages
19067 with optional bodies, and generics that instantiate unconstrained
19068 types without the use of @code{(<>)}.
19070 @node Differences in the Definition of Package System
19071 @section Differences in the Definition of Package System
19073 @noindent
19074 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
19075 implementation-dependent declarations to package System. In normal mode,
19076 GNAT does not take advantage of this permission, and the version of System
19077 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
19079 However, DEC Ada adds an extensive set of declarations to package System,
19080 as fully documented in the DEC Ada manuals. To minimize changes required
19081 for programs that make use of these extensions, GNAT provides the pragma
19082 Extend_System for extending the definition of package System. By using:
19084 @smallexample @c ada
19085 @group
19086 @cartouche
19087 pragma Extend_System (Aux_DEC);
19088 @end cartouche
19089 @end group
19090 @end smallexample
19092 @noindent
19093 The set of definitions in System is extended to include those in package
19094 @code{System.Aux_DEC}.
19095 These definitions are incorporated directly into package
19096 System, as though they had been declared there in the first place. For a
19097 list of the declarations added, see the specification of this package,
19098 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
19099 The pragma Extend_System is a configuration pragma, which means that
19100 it can be placed in the file @file{gnat.adc}, so that it will automatically
19101 apply to all subsequent compilations. See the section on Configuration
19102 Pragmas for further details.
19104 An alternative approach that avoids the use of the non-standard
19105 Extend_System pragma is to add a context clause to the unit that
19106 references these facilities:
19108 @smallexample @c ada
19109 @group
19110 @cartouche
19111 with System.Aux_DEC;
19112 use  System.Aux_DEC;
19113 @end cartouche
19114 @end group
19115 @end smallexample
19117 @noindent
19118 The effect is not quite semantically identical to incorporating
19119 the declarations directly into package @code{System},
19120 but most programs will not notice a difference
19121 unless they use prefix notation (e.g. @code{System.Integer_8})
19122 to reference the
19123 entities directly in package @code{System}.
19124 For units containing such references,
19125 the prefixes must either be removed, or the pragma @code{Extend_System}
19126 must be used.
19128 @node Language-Related Features
19129 @section Language-Related Features
19131 @noindent
19132 The following sections highlight differences in types,
19133 representations of types, operations, alignment, and
19134 related topics.
19136 @menu
19137 * Integer Types and Representations::
19138 * Floating-Point Types and Representations::
19139 * Pragmas Float_Representation and Long_Float::
19140 * Fixed-Point Types and Representations::
19141 * Record and Array Component Alignment::
19142 * Address Clauses::
19143 * Other Representation Clauses::
19144 @end menu
19146 @node Integer Types and Representations
19147 @subsection Integer Types and Representations
19149 @noindent
19150 The set of predefined integer types is identical in DEC Ada and GNAT.
19151 Furthermore the representation of these integer types is also identical,
19152 including the capability of size clauses forcing biased representation.
19154 In addition,
19155 DEC Ada for OpenVMS Alpha systems has defined the
19156 following additional integer types in package System:
19158 @itemize @bullet
19160 @item
19161 INTEGER_8
19163 @item
19164 INTEGER_16
19166 @item
19167 INTEGER_32
19169 @item
19170 INTEGER_64
19172 @item
19173 LARGEST_INTEGER
19174 @end itemize
19176 @noindent
19177 When using GNAT, the first four of these types may be obtained from the
19178 standard Ada 95 package @code{Interfaces}.
19179 Alternatively, by use of the pragma
19180 @code{Extend_System}, identical
19181 declarations can be referenced directly in package @code{System}.
19182 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
19184 @node Floating-Point Types and Representations
19185 @subsection Floating-Point Types and Representations
19186 @cindex Floating-Point types
19188 @noindent
19189 The set of predefined floating-point types is identical in DEC Ada and GNAT.
19190 Furthermore the representation of these floating-point
19191 types is also identical. One important difference is that the default
19192 representation for DEC Ada is VAX_Float, but the default representation
19193 for GNAT is IEEE.
19195 Specific types may be declared to be VAX_Float or IEEE, using the pragma
19196 @code{Float_Representation} as described in the DEC Ada documentation.
19197 For example, the declarations:
19199 @smallexample @c ada
19200 @group
19201 @cartouche
19202 type F_Float is digits 6;
19203 pragma Float_Representation (VAX_Float, F_Float);
19204 @end cartouche
19205 @end group
19206 @end smallexample
19208 @noindent
19209 declare a type F_Float that will be represented in VAX_Float format.
19210 This set of declarations actually appears in System.Aux_DEC, which provides
19211 the full set of additional floating-point declarations provided in
19212 the DEC Ada version of package
19213 System. This and similar declarations may be accessed in a user program
19214 by using pragma @code{Extend_System}. The use of this
19215 pragma, and the related pragma @code{Long_Float} is described in further
19216 detail in the following section.
19218 @node Pragmas Float_Representation and Long_Float
19219 @subsection Pragmas Float_Representation and Long_Float
19221 @noindent
19222 DEC Ada provides the pragma @code{Float_Representation}, which
19223 acts as a program library switch to allow control over
19224 the internal representation chosen for the predefined
19225 floating-point types declared in the package @code{Standard}.
19226 The format of this pragma is as follows:
19228 @smallexample
19229 @group
19230 @cartouche
19231 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
19232 @end cartouche
19233 @end group
19234 @end smallexample
19236 @noindent
19237 This pragma controls the representation of floating-point
19238 types as follows:
19240 @itemize @bullet
19241 @item
19242 @code{VAX_Float} specifies that floating-point
19243 types are represented by default with the VAX hardware types
19244 F-floating, D-floating, G-floating. Note that the H-floating
19245 type is available only on DIGITAL Vax systems, and is not available
19246 in either DEC Ada or GNAT for Alpha systems.
19248 @item
19249 @code{IEEE_Float} specifies that floating-point
19250 types are represented by default with the IEEE single and
19251 double floating-point types.
19252 @end itemize
19254 @noindent
19255 GNAT provides an identical implementation of the pragma
19256 @code{Float_Representation}, except that it functions as a
19257 configuration pragma, as defined by Ada 95. Note that the
19258 notion of configuration pragma corresponds closely to the
19259 DEC Ada notion of a program library switch.
19261 When no pragma is used in GNAT, the default is IEEE_Float, which is different
19262 from DEC Ada 83, where the default is VAX_Float. In addition, the
19263 predefined libraries in GNAT are built using IEEE_Float, so it is not
19264 advisable to change the format of numbers passed to standard library
19265 routines, and if necessary explicit type conversions may be needed.
19267 The use of IEEE_Float is recommended in GNAT since it is more efficient,
19268 and (given that it conforms to an international standard) potentially more
19269 portable. The situation in which VAX_Float may be useful is in interfacing
19270 to existing code and data that expects the use of VAX_Float. There are
19271 two possibilities here. If the requirement for the use of VAX_Float is
19272 localized, then the best approach is to use the predefined VAX_Float
19273 types in package @code{System}, as extended by
19274 @code{Extend_System}. For example, use @code{System.F_Float}
19275 to specify the 32-bit @code{F-Float} format.
19277 Alternatively, if an entire program depends heavily on the use of
19278 the @code{VAX_Float} and in particular assumes that the types in
19279 package @code{Standard} are in @code{Vax_Float} format, then it
19280 may be desirable to reconfigure GNAT to assume Vax_Float by default.
19281 This is done by using the GNAT LIBRARY command to rebuild the library, and
19282 then using the general form of the @code{Float_Representation}
19283 pragma to ensure that this default format is used throughout.
19284 The form of the GNAT LIBRARY command is:
19286 @smallexample
19287 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
19288 @end smallexample
19290 @noindent
19291 where @i{file} contains the new configuration pragmas
19292 and @i{directory} is the directory to be created to contain
19293 the new library.
19295 @noindent
19296 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
19297 to allow control over the internal representation chosen
19298 for the predefined type @code{Long_Float} and for floating-point
19299 type declarations with digits specified in the range 7 .. 15.
19300 The format of this pragma is as follows:
19302 @smallexample @c ada
19303 @cartouche
19304 pragma Long_Float (D_FLOAT | G_FLOAT);
19305 @end cartouche
19306 @end smallexample
19308 @node Fixed-Point Types and Representations
19309 @subsection Fixed-Point Types and Representations
19311 @noindent
19312 On DEC Ada for OpenVMS Alpha systems, rounding is
19313 away from zero for both positive and negative numbers.
19314 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
19316 On GNAT for OpenVMS Alpha, the results of operations
19317 on fixed-point types are in accordance with the Ada 95
19318 rules. In particular, results of operations on decimal
19319 fixed-point types are truncated.
19321 @node Record and Array Component Alignment
19322 @subsection Record and Array Component Alignment
19324 @noindent
19325 On DEC Ada for OpenVMS Alpha, all non composite components
19326 are aligned on natural boundaries. For example, 1-byte
19327 components are aligned on byte boundaries, 2-byte
19328 components on 2-byte boundaries, 4-byte components on 4-byte
19329 byte boundaries, and so on. The OpenVMS Alpha hardware
19330 runs more efficiently with naturally aligned data.
19332 ON GNAT for OpenVMS Alpha, alignment rules are compatible
19333 with DEC Ada for OpenVMS Alpha.
19335 @node Address Clauses
19336 @subsection Address Clauses
19338 @noindent
19339 In DEC Ada and GNAT, address clauses are supported for
19340 objects and imported subprograms.
19341 The predefined type @code{System.Address} is a private type
19342 in both compilers, with the same representation (it is simply
19343 a machine pointer). Addition, subtraction, and comparison
19344 operations are available in the standard Ada 95 package
19345 @code{System.Storage_Elements}, or in package @code{System}
19346 if it is extended to include @code{System.Aux_DEC} using a
19347 pragma @code{Extend_System} as previously described.
19349 Note that code that with's both this extended package @code{System}
19350 and the package @code{System.Storage_Elements} should not @code{use}
19351 both packages, or ambiguities will result. In general it is better
19352 not to mix these two sets of facilities. The Ada 95 package was
19353 designed specifically to provide the kind of features that DEC Ada
19354 adds directly to package @code{System}.
19356 GNAT is compatible with DEC Ada in its handling of address
19357 clauses, except for some limitations in
19358 the form of address clauses for composite objects with
19359 initialization. Such address clauses are easily replaced
19360 by the use of an explicitly-defined constant as described
19361 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
19362 of declarations:
19364 @smallexample @c ada
19365 @cartouche
19366 X, Y : Integer := Init_Func;
19367 Q : String (X .. Y) := "abc";
19369 for Q'Address use Compute_Address;
19370 @end cartouche
19371 @end smallexample
19373 @noindent
19374 will be rejected by GNAT, since the address cannot be computed at the time
19375 that Q is declared. To achieve the intended effect, write instead:
19377 @smallexample @c ada
19378 @group
19379 @cartouche
19380 X, Y : Integer := Init_Func;
19381 Q_Address : constant Address := Compute_Address;
19382 Q : String (X .. Y) := "abc";
19384 for Q'Address use Q_Address;
19385 @end cartouche
19386 @end group
19387 @end smallexample
19389 @noindent
19390 which will be accepted by GNAT (and other Ada 95 compilers), and is also
19391 backwards compatible with Ada 83. A fuller description of the restrictions
19392 on address specifications is found in the GNAT Reference Manual.
19394 @node Other Representation Clauses
19395 @subsection Other Representation Clauses
19397 @noindent
19398 GNAT supports in a compatible manner all the representation
19399 clauses supported by DEC Ada. In addition, it
19400 supports representation clause forms that are new in Ada 95
19401 including COMPONENT_SIZE and SIZE clauses for objects.
19403 @node The Package STANDARD
19404 @section The Package STANDARD
19406 @noindent
19407 The package STANDARD, as implemented by DEC Ada, is fully
19408 described in the Reference Manual for the Ada Programming
19409 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
19410 Language Reference Manual. As implemented by GNAT, the
19411 package STANDARD is described in the Ada 95 Reference
19412 Manual.
19414 In addition, DEC Ada supports the Latin-1 character set in
19415 the type CHARACTER. GNAT supports the Latin-1 character set
19416 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
19417 the type WIDE_CHARACTER.
19419 The floating-point types supported by GNAT are those
19420 supported by DEC Ada, but defaults are different, and are controlled by
19421 pragmas. See @pxref{Floating-Point Types and Representations} for details.
19423 @node The Package SYSTEM
19424 @section The Package SYSTEM
19426 @noindent
19427 DEC Ada provides a system-specific version of the package
19428 SYSTEM for each platform on which the language ships.
19429 For the complete specification of the package SYSTEM, see
19430 Appendix F of the DEC Ada Language Reference Manual.
19432 On DEC Ada, the package SYSTEM includes the following conversion functions:
19433 @itemize @bullet
19434 @item TO_ADDRESS(INTEGER)
19436 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
19438 @item  TO_ADDRESS(universal_integer)
19440 @item  TO_INTEGER(ADDRESS)
19442 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
19444 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
19445                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
19446 @end itemize
19448 @noindent
19449 By default, GNAT supplies a version of SYSTEM that matches
19450 the definition given in the Ada 95 Reference Manual.
19451 This
19452 is a subset of the DIGITAL system definitions, which is as
19453 close as possible to the original definitions. The only difference
19454 is that the definition of SYSTEM_NAME is different:
19456 @smallexample @c ada
19457 @group
19458 @cartouche
19459 type Name is (SYSTEM_NAME_GNAT);
19460 System_Name : constant Name := SYSTEM_NAME_GNAT;
19461 @end cartouche
19462 @end group
19463 @end smallexample
19465 @noindent
19466 Also, GNAT adds the new Ada 95 declarations for
19467 BIT_ORDER and DEFAULT_BIT_ORDER.
19469 However, the use of the following pragma causes GNAT
19470 to extend the definition of package SYSTEM so that it
19471 encompasses the full set of DIGITAL-specific extensions,
19472 including the functions listed above:
19474 @smallexample @c ada
19475 @cartouche
19476 pragma Extend_System (Aux_DEC);
19477 @end cartouche
19478 @end smallexample
19480 @noindent
19481 The pragma Extend_System is a configuration pragma that
19482 is most conveniently placed in the @file{gnat.adc} file. See the
19483 GNAT Reference Manual for further details.
19485 DEC Ada does not allow the recompilation of the package
19486 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
19487 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
19488 the package SYSTEM. On OpenVMS Alpha systems, the pragma
19489 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
19490 its single argument.
19492 GNAT does permit the recompilation of package SYSTEM using
19493 a special switch (@option{-gnatg}) and this switch can be used if
19494 it is necessary to modify the definitions in SYSTEM. GNAT does
19495 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
19496 or MEMORY_SIZE by any other means.
19498 On GNAT systems, the pragma SYSTEM_NAME takes the
19499 enumeration literal SYSTEM_NAME_GNAT.
19501 The definitions provided by the use of
19503 @smallexample @c ada
19504 pragma Extend_System (AUX_Dec);
19505 @end smallexample
19507 @noindent
19508 are virtually identical to those provided by the DEC Ada 83 package
19509 System. One important difference is that the name of the TO_ADDRESS
19510 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
19511 See the GNAT Reference manual for a discussion of why this change was
19512 necessary.
19514 @noindent
19515 The version of TO_ADDRESS taking a universal integer argument is in fact
19516 an extension to Ada 83 not strictly compatible with the reference manual.
19517 In GNAT, we are constrained to be exactly compatible with the standard,
19518 and this means we cannot provide this capability. In DEC Ada 83, the
19519 point of this definition is to deal with a call like:
19521 @smallexample @c ada
19522 TO_ADDRESS (16#12777#);
19523 @end smallexample
19525 @noindent
19526 Normally, according to the Ada 83 standard, one would expect this to be
19527 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
19528 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
19529 definition using universal_integer takes precedence.
19531 In GNAT, since the version with universal_integer cannot be supplied, it is
19532 not possible to be 100% compatible. Since there are many programs using
19533 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
19534 to change the name of the function in the UNSIGNED_LONGWORD case, so the
19535 declarations provided in the GNAT version of AUX_Dec are:
19537 @smallexample @c ada
19538 function To_Address (X : Integer) return Address;
19539 pragma Pure_Function (To_Address);
19541 function To_Address_Long (X : Unsigned_Longword) return Address;
19542 pragma Pure_Function (To_Address_Long);
19543 @end smallexample
19545 @noindent
19546 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
19547 change the name to TO_ADDRESS_LONG.
19549 @node Tasking and Task-Related Features
19550 @section Tasking and Task-Related Features
19552 @noindent
19553 The concepts relevant to a comparison of tasking on GNAT
19554 and on DEC Ada for OpenVMS Alpha systems are discussed in
19555 the following sections.
19557 For detailed information on concepts related to tasking in
19558 DEC Ada, see the DEC Ada Language Reference Manual and the
19559 relevant run-time reference manual.
19561 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19562 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19564 @noindent
19565 On OpenVMS Alpha systems, each Ada task (except a passive
19566 task) is implemented as a single stream of execution
19567 that is created and managed by the kernel. On these
19568 systems, DEC Ada tasking support is based on DECthreads,
19569 an implementation of the POSIX standard for threads.
19571 Although tasks are implemented as threads, all tasks in
19572 an Ada program are part of the same process. As a result,
19573 resources such as open files and virtual memory can be
19574 shared easily among tasks. Having all tasks in one process
19575 allows better integration with the programming environment
19576 (the shell and the debugger, for example).
19578 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
19579 code that calls DECthreads routines can be used together.
19580 The interaction between Ada tasks and DECthreads routines
19581 can have some benefits. For example when on OpenVMS Alpha,
19582 DEC Ada can call C code that is already threaded.
19583 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
19584 and Ada tasks are mapped to threads.
19586 @menu
19587 * Assigning Task IDs::
19588 * Task IDs and Delays::
19589 * Task-Related Pragmas::
19590 * Scheduling and Task Priority::
19591 * The Task Stack::
19592 * External Interrupts::
19593 @end menu
19595 @node Assigning Task IDs
19596 @subsection Assigning Task IDs
19598 @noindent
19599 The DEC Ada Run-Time Library always assigns %TASK 1 to
19600 the environment task that executes the main program. On
19601 OpenVMS Alpha systems, %TASK 0 is often used for tasks
19602 that have been created but are not yet activated.
19604 On OpenVMS Alpha systems, task IDs are assigned at
19605 activation. On GNAT systems, task IDs are also assigned at
19606 task creation but do not have the same form or values as
19607 task ID values in DEC Ada. There is no null task, and the
19608 environment task does not have a specific task ID value.
19610 @node Task IDs and Delays
19611 @subsection Task IDs and Delays
19613 @noindent
19614 On OpenVMS Alpha systems, tasking delays are implemented
19615 using Timer System Services. The Task ID is used for the
19616 identification of the timer request (the REQIDT parameter).
19617 If Timers are used in the application take care not to use
19618 0 for the identification, because cancelling such a timer
19619 will cancel all timers and may lead to unpredictable results.
19621 @node Task-Related Pragmas
19622 @subsection Task-Related Pragmas
19624 @noindent
19625 Ada supplies the pragma TASK_STORAGE, which allows
19626 specification of the size of the guard area for a task
19627 stack. (The guard area forms an area of memory that has no
19628 read or write access and thus helps in the detection of
19629 stack overflow.) On OpenVMS Alpha systems, if the pragma
19630 TASK_STORAGE specifies a value of zero, a minimal guard
19631 area is created. In the absence of a pragma TASK_STORAGE, a default guard
19632 area is created.
19634 GNAT supplies the following task-related pragmas:
19636 @itemize @bullet
19637 @item  TASK_INFO
19639               This pragma appears within a task definition and
19640               applies to the task in which it appears. The argument
19641               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
19643 @item  TASK_STORAGE
19645               GNAT implements pragma TASK_STORAGE in the same way as
19646               DEC Ada.
19647               Both DEC Ada and GNAT supply the pragmas PASSIVE,
19648               SUPPRESS, and VOLATILE.
19649 @end itemize
19650 @node Scheduling and Task Priority
19651 @subsection Scheduling and Task Priority
19653 @noindent
19654 DEC Ada implements the Ada language requirement that
19655 when two tasks are eligible for execution and they have
19656 different priorities, the lower priority task does not
19657 execute while the higher priority task is waiting. The DEC
19658 Ada Run-Time Library keeps a task running until either the
19659 task is suspended or a higher priority task becomes ready.
19661 On OpenVMS Alpha systems, the default strategy is round-
19662 robin with preemption. Tasks of equal priority take turns
19663 at the processor. A task is run for a certain period of
19664 time and then placed at the rear of the ready queue for
19665 its priority level.
19667 DEC Ada provides the implementation-defined pragma TIME_SLICE,
19668 which can be used to enable or disable round-robin
19669 scheduling of tasks with the same priority.
19670 See the relevant DEC Ada run-time reference manual for
19671 information on using the pragmas to control DEC Ada task
19672 scheduling.
19674 GNAT follows the scheduling rules of Annex D (real-time
19675 Annex) of the Ada 95 Reference Manual. In general, this
19676 scheduling strategy is fully compatible with DEC Ada
19677 although it provides some additional constraints (as
19678 fully documented in Annex D).
19679 GNAT implements time slicing control in a manner compatible with
19680 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
19681 to the DEC Ada 83 pragma of the same name.
19682 Note that it is not possible to mix GNAT tasking and
19683 DEC Ada 83 tasking in the same program, since the two run times are
19684 not compatible.
19686 @node The Task Stack
19687 @subsection The Task Stack
19689 @noindent
19690 In DEC Ada, a task stack is allocated each time a
19691 non passive task is activated. As soon as the task is
19692 terminated, the storage for the task stack is deallocated.
19693 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
19694 a default stack size is used. Also, regardless of the size
19695 specified, some additional space is allocated for task
19696 management purposes. On OpenVMS Alpha systems, at least
19697 one page is allocated.
19699 GNAT handles task stacks in a similar manner. According to
19700 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
19701 an alternative method for controlling the task stack size.
19702 The specification of the attribute T'STORAGE_SIZE is also
19703 supported in a manner compatible with DEC Ada.
19705 @node External Interrupts
19706 @subsection External Interrupts
19708 @noindent
19709 On DEC Ada, external interrupts can be associated with task entries.
19710 GNAT is compatible with DEC Ada in its handling of external interrupts.
19712 @node Pragmas and Pragma-Related Features
19713 @section Pragmas and Pragma-Related Features
19715 @noindent
19716 Both DEC Ada and GNAT supply all language-defined pragmas
19717 as specified by the Ada 83 standard. GNAT also supplies all
19718 language-defined pragmas specified in the Ada 95 Reference Manual.
19719 In addition, GNAT implements the implementation-defined pragmas
19720 from DEC Ada 83.
19722 @itemize @bullet
19723 @item  AST_ENTRY
19725 @item  COMMON_OBJECT
19727 @item  COMPONENT_ALIGNMENT
19729 @item  EXPORT_EXCEPTION
19731 @item  EXPORT_FUNCTION
19733 @item  EXPORT_OBJECT
19735 @item  EXPORT_PROCEDURE
19737 @item  EXPORT_VALUED_PROCEDURE
19739 @item  FLOAT_REPRESENTATION
19741 @item  IDENT
19743 @item  IMPORT_EXCEPTION
19745 @item  IMPORT_FUNCTION
19747 @item  IMPORT_OBJECT
19749 @item  IMPORT_PROCEDURE
19751 @item  IMPORT_VALUED_PROCEDURE
19753 @item  INLINE_GENERIC
19755 @item  INTERFACE_NAME
19757 @item  LONG_FLOAT
19759 @item  MAIN_STORAGE
19761 @item  PASSIVE
19763 @item  PSET_OBJECT
19765 @item  SHARE_GENERIC
19767 @item  SUPPRESS_ALL
19769 @item  TASK_STORAGE
19771 @item  TIME_SLICE
19773 @item  TITLE
19774 @end itemize
19776 @noindent
19777 These pragmas are all fully implemented, with the exception of @code{Title},
19778 @code{Passive}, and @code{Share_Generic}, which are
19779 recognized, but which have no
19780 effect in GNAT. The effect of @code{Passive} may be obtained by the
19781 use of protected objects in Ada 95. In GNAT, all generics are inlined.
19783 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
19784 a separate subprogram specification which must appear before the
19785 subprogram body.
19787 GNAT also supplies a number of implementation-defined pragmas as follows:
19788 @itemize @bullet
19789 @item  C_PASS_BY_COPY
19791 @item  EXTEND_SYSTEM
19793 @item  SOURCE_FILE_NAME
19795 @item  UNSUPPRESS
19797 @item  WARNINGS
19799 @item  ABORT_DEFER
19801 @item  ADA_83
19803 @item  ADA_95
19805 @item  ANNOTATE
19807 @item  ASSERT
19809 @item  CPP_CLASS
19811 @item  CPP_CONSTRUCTOR
19813 @item  CPP_DESTRUCTOR
19815 @item  CPP_VIRTUAL
19817 @item  CP_VTABLE
19819 @item  DEBUG
19821 @item  LINKER_ALIAS
19823 @item  LINKER_SECTION
19825 @item  MACHINE_ATTRIBUTE
19827 @item  NO_RETURN
19829 @item  PURE_FUNCTION
19831 @item  SOURCE_REFERENCE
19833 @item  TASK_INFO
19835 @item  UNCHECKED_UNION
19837 @item  UNIMPLEMENTED_UNIT
19839 @item  UNIVERSAL_DATA
19841 @item  WEAK_EXTERNAL
19842 @end itemize
19844 @noindent
19845 For full details on these GNAT implementation-defined pragmas, see
19846 the GNAT Reference Manual.
19848 @menu
19849 * Restrictions on the Pragma INLINE::
19850 * Restrictions on the Pragma INTERFACE::
19851 * Restrictions on the Pragma SYSTEM_NAME::
19852 @end menu
19854 @node Restrictions on the Pragma INLINE
19855 @subsection Restrictions on the Pragma INLINE
19857 @noindent
19858 DEC Ada applies the following restrictions to the pragma INLINE:
19859 @itemize @bullet
19860 @item  Parameters cannot be a task type.
19862 @item  Function results cannot be task types, unconstrained
19863 array types, or unconstrained types with discriminants.
19865 @item  Bodies cannot declare the following:
19866 @itemize @bullet
19867 @item  Subprogram body or stub (imported subprogram is allowed)
19869 @item  Tasks
19871 @item  Generic declarations
19873 @item  Instantiations
19875 @item  Exceptions
19877 @item  Access types (types derived from access types allowed)
19879 @item  Array or record types
19881 @item  Dependent tasks
19883 @item  Direct recursive calls of subprogram or containing
19884 subprogram, directly or via a renaming
19886 @end itemize
19887 @end itemize
19889 @noindent
19890 In GNAT, the only restriction on pragma INLINE is that the
19891 body must occur before the call if both are in the same
19892 unit, and the size must be appropriately small. There are
19893 no other specific restrictions which cause subprograms to
19894 be incapable of being inlined.
19896 @node  Restrictions on the Pragma INTERFACE
19897 @subsection  Restrictions on the Pragma INTERFACE
19899 @noindent
19900 The following lists and describes the restrictions on the
19901 pragma INTERFACE on DEC Ada and GNAT:
19902 @itemize @bullet
19903 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
19904 Default is the default on OpenVMS Alpha systems.
19906 @item  Parameter passing: Language specifies default
19907 mechanisms but can be overridden with an EXPORT pragma.
19909 @itemize @bullet
19910 @item  Ada: Use internal Ada rules.
19912 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
19913 record or task type. Result cannot be a string, an
19914 array, or a record.
19916 @item  Fortran: Parameters cannot be a task. Result cannot
19917 be a string, an array, or a record.
19918 @end itemize
19919 @end itemize
19921 @noindent
19922 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
19923 record parameters for all languages.
19925 @node  Restrictions on the Pragma SYSTEM_NAME
19926 @subsection  Restrictions on the Pragma SYSTEM_NAME
19928 @noindent
19929 For DEC Ada for OpenVMS Alpha, the enumeration literal
19930 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
19931 literal for the type NAME is SYSTEM_NAME_GNAT.
19933 @node  Library of Predefined Units
19934 @section  Library of Predefined Units
19936 @noindent
19937 A library of predefined units is provided as part of the
19938 DEC Ada and GNAT implementations. DEC Ada does not provide
19939 the package MACHINE_CODE but instead recommends importing
19940 assembler code.
19942 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
19943 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
19944 version. During GNAT installation, the DEC Ada Predefined
19945 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
19946 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
19947 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
19948 for details.
19950 The GNAT RTL is contained in
19951 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
19952 the default search path is set up to find DECLIB units in preference
19953 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
19954 for example).
19956 However, it is possible to change the default so that the
19957 reverse is true, or even to mix them using child package
19958 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
19959 is the package name, and the Ada units are available in the
19960 standard manner defined for Ada 95, that is to say as Ada.xxx. To
19961 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
19962 appropriately. For example, to change the default to use the Ada95
19963 versions do:
19965 @smallexample
19966 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
19967                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
19968 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
19969                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
19970 @end smallexample
19972 @menu
19973 * Changes to DECLIB::
19974 @end menu
19976 @node Changes to DECLIB
19977 @subsection Changes to DECLIB
19979 @noindent
19980 The changes made to the DEC Ada predefined library for GNAT and Ada 95
19981 compatibility are minor and include the following:
19983 @itemize @bullet
19984 @item  Adjusting the location of pragmas and record representation
19985 clauses to obey Ada 95 rules
19987 @item  Adding the proper notation to generic formal parameters
19988 that take unconstrained types in instantiation
19990 @item  Adding pragma ELABORATE_BODY to package specifications
19991 that have package bodies not otherwise allowed
19993 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
19994 @code{"PROTECTD"}.
19995 Currently these are found only in the STARLET package spec.
19996 @end itemize
19998 @noindent
19999 None of the above changes is visible to users.
20001 @node Bindings
20002 @section Bindings
20004 @noindent
20005 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
20006 @itemize @bullet
20008 @item  Command Language Interpreter (CLI interface)
20010 @item  DECtalk Run-Time Library (DTK interface)
20012 @item  Librarian utility routines (LBR interface)
20014 @item  General Purpose Run-Time Library (LIB interface)
20016 @item  Math Run-Time Library (MTH interface)
20018 @item  National Character Set Run-Time Library (NCS interface)
20020 @item  Compiled Code Support Run-Time Library (OTS interface)
20022 @item  Parallel Processing Run-Time Library (PPL interface)
20024 @item  Screen Management Run-Time Library (SMG interface)
20026 @item  Sort Run-Time Library (SOR interface)
20028 @item  String Run-Time Library (STR interface)
20030 @item STARLET System Library
20031 @findex Starlet
20033 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20035 @item  X Windows Toolkit (XT interface)
20037 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20038 @end itemize
20040 @noindent
20041 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20043 The X/Motif bindings used to build DECLIB are whatever versions are in the
20044 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20045 The build script will
20046 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20047 and @code{X_Lib}
20048 causing the default X/Motif sharable image libraries to be linked in. This
20049 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20050 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20052 It may be necessary to edit these options files to update or correct the
20053 library names if, for example, the newer X/Motif bindings from
20054 @file{ADA$EXAMPLES}
20055 had been (previous to installing GNAT) copied and renamed to supersede the
20056 default @file{ADA$PREDEFINED} versions.
20058 @menu
20059 * Shared Libraries and Options Files::
20060 * Interfaces to C::
20061 @end menu
20063 @node Shared Libraries and Options Files
20064 @subsection Shared Libraries and Options Files
20066 @noindent
20067 When using the DEC Ada
20068 predefined X and Motif bindings, the linking with their sharable images is
20069 done automatically by @command{GNAT LINK}.
20070 When using other X and Motif bindings, you need
20071 to add the corresponding sharable images to the command line for
20072 @code{GNAT LINK}. When linking with shared libraries, or with
20073 @file{.OPT} files, you must
20074 also add them to the command line for @command{GNAT LINK}.
20076 A shared library to be used with GNAT is built in the same way as other
20077 libraries under VMS. The VMS Link command can be used in standard fashion.
20079 @node Interfaces to C
20080 @subsection Interfaces to C
20082 @noindent
20083 DEC Ada
20084 provides the following Ada types and operations:
20086 @itemize @bullet
20087 @item C types package (C_TYPES)
20089 @item C strings (C_TYPES.NULL_TERMINATED)
20091 @item Other_types (SHORT_INT)
20092 @end itemize
20094 @noindent
20095 Interfacing to C with GNAT, one can use the above approach
20096 described for DEC Ada or the facilities of Annex B of
20097 the Ada 95 Reference Manual (packages INTERFACES.C,
20098 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
20099 information, see the section ``Interfacing to C'' in the
20100 @cite{GNAT Reference Manual}.
20102 The @option{-gnatF} qualifier forces default and explicit
20103 @code{External_Name} parameters in pragmas Import and Export
20104 to be uppercased for compatibility with the default behavior
20105 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
20107 @node Main Program Definition
20108 @section Main Program Definition
20110 @noindent
20111 The following section discusses differences in the
20112 definition of main programs on DEC Ada and GNAT.
20113 On DEC Ada, main programs are defined to meet the
20114 following conditions:
20115 @itemize @bullet
20116 @item  Procedure with no formal parameters (returns 0 upon
20117        normal completion)
20119 @item  Procedure with no formal parameters (returns 42 when
20120        unhandled exceptions are raised)
20122 @item  Function with no formal parameters whose returned value
20123        is of a discrete type
20125 @item  Procedure with one OUT formal of a discrete type for
20126        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
20128 @end itemize
20130 @noindent
20131 When declared with the pragma EXPORT_VALUED_PROCEDURE,
20132 a main function or main procedure returns a discrete
20133 value whose size is less than 64 bits (32 on VAX systems),
20134 the value is zero- or sign-extended as appropriate.
20135 On GNAT, main programs are defined as follows:
20136 @itemize @bullet
20137 @item  Must be a non-generic, parameter-less subprogram that
20138 is either a procedure or function returning an Ada
20139 STANDARD.INTEGER (the predefined type)
20141 @item  Cannot be a generic subprogram or an instantiation of a
20142 generic subprogram
20143 @end itemize
20145 @node Implementation-Defined Attributes
20146 @section Implementation-Defined Attributes
20148 @noindent
20149 GNAT provides all DEC Ada implementation-defined
20150 attributes.
20152 @node Compiler and Run-Time Interfacing
20153 @section Compiler and Run-Time Interfacing
20155 @noindent
20156 DEC Ada provides the following ways to pass options to the linker
20157 (ACS LINK):
20158 @itemize @bullet
20159 @item  /WAIT and /SUBMIT qualifiers
20161 @item  /COMMAND qualifier
20163 @item  /[NO]MAP qualifier
20165 @item  /OUTPUT=file-spec
20167 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
20168 @end itemize
20170 @noindent
20171 To pass options to the linker, GNAT provides the following
20172 switches:
20174 @itemize @bullet
20175 @item   @option{/EXECUTABLE=exec-name}
20177 @item   @option{/VERBOSE qualifier}
20179 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
20180 @end itemize
20182 @noindent
20183 For more information on these switches, see
20184 @ref{Switches for gnatlink}.
20185 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
20186 to control optimization. DEC Ada also supplies the
20187 following pragmas:
20188 @itemize @bullet
20189 @item  @code{OPTIMIZE}
20191 @item  @code{INLINE}
20193 @item  @code{INLINE_GENERIC}
20195 @item  @code{SUPPRESS_ALL}
20197 @item  @code{PASSIVE}
20198 @end itemize
20200 @noindent
20201 In GNAT, optimization is controlled strictly by command
20202 line parameters, as described in the corresponding section of this guide.
20203 The DIGITAL pragmas for control of optimization are
20204 recognized but ignored.
20206 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
20207 the default is that optimization is turned on.
20209 @node Program Compilation and Library Management
20210 @section Program Compilation and Library Management
20212 @noindent
20213 DEC Ada and GNAT provide a comparable set of commands to
20214 build programs. DEC Ada also provides a program library,
20215 which is a concept that does not exist on GNAT. Instead,
20216 GNAT provides directories of sources that are compiled as
20217 needed.
20219 The following table summarizes
20220 the DEC Ada commands and provides
20221 equivalent GNAT commands. In this table, some GNAT
20222 equivalents reflect the fact that GNAT does not use the
20223 concept of a program library. Instead, it uses a model
20224 in which collections of source and object files are used
20225 in a manner consistent with other languages like C and
20226 Fortran. Therefore, standard system file commands are used
20227 to manipulate these elements. Those GNAT commands are marked with
20228 an asterisk.
20229 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
20231 @need 1500
20232 @multitable @columnfractions .35 .65
20234 @item @emph{DEC Ada Command}
20235 @tab @emph{GNAT Equivalent / Description}
20237 @item @command{ADA}
20238 @tab @command{GNAT COMPILE}@*
20239 Invokes the compiler to compile one or more Ada source files.
20241 @item @command{ACS ATTACH}@*
20242 @tab [No equivalent]@*
20243 Switches control of terminal from current process running the program
20244 library manager.
20246 @item @command{ACS CHECK}
20247 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20248 Forms the execution closure of one
20249 or more compiled units and checks completeness and currency.
20251 @item @command{ACS COMPILE}
20252 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20253 Forms the execution closure of one or
20254 more specified units, checks completeness and currency,
20255 identifies units that have revised source files, compiles same,
20256 and recompiles units that are or will become obsolete.
20257 Also completes incomplete generic instantiations.
20259 @item @command{ACS COPY FOREIGN}
20260 @tab Copy (*)@*
20261 Copies a foreign object file into the program library as a
20262 library unit body.
20264 @item @command{ACS COPY UNIT}
20265 @tab Copy (*)@*
20266 Copies a compiled unit from one program library to another.
20268 @item @command{ACS CREATE LIBRARY}
20269 @tab Create /directory (*)@*
20270 Creates a program library.
20272 @item @command{ACS CREATE SUBLIBRARY}
20273 @tab Create /directory (*)@*
20274 Creates a program sublibrary.
20276 @item @command{ACS DELETE LIBRARY}
20277 @tab @*
20278 Deletes a program library and its contents.
20280 @item @command{ACS DELETE SUBLIBRARY}
20281 @tab @*
20282 Deletes a program sublibrary and its contents.
20284 @item @command{ACS DELETE UNIT}
20285 @tab Delete file (*)@*
20286 On OpenVMS systems, deletes one or more compiled units from
20287 the current program library.
20289 @item @command{ACS DIRECTORY}
20290 @tab Directory (*)@*
20291 On OpenVMS systems, lists units contained in the current
20292 program library.
20294 @item @command{ACS ENTER FOREIGN}
20295 @tab Copy (*)@*
20296 Allows the import of a foreign body as an Ada library
20297 specification and enters a reference to a pointer.
20299 @item @command{ACS ENTER UNIT}
20300 @tab Copy (*)@*
20301 Enters a reference (pointer) from the current program library to
20302 a unit compiled into another program library.
20304 @item @command{ACS EXIT}
20305 @tab [No equivalent]@*
20306 Exits from the program library manager.
20308 @item @command{ACS EXPORT}
20309 @tab Copy (*)@*
20310 Creates an object file that contains system-specific object code
20311 for one or more units. With GNAT, object files can simply be copied
20312 into the desired directory.
20314 @item @command{ACS EXTRACT SOURCE}
20315 @tab Copy (*)@*
20316 Allows access to the copied source file for each Ada compilation unit
20318 @item @command{ACS HELP}
20319 @tab @command{HELP GNAT}@*
20320 Provides online help.
20322 @item @command{ACS LINK}
20323 @tab @command{GNAT LINK}@*
20324 Links an object file containing Ada units into an executable file.
20326 @item @command{ACS LOAD}
20327 @tab Copy (*)@*
20328 Loads (partially compiles) Ada units into the program library.
20329 Allows loading a program from a collection of files into a library
20330 without knowing the relationship among units.
20332 @item @command{ACS MERGE}
20333 @tab Copy (*)@*
20334 Merges into the current program library, one or more units from
20335 another library where they were modified.
20337 @item @command{ACS RECOMPILE}
20338 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20339 Recompiles from   external or copied source files any obsolete
20340 unit in the closure. Also, completes any incomplete generic
20341 instantiations.
20343 @item @command{ACS REENTER}
20344 @tab @command{GNAT MAKE}@*
20345 Reenters current references to units compiled after last entered
20346 with the @command{ACS ENTER UNIT} command.
20348 @item @command{ACS SET LIBRARY}
20349 @tab Set default (*)@*
20350 Defines a program library to be the compilation context as well
20351 as the target library for compiler output and commands in general.
20353 @item @command{ACS SET PRAGMA}
20354 @tab Edit @file{gnat.adc} (*)@*
20355 Redefines specified  values of the library characteristics
20356 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20357 and @code{Float_Representation}.
20359 @item @command{ACS SET SOURCE}
20360 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20361 Defines the source file search list for the @command{ACS COMPILE} command.
20363 @item @command{ACS SHOW LIBRARY}
20364 @tab Directory (*)@*
20365 Lists information about one or more program libraries.
20367 @item @command{ACS SHOW PROGRAM}
20368 @tab [No equivalent]@*
20369 Lists information about the execution closure of one or
20370 more units in the program library.
20372 @item @command{ACS SHOW SOURCE}
20373 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20374 Shows the source file search used when compiling units.
20376 @item @command{ACS SHOW VERSION}
20377 @tab Compile with @option{VERBOSE} option
20378 Displays the version number of the compiler and program library
20379 manager used.
20381 @item @command{ACS SPAWN}
20382 @tab [No equivalent]@*
20383 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20384 command).
20386 @item @command{ACS VERIFY}
20387 @tab [No equivalent]@*
20388 Performs a series of consistency checks on a program library to
20389 determine whether the library structure and library files are in
20390 valid form.
20391 @end multitable
20393 @noindent
20395 @node Input-Output
20396 @section Input-Output
20398 @noindent
20399 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
20400 Management Services (RMS) to perform operations on
20401 external files.
20403 @noindent
20404 DEC Ada and GNAT predefine an identical set of input-
20405 output packages. To make the use of the
20406 generic TEXT_IO operations more convenient, DEC Ada
20407 provides predefined library packages that instantiate the
20408 integer and floating-point operations for the predefined
20409 integer and floating-point types as shown in the following table.
20411 @multitable @columnfractions .45 .55
20412 @item @emph{Package Name} @tab Instantiation
20414 @item @code{INTEGER_TEXT_IO}
20415 @tab @code{INTEGER_IO(INTEGER)}
20417 @item @code{SHORT_INTEGER_TEXT_IO}
20418 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20420 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20421 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20423 @item @code{FLOAT_TEXT_IO}
20424 @tab @code{FLOAT_IO(FLOAT)}
20426 @item @code{LONG_FLOAT_TEXT_IO}
20427 @tab @code{FLOAT_IO(LONG_FLOAT)}
20428 @end multitable
20430 @noindent
20431 The DEC Ada predefined packages and their operations
20432 are implemented using OpenVMS Alpha files and input-
20433 output facilities. DEC Ada supports asynchronous input-
20434 output on OpenVMS Alpha. Familiarity with the following is
20435 recommended:
20436 @itemize @bullet
20437 @item  RMS file organizations and access methods
20439 @item  OpenVMS file specifications and directories
20441 @item  OpenVMS File Definition Language (FDL)
20442 @end itemize
20444 @noindent
20445 GNAT provides I/O facilities that are completely
20446 compatible with DEC Ada. The distribution includes the
20447 standard DEC Ada versions of all I/O packages, operating
20448 in a manner compatible with DEC Ada. In particular, the
20449 following packages are by default the DEC Ada (Ada 83)
20450 versions of these packages rather than the renamings
20451 suggested in annex J of the Ada 95 Reference Manual:
20452 @itemize @bullet
20453 @item  @code{TEXT_IO}
20455 @item  @code{SEQUENTIAL_IO}
20457 @item  @code{DIRECT_IO}
20458 @end itemize
20460 @noindent
20461 The use of the standard Ada 95 syntax for child packages (for
20462 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
20463 packages, as defined in the Ada 95 Reference Manual.
20464 GNAT provides DIGITAL-compatible predefined instantiations
20465 of the @code{TEXT_IO} packages, and also
20466 provides the standard predefined instantiations required
20467 by the Ada 95 Reference Manual.
20469 For further information on how GNAT interfaces to the file
20470 system or how I/O is implemented in programs written in
20471 mixed languages, see the chapter ``Implementation of the
20472 Standard I/O'' in the @cite{GNAT Reference Manual}.
20473 This chapter covers the following:
20474 @itemize @bullet
20475 @item  Standard I/O packages
20477 @item  @code{FORM} strings
20479 @item  @code{ADA.DIRECT_IO}
20481 @item  @code{ADA.SEQUENTIAL_IO}
20483 @item  @code{ADA.TEXT_IO}
20485 @item  Stream pointer positioning
20487 @item  Reading and writing non-regular files
20489 @item  @code{GET_IMMEDIATE}
20491 @item  Treating @code{TEXT_IO} files as streams
20493 @item  Shared files
20495 @item  Open modes
20496 @end itemize
20498 @node Implementation Limits
20499 @section Implementation Limits
20501 @noindent
20502 The following table lists implementation limits for DEC Ada
20503 and GNAT systems.
20504 @multitable @columnfractions .60 .20 .20
20505 @sp 1
20506 @item  @emph{Compilation Parameter}
20507 @tab   @emph{DEC Ada}
20508 @tab   @emph{GNAT}
20509 @sp 1
20511 @item  In a subprogram or entry  declaration, maximum number of
20512        formal parameters that are of an unconstrained record type
20513 @tab   32
20514 @tab   No set limit
20515 @sp 1
20517 @item  Maximum identifier length (number of characters)
20518 @tab   255
20519 @tab   255
20520 @sp 1
20522 @item  Maximum number of characters in a source line
20523 @tab   255
20524 @tab   255
20525 @sp 1
20527 @item  Maximum collection size   (number of bytes)
20528 @tab   2**31-1
20529 @tab   2**31-1
20530 @sp 1
20532 @item  Maximum number of discriminants for a record type
20533 @tab   245
20534 @tab   No set limit
20535 @sp 1
20537 @item  Maximum number of formal parameters in an entry or
20538        subprogram declaration
20539 @tab   246
20540 @tab    No set limit
20541 @sp 1
20543 @item  Maximum number of dimensions in an array type
20544 @tab   255
20545 @tab   No set limit
20546 @sp 1
20548 @item  Maximum number of library  units and subunits in a compilation.
20549 @tab   4095
20550 @tab   No set limit
20551 @sp 1
20553 @item  Maximum number of library units and subunits in an execution.
20554 @tab   16383
20555 @tab   No set limit
20556 @sp 1
20558 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20559        or @code{PSECT_OBJECT}
20560 @tab   32757
20561 @tab   No set limit
20562 @sp 1
20564 @item  Maximum number of enumeration literals in an enumeration type
20565        definition
20566 @tab   65535
20567 @tab   No set limit
20568 @sp 1
20570 @item  Maximum number of lines in a source file
20571 @tab   65534
20572 @tab   No set limit
20573 @sp 1
20575 @item  Maximum number of bits in any object
20576 @tab   2**31-1
20577 @tab   2**31-1
20578 @sp 1
20580 @item  Maximum size of the static portion of a stack frame (approximate)
20581 @tab   2**31-1
20582 @tab   2**31-1
20583 @end multitable
20585 @node  Tools
20586 @section Tools
20588 @end ifset
20591 @c **************************************
20592 @node Platform-Specific Information for the Run-Time Libraries
20593 @appendix Platform-Specific Information for the Run-Time Libraries
20594 @cindex Tasking and threads libraries
20595 @cindex Threads libraries and tasking
20596 @cindex Run-time libraries (platform-specific information)
20598 @noindent
20599 The GNAT run-time implementation
20600 may vary with respect to both the underlying threads library and
20601 the exception handling scheme.
20602 For threads support, one or more of the following are supplied:
20603 @itemize @bullet
20604 @item @b{native threads library}, a binding to the thread package from
20605 the underlying operating system
20607 @item @b{FSU threads library}, a binding to the Florida State University
20608 threads implementation, which complies fully with the requirements of Annex D
20610 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
20611 POSIX thread package
20612 @end itemize
20614 @noindent
20615 For exception handling, either or both of two models are supplied:
20616 @itemize @bullet
20617 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
20618 Most programs should experience a substantial speed improvement by
20619 being compiled with a ZCX run-time.
20620 This is especially true for
20621 tasking applications or applications with many exception handlers.}
20622 @cindex Zero-Cost Exceptions
20623 @cindex ZCX (Zero-Cost Exceptions)
20624 which uses binder-generated tables that
20625 are interrogated at run time to locate a handler
20627 @item @b{setjmp / longjmp} (``SJLJ''),
20628 @cindex setjmp/longjmp Exception Model
20629 @cindex SJLJ (setjmp/longjmp Exception Model)
20630 which uses dynamically-set data to establish
20631 the set of handlers
20632 @end itemize
20634 @noindent
20635 This appendix summarizes which combinations of threads and exception support
20636 are supplied on various GNAT platforms.
20637 It then shows how to select a particular library either
20638 permanently or temporarily,
20639 explains the properties of (and tradeoffs among) the various threads
20640 libraries, and provides some additional
20641 information about several specific platforms.
20643 @menu
20644 * Summary of Run-Time Configurations::
20645 * Specifying a Run-Time Library::
20646 * Choosing between Native and FSU Threads Libraries::
20647 * Choosing the Scheduling Policy::
20648 * Solaris-Specific Considerations::
20649 * IRIX-Specific Considerations::
20650 * Linux-Specific Considerations::
20651 @end menu
20654 @node Summary of Run-Time Configurations
20655 @section Summary of Run-Time Configurations
20658 @multitable @columnfractions .30 .70
20659 @item @b{alpha-openvms}
20660 @item @code{@ @ }@i{rts-native (default)}
20661 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
20662 @item @code{@ @ @ @ }Exceptions @tab ZCX
20664 @item @b{pa-hpux}
20665 @item @code{@ @ }@i{rts-native (default)}
20666 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20667 @item @code{@ @ @ @ }Exceptions @tab ZCX
20669 @item @code{@ @ }@i{rts-sjlj}
20670 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20671 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20673 @item @b{sparc-solaris}  @tab
20674 @item @code{@ @ }@i{rts-native (default)}
20675 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20676 @item @code{@ @ @ @ }Exceptions @tab ZCX
20678 @item @code{@ @ }@i{rts-fsu}    @tab
20679 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20680 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20682 @item @code{@ @ }@i{rts-m64}
20683 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
20684 @item @code{@ @ @ @ }Exceptions  @tab ZCX
20685 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
20686 @item    @tab Use only on Solaris 8 or later.
20687 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
20689 @item @code{@ @ }@i{rts-pthread}
20690 @item @code{@ @ @ @ }Tasking    @tab pthreads library
20691 @item @code{@ @ @ @ }Exceptions @tab ZCX
20693 @item @code{@ @ }@i{rts-sjlj}
20694 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20695 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20697 @item @b{x86-linux}
20698 @item @code{@ @ }@i{rts-native (default)}
20699 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20700 @item @code{@ @ @ @ }Exceptions @tab ZCX
20702 @item @code{@ @ }@i{rts-fsu}
20703 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20704 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20706 @item @code{@ @ }@i{rts-sjlj}
20707 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20708 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20710 @item @b{x86-windows}
20711 @item @code{@ @ }@i{rts-native (default)}
20712 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
20713 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20715 @end multitable
20719 @node Specifying a Run-Time Library
20720 @section Specifying a Run-Time Library
20722 @noindent
20723 The @file{adainclude} subdirectory containing the sources of the GNAT
20724 run-time library, and the @file{adalib} subdirectory containing the
20725 @file{ALI} files and the static and/or shared GNAT library, are located
20726 in the gcc target-dependent area:
20728 @smallexample
20729 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
20730 @end smallexample
20732 @noindent
20733 As indicated above, on some platforms several run-time libraries are supplied.
20734 These libraries are installed in the target dependent area and
20735 contain a complete source and binary subdirectory. The detailed description
20736 below explains the differences between the different libraries in terms of
20737 their thread support.
20739 The default run-time library (when GNAT is installed) is @emph{rts-native}.
20740 This default run time is selected by the means of soft links.
20741 For example on x86-linux:
20743 @smallexample
20744 @group
20745  $(target-dir)
20746      |
20747      +--- adainclude----------+
20748      |                        |
20749      +--- adalib-----------+  |
20750      |                     |  |
20751      +--- rts-native       |  |
20752      |    |                |  |
20753      |    +--- adainclude <---+
20754      |    |                |
20755      |    +--- adalib <----+
20756      |
20757      +--- rts-fsu
20758      |    |
20759      |    +--- adainclude
20760      |    |
20761      |    +--- adalib
20762      |
20763      +--- rts-sjlj
20764           |
20765           +--- adainclude
20766           |
20767           +--- adalib
20768 @end group
20769 @end smallexample
20771 @noindent
20772 If the @i{rts-fsu} library is to be selected on a permanent basis,
20773 these soft links can be modified with the following commands:
20775 @smallexample
20776 $ cd $target
20777 $ rm -f adainclude adalib
20778 $ ln -s rts-fsu/adainclude adainclude
20779 $ ln -s rts-fsu/adalib adalib
20780 @end smallexample
20782 @noindent
20783 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
20784 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
20785 @file{$target/ada_object_path}.
20787 Selecting another run-time library temporarily can be
20788 achieved by the regular mechanism for GNAT object or source path selection:
20790 @itemize @bullet
20791 @item
20792 Set the environment variables:
20794 @smallexample
20795 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
20796 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
20797 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
20798 @end smallexample
20800 @item
20801 Use @option{-aI$target/rts-fsu/adainclude}
20802 and @option{-aO$target/rts-fsu/adalib}
20803 on the @command{gnatmake} command line
20805 @item
20806 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
20807 @cindex @option{--RTS} option
20808 @end itemize
20810 @noindent
20811 You can similarly switch to @emph{rts-sjlj}.
20813 @node Choosing between Native and FSU Threads Libraries
20814 @section Choosing between Native and FSU Threads Libraries
20815 @cindex Native threads library
20816 @cindex FSU threads library
20818 @noindent
20819 Some GNAT implementations offer a choice between
20820 native threads and FSU threads.
20822 @itemize @bullet
20823 @item
20824 The @emph{native threads} library correspond to the standard system threads
20825 implementation (e.g. LinuxThreads on GNU/Linux,
20826 @cindex LinuxThreads library
20827 POSIX threads on AIX, or
20828 Solaris threads on Solaris). When this option is chosen, GNAT provides
20829 a full and accurate implementation of the core language tasking model
20830 as described in Chapter 9 of the Ada Reference Manual,
20831 but might not (and probably does not) implement
20832 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
20833 @cindex Annex D (Real-Time Systems Annex) compliance
20834 @cindex Real-Time Systems Annex compliance
20835 Indeed, the reason that a choice of libraries is offered
20836 on a given target is because some of the
20837 ACATS tests for @w{Annex D} fail using the native threads library.
20838 As far as possible, this library is implemented
20839 in accordance with Ada semantics (e.g., modifying priorities as required
20840 to simulate ceiling locking),
20841 but there are often slight inaccuracies, most often in the area of
20842 absolutely respecting the priority rules on a single
20843 processor.
20844 Moreover, it is not possible in general to define the exact behavior,
20845 because the native threads implementations
20846 are not well enough documented.
20848 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
20849 @cindex POSIX scheduling policies
20850 @cindex @code{SCHED_FIFO} scheduling policy
20851 native threads will provide a behavior very close to the @w{Annex D}
20852 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
20853 on some systems (in particular GNU/Linux and Solaris), you need to have root
20854 privileges to use the @code{SCHED_FIFO} policy.
20856 @item
20857 The @emph{FSU threads} library provides a completely accurate implementation
20858 of @w{Annex D}.
20859 Thus, operating with this library, GNAT is 100% compliant with both the core
20860 and all @w{Annex D}
20861 requirements.
20862 The formal validations for implementations offering
20863 a choice of threads packages are always carried out using the FSU
20864 threads option.
20865 @end itemize
20867 @noindent
20868 From these considerations, it might seem that FSU threads are the
20869 better choice,
20870 but that is by no means always the case. The FSU threads package
20871 operates with all Ada tasks appearing to the system to be a single
20872 thread. This is often considerably more efficient than operating
20873 with separate threads, since for example, switching between tasks
20874 can be accomplished without the (in some cases considerable)
20875 overhead of a context switch between two system threads. However,
20876 it means that you may well lose concurrency at the system
20877 level. Notably, some system operations (such as I/O) may block all
20878 tasks in a program and not just the calling task. More
20879 significantly, the FSU threads approach likely means you cannot
20880 take advantage of multiple processors, since for this you need
20881 separate threads (or even separate processes) to operate on
20882 different processors.
20884 For most programs, the native threads library is
20885 usually the better choice. Use the FSU threads if absolute
20886 conformance to @w{Annex D} is important for your application, or if
20887 you find that the improved efficiency of FSU threads is significant to you.
20889 Note also that to take full advantage of Florist and Glade, it is highly
20890 recommended that you use native threads.
20893 @node Choosing the Scheduling Policy
20894 @section Choosing the Scheduling Policy
20896 @noindent
20897 When using a POSIX threads implementation, you have a choice of several
20898 scheduling policies: @code{SCHED_FIFO},
20899 @cindex @code{SCHED_FIFO} scheduling policy
20900 @code{SCHED_RR}
20901 @cindex @code{SCHED_RR} scheduling policy
20902 and @code{SCHED_OTHER}.
20903 @cindex @code{SCHED_OTHER} scheduling policy
20904 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
20905 or @code{SCHED_RR} requires special (e.g., root) privileges.
20907 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
20908 @code{SCHED_FIFO},
20909 @cindex @code{SCHED_FIFO} scheduling policy
20910 you can use one of the following:
20912 @itemize @bullet
20913 @item
20914 @code{pragma Time_Slice (0.0)}
20915 @cindex pragma Time_Slice
20916 @item
20917 the corresponding binder option @option{-T0}
20918 @cindex @option{-T0} option
20919 @item
20920 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
20921 @cindex pragma Task_Dispatching_Policy
20922 @end itemize
20924 @noindent
20925 To specify @code{SCHED_RR},
20926 @cindex @code{SCHED_RR} scheduling policy
20927 you should use @code{pragma Time_Slice} with a
20928 value greater than @code{0.0}, or else use the corresponding @option{-T}
20929 binder option.
20933 @node Solaris-Specific Considerations
20934 @section Solaris-Specific Considerations
20935 @cindex Solaris Sparc threads libraries
20937 @noindent
20938 This section addresses some topics related to the various threads libraries
20939 on Sparc Solaris and then provides some information on building and
20940 debugging 64-bit applications.
20942 @menu
20943 * Solaris Threads Issues::
20944 * Building and Debugging 64-bit Applications::
20945 @end menu
20948 @node Solaris Threads Issues
20949 @subsection Solaris Threads Issues
20951 @noindent
20952 Starting with version 3.14, GNAT under Solaris comes with a new tasking
20953 run-time library based on POSIX threads --- @emph{rts-pthread}.
20954 @cindex rts-pthread threads library
20955 This run-time library has the advantage of being mostly shared across all
20956 POSIX-compliant thread implementations, and it also provides under
20957 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
20958 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
20959 and @code{PTHREAD_PRIO_PROTECT}
20960 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
20961 semantics that can be selected using the predefined pragma
20962 @code{Locking_Policy}
20963 @cindex pragma Locking_Policy (under rts-pthread)
20964 with respectively
20965 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
20966 @cindex @code{Inheritance_Locking} (under rts-pthread)
20967 @cindex @code{Ceiling_Locking} (under rts-pthread)
20969 As explained above, the native run-time library is based on the Solaris thread
20970 library (@code{libthread}) and is the default library.
20971 The FSU run-time library is based on the FSU threads.
20972 @cindex FSU threads library
20974 Starting with Solaris 2.5.1, when the Solaris threads library is used
20975 (this is the default), programs
20976 compiled with GNAT can automatically take advantage of
20977 and can thus execute on multiple processors.
20978 The user can alternatively specify a processor on which the program should run
20979 to emulate a single-processor system. The multiprocessor / uniprocessor choice
20980 is made by
20981 setting the environment variable @code{GNAT_PROCESSOR}
20982 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
20983 to one of the following:
20985 @table @code
20986 @item -2
20987 Use the default configuration (run the program on all
20988          available processors) - this is the same as having
20989          @code{GNAT_PROCESSOR} unset
20991 @item -1
20992 Let the run-time implementation choose one processor and run the program on
20993          that processor
20995 @item 0 .. Last_Proc
20996 Run the program on the specified processor.
20997   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
20998 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
20999 @end table
21002 @node Building and Debugging 64-bit Applications
21003 @subsection Building and Debugging 64-bit Applications
21005 @noindent
21006 In a 64-bit application, all the sources involved must be compiled with the
21007 @option{-m64} command-line option, and a specific GNAT library (compiled with
21008 this option) is required.
21009 The easiest way to build a 64bit application is to add
21010 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21012 To debug these applications, dwarf-2 debug information is required, so you
21013 have to add @option{-gdwarf-2} to your gnatmake arguments.
21014 In addition, a special
21015 version of gdb, called @command{gdb64}, needs to be used.
21017 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21018 amounts to:
21020 @smallexample
21021      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21022      $ gdb64 hello
21023 @end smallexample
21027 @node IRIX-Specific Considerations
21028 @section IRIX-Specific Considerations
21029 @cindex IRIX thread library
21031 @noindent
21032 On SGI IRIX, the thread library depends on which compiler is used.
21033 The @emph{o32 ABI} compiler comes with a run-time library based on the
21034 user-level @code{athread}
21035 library. Thus kernel-level capabilities such as nonblocking system
21036 calls or time slicing can only be achieved reliably by specifying different
21037 @code{sprocs} via the pragma @code{Task_Info}
21038 @cindex pragma Task_Info (and IRIX threads)
21039 and the
21040 @code{System.Task_Info} package.
21041 @cindex @code{System.Task_Info} package (and IRIX threads)
21042 See the @cite{GNAT Reference Manual} for further information.
21044 The @emph{n32 ABI} compiler comes with a run-time library based on the
21045 kernel POSIX threads and thus does not have the limitations mentioned above.
21048 @node Linux-Specific Considerations
21049 @section Linux-Specific Considerations
21050 @cindex Linux threads libraries
21052 @noindent
21053 The default thread library under GNU/Linux has the following disadvantages
21054 compared to other native thread libraries:
21056 @itemize @bullet
21057 @item The size of the task's stack is limited to 2 megabytes.
21058 @item  The signal model is not POSIX compliant, which means that to send a
21059   signal to the process, you need to send the signal to all threads,
21060   e.g. by using @code{killpg()}.
21061 @end itemize
21065 @c *******************************
21066 @node Example of Binder Output File
21067 @appendix Example of Binder Output File
21069 @noindent
21070 This Appendix displays the source code for @command{gnatbind}'s output
21071 file generated for a simple ``Hello World'' program.
21072 Comments have been added for clarification purposes.
21075 @smallexample @c adanocomment
21076 @iftex
21077 @leftskip=0cm
21078 @end iftex
21079 --  The package is called Ada_Main unless this name is actually used
21080 --  as a unit name in the partition, in which case some other unique
21081 --  name is used.
21083 with System;
21084 package ada_main is
21086    Elab_Final_Code : Integer;
21087    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21089    --  The main program saves the parameters (argument count,
21090    --  argument values, environment pointer) in global variables
21091    --  for later access by other units including
21092    --  Ada.Command_Line.
21094    gnat_argc : Integer;
21095    gnat_argv : System.Address;
21096    gnat_envp : System.Address;
21098    --  The actual variables are stored in a library routine. This
21099    --  is useful for some shared library situations, where there
21100    --  are problems if variables are not in the library.
21102    pragma Import (C, gnat_argc);
21103    pragma Import (C, gnat_argv);
21104    pragma Import (C, gnat_envp);
21106    --  The exit status is similarly an external location
21108    gnat_exit_status : Integer;
21109    pragma Import (C, gnat_exit_status);
21111    GNAT_Version : constant String :=
21112                     "GNAT Version: 3.15w (20010315)";
21113    pragma Export (C, GNAT_Version, "__gnat_version");
21115    --  This is the generated adafinal routine that performs
21116    --  finalization at the end of execution. In the case where
21117    --  Ada is the main program, this main program makes a call
21118    --  to adafinal at program termination.
21120    procedure adafinal;
21121    pragma Export (C, adafinal, "adafinal");
21123    --  This is the generated adainit routine that performs
21124    --  initialization at the start of execution. In the case
21125    --  where Ada is the main program, this main program makes
21126    --  a call to adainit at program startup.
21128    procedure adainit;
21129    pragma Export (C, adainit, "adainit");
21131    --  This routine is called at the start of execution. It is
21132    --  a dummy routine that is used by the debugger to breakpoint
21133    --  at the start of execution.
21135    procedure Break_Start;
21136    pragma Import (C, Break_Start, "__gnat_break_start");
21138    --  This is the actual generated main program (it would be
21139    --  suppressed if the no main program switch were used). As
21140    --  required by standard system conventions, this program has
21141    --  the external name main.
21143    function main
21144      (argc : Integer;
21145       argv : System.Address;
21146       envp : System.Address)
21147       return Integer;
21148    pragma Export (C, main, "main");
21150    --  The following set of constants give the version
21151    --  identification values for every unit in the bound
21152    --  partition. This identification is computed from all
21153    --  dependent semantic units, and corresponds to the
21154    --  string that would be returned by use of the
21155    --  Body_Version or Version attributes.
21157    type Version_32 is mod 2 ** 32;
21158    u00001 : constant Version_32 := 16#7880BEB3#;
21159    u00002 : constant Version_32 := 16#0D24CBD0#;
21160    u00003 : constant Version_32 := 16#3283DBEB#;
21161    u00004 : constant Version_32 := 16#2359F9ED#;
21162    u00005 : constant Version_32 := 16#664FB847#;
21163    u00006 : constant Version_32 := 16#68E803DF#;
21164    u00007 : constant Version_32 := 16#5572E604#;
21165    u00008 : constant Version_32 := 16#46B173D8#;
21166    u00009 : constant Version_32 := 16#156A40CF#;
21167    u00010 : constant Version_32 := 16#033DABE0#;
21168    u00011 : constant Version_32 := 16#6AB38FEA#;
21169    u00012 : constant Version_32 := 16#22B6217D#;
21170    u00013 : constant Version_32 := 16#68A22947#;
21171    u00014 : constant Version_32 := 16#18CC4A56#;
21172    u00015 : constant Version_32 := 16#08258E1B#;
21173    u00016 : constant Version_32 := 16#367D5222#;
21174    u00017 : constant Version_32 := 16#20C9ECA4#;
21175    u00018 : constant Version_32 := 16#50D32CB6#;
21176    u00019 : constant Version_32 := 16#39A8BB77#;
21177    u00020 : constant Version_32 := 16#5CF8FA2B#;
21178    u00021 : constant Version_32 := 16#2F1EB794#;
21179    u00022 : constant Version_32 := 16#31AB6444#;
21180    u00023 : constant Version_32 := 16#1574B6E9#;
21181    u00024 : constant Version_32 := 16#5109C189#;
21182    u00025 : constant Version_32 := 16#56D770CD#;
21183    u00026 : constant Version_32 := 16#02F9DE3D#;
21184    u00027 : constant Version_32 := 16#08AB6B2C#;
21185    u00028 : constant Version_32 := 16#3FA37670#;
21186    u00029 : constant Version_32 := 16#476457A0#;
21187    u00030 : constant Version_32 := 16#731E1B6E#;
21188    u00031 : constant Version_32 := 16#23C2E789#;
21189    u00032 : constant Version_32 := 16#0F1BD6A1#;
21190    u00033 : constant Version_32 := 16#7C25DE96#;
21191    u00034 : constant Version_32 := 16#39ADFFA2#;
21192    u00035 : constant Version_32 := 16#571DE3E7#;
21193    u00036 : constant Version_32 := 16#5EB646AB#;
21194    u00037 : constant Version_32 := 16#4249379B#;
21195    u00038 : constant Version_32 := 16#0357E00A#;
21196    u00039 : constant Version_32 := 16#3784FB72#;
21197    u00040 : constant Version_32 := 16#2E723019#;
21198    u00041 : constant Version_32 := 16#623358EA#;
21199    u00042 : constant Version_32 := 16#107F9465#;
21200    u00043 : constant Version_32 := 16#6843F68A#;
21201    u00044 : constant Version_32 := 16#63305874#;
21202    u00045 : constant Version_32 := 16#31E56CE1#;
21203    u00046 : constant Version_32 := 16#02917970#;
21204    u00047 : constant Version_32 := 16#6CCBA70E#;
21205    u00048 : constant Version_32 := 16#41CD4204#;
21206    u00049 : constant Version_32 := 16#572E3F58#;
21207    u00050 : constant Version_32 := 16#20729FF5#;
21208    u00051 : constant Version_32 := 16#1D4F93E8#;
21209    u00052 : constant Version_32 := 16#30B2EC3D#;
21210    u00053 : constant Version_32 := 16#34054F96#;
21211    u00054 : constant Version_32 := 16#5A199860#;
21212    u00055 : constant Version_32 := 16#0E7F912B#;
21213    u00056 : constant Version_32 := 16#5760634A#;
21214    u00057 : constant Version_32 := 16#5D851835#;
21216    --  The following Export pragmas export the version numbers
21217    --  with symbolic names ending in B (for body) or S
21218    --  (for spec) so that they can be located in a link. The
21219    --  information provided here is sufficient to track down
21220    --  the exact versions of units used in a given build.
21222    pragma Export (C, u00001, "helloB");
21223    pragma Export (C, u00002, "system__standard_libraryB");
21224    pragma Export (C, u00003, "system__standard_libraryS");
21225    pragma Export (C, u00004, "adaS");
21226    pragma Export (C, u00005, "ada__text_ioB");
21227    pragma Export (C, u00006, "ada__text_ioS");
21228    pragma Export (C, u00007, "ada__exceptionsB");
21229    pragma Export (C, u00008, "ada__exceptionsS");
21230    pragma Export (C, u00009, "gnatS");
21231    pragma Export (C, u00010, "gnat__heap_sort_aB");
21232    pragma Export (C, u00011, "gnat__heap_sort_aS");
21233    pragma Export (C, u00012, "systemS");
21234    pragma Export (C, u00013, "system__exception_tableB");
21235    pragma Export (C, u00014, "system__exception_tableS");
21236    pragma Export (C, u00015, "gnat__htableB");
21237    pragma Export (C, u00016, "gnat__htableS");
21238    pragma Export (C, u00017, "system__exceptionsS");
21239    pragma Export (C, u00018, "system__machine_state_operationsB");
21240    pragma Export (C, u00019, "system__machine_state_operationsS");
21241    pragma Export (C, u00020, "system__machine_codeS");
21242    pragma Export (C, u00021, "system__storage_elementsB");
21243    pragma Export (C, u00022, "system__storage_elementsS");
21244    pragma Export (C, u00023, "system__secondary_stackB");
21245    pragma Export (C, u00024, "system__secondary_stackS");
21246    pragma Export (C, u00025, "system__parametersB");
21247    pragma Export (C, u00026, "system__parametersS");
21248    pragma Export (C, u00027, "system__soft_linksB");
21249    pragma Export (C, u00028, "system__soft_linksS");
21250    pragma Export (C, u00029, "system__stack_checkingB");
21251    pragma Export (C, u00030, "system__stack_checkingS");
21252    pragma Export (C, u00031, "system__tracebackB");
21253    pragma Export (C, u00032, "system__tracebackS");
21254    pragma Export (C, u00033, "ada__streamsS");
21255    pragma Export (C, u00034, "ada__tagsB");
21256    pragma Export (C, u00035, "ada__tagsS");
21257    pragma Export (C, u00036, "system__string_opsB");
21258    pragma Export (C, u00037, "system__string_opsS");
21259    pragma Export (C, u00038, "interfacesS");
21260    pragma Export (C, u00039, "interfaces__c_streamsB");
21261    pragma Export (C, u00040, "interfaces__c_streamsS");
21262    pragma Export (C, u00041, "system__file_ioB");
21263    pragma Export (C, u00042, "system__file_ioS");
21264    pragma Export (C, u00043, "ada__finalizationB");
21265    pragma Export (C, u00044, "ada__finalizationS");
21266    pragma Export (C, u00045, "system__finalization_rootB");
21267    pragma Export (C, u00046, "system__finalization_rootS");
21268    pragma Export (C, u00047, "system__finalization_implementationB");
21269    pragma Export (C, u00048, "system__finalization_implementationS");
21270    pragma Export (C, u00049, "system__string_ops_concat_3B");
21271    pragma Export (C, u00050, "system__string_ops_concat_3S");
21272    pragma Export (C, u00051, "system__stream_attributesB");
21273    pragma Export (C, u00052, "system__stream_attributesS");
21274    pragma Export (C, u00053, "ada__io_exceptionsS");
21275    pragma Export (C, u00054, "system__unsigned_typesS");
21276    pragma Export (C, u00055, "system__file_control_blockS");
21277    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21278    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21280    -- BEGIN ELABORATION ORDER
21281    -- ada (spec)
21282    -- gnat (spec)
21283    -- gnat.heap_sort_a (spec)
21284    -- gnat.heap_sort_a (body)
21285    -- gnat.htable (spec)
21286    -- gnat.htable (body)
21287    -- interfaces (spec)
21288    -- system (spec)
21289    -- system.machine_code (spec)
21290    -- system.parameters (spec)
21291    -- system.parameters (body)
21292    -- interfaces.c_streams (spec)
21293    -- interfaces.c_streams (body)
21294    -- system.standard_library (spec)
21295    -- ada.exceptions (spec)
21296    -- system.exception_table (spec)
21297    -- system.exception_table (body)
21298    -- ada.io_exceptions (spec)
21299    -- system.exceptions (spec)
21300    -- system.storage_elements (spec)
21301    -- system.storage_elements (body)
21302    -- system.machine_state_operations (spec)
21303    -- system.machine_state_operations (body)
21304    -- system.secondary_stack (spec)
21305    -- system.stack_checking (spec)
21306    -- system.soft_links (spec)
21307    -- system.soft_links (body)
21308    -- system.stack_checking (body)
21309    -- system.secondary_stack (body)
21310    -- system.standard_library (body)
21311    -- system.string_ops (spec)
21312    -- system.string_ops (body)
21313    -- ada.tags (spec)
21314    -- ada.tags (body)
21315    -- ada.streams (spec)
21316    -- system.finalization_root (spec)
21317    -- system.finalization_root (body)
21318    -- system.string_ops_concat_3 (spec)
21319    -- system.string_ops_concat_3 (body)
21320    -- system.traceback (spec)
21321    -- system.traceback (body)
21322    -- ada.exceptions (body)
21323    -- system.unsigned_types (spec)
21324    -- system.stream_attributes (spec)
21325    -- system.stream_attributes (body)
21326    -- system.finalization_implementation (spec)
21327    -- system.finalization_implementation (body)
21328    -- ada.finalization (spec)
21329    -- ada.finalization (body)
21330    -- ada.finalization.list_controller (spec)
21331    -- ada.finalization.list_controller (body)
21332    -- system.file_control_block (spec)
21333    -- system.file_io (spec)
21334    -- system.file_io (body)
21335    -- ada.text_io (spec)
21336    -- ada.text_io (body)
21337    -- hello (body)
21338    -- END ELABORATION ORDER
21340 end ada_main;
21342 --  The following source file name pragmas allow the generated file
21343 --  names to be unique for different main programs. They are needed
21344 --  since the package name will always be Ada_Main.
21346 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21347 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21349 --  Generated package body for Ada_Main starts here
21351 package body ada_main is
21353    --  The actual finalization is performed by calling the
21354    --  library routine in System.Standard_Library.Adafinal
21356    procedure Do_Finalize;
21357    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21359    -------------
21360    -- adainit --
21361    -------------
21363 @findex adainit
21364    procedure adainit is
21366       --  These booleans are set to True once the associated unit has
21367       --  been elaborated. It is also used to avoid elaborating the
21368       --  same unit twice.
21370       E040 : Boolean;
21371       pragma Import (Ada, E040, "interfaces__c_streams_E");
21373       E008 : Boolean;
21374       pragma Import (Ada, E008, "ada__exceptions_E");
21376       E014 : Boolean;
21377       pragma Import (Ada, E014, "system__exception_table_E");
21379       E053 : Boolean;
21380       pragma Import (Ada, E053, "ada__io_exceptions_E");
21382       E017 : Boolean;
21383       pragma Import (Ada, E017, "system__exceptions_E");
21385       E024 : Boolean;
21386       pragma Import (Ada, E024, "system__secondary_stack_E");
21388       E030 : Boolean;
21389       pragma Import (Ada, E030, "system__stack_checking_E");
21391       E028 : Boolean;
21392       pragma Import (Ada, E028, "system__soft_links_E");
21394       E035 : Boolean;
21395       pragma Import (Ada, E035, "ada__tags_E");
21397       E033 : Boolean;
21398       pragma Import (Ada, E033, "ada__streams_E");
21400       E046 : Boolean;
21401       pragma Import (Ada, E046, "system__finalization_root_E");
21403       E048 : Boolean;
21404       pragma Import (Ada, E048, "system__finalization_implementation_E");
21406       E044 : Boolean;
21407       pragma Import (Ada, E044, "ada__finalization_E");
21409       E057 : Boolean;
21410       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21412       E055 : Boolean;
21413       pragma Import (Ada, E055, "system__file_control_block_E");
21415       E042 : Boolean;
21416       pragma Import (Ada, E042, "system__file_io_E");
21418       E006 : Boolean;
21419       pragma Import (Ada, E006, "ada__text_io_E");
21421       --  Set_Globals is a library routine that stores away the
21422       --  value of the indicated set of global values in global
21423       --  variables within the library.
21425       procedure Set_Globals
21426         (Main_Priority            : Integer;
21427          Time_Slice_Value         : Integer;
21428          WC_Encoding              : Character;
21429          Locking_Policy           : Character;
21430          Queuing_Policy           : Character;
21431          Task_Dispatching_Policy  : Character;
21432          Adafinal                 : System.Address;
21433          Unreserve_All_Interrupts : Integer;
21434          Exception_Tracebacks     : Integer);
21435 @findex __gnat_set_globals
21436       pragma Import (C, Set_Globals, "__gnat_set_globals");
21438       --  SDP_Table_Build is a library routine used to build the
21439       --  exception tables. See unit Ada.Exceptions in files
21440       --  a-except.ads/adb for full details of how zero cost
21441       --  exception handling works. This procedure, the call to
21442       --  it, and the two following tables are all omitted if the
21443       --  build is in longjmp/setjump exception mode.
21445 @findex SDP_Table_Build
21446 @findex Zero Cost Exceptions
21447       procedure SDP_Table_Build
21448         (SDP_Addresses   : System.Address;
21449          SDP_Count       : Natural;
21450          Elab_Addresses  : System.Address;
21451          Elab_Addr_Count : Natural);
21452       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21454       --  Table of Unit_Exception_Table addresses. Used for zero
21455       --  cost exception handling to build the top level table.
21457       ST : aliased constant array (1 .. 23) of System.Address := (
21458         Hello'UET_Address,
21459         Ada.Text_Io'UET_Address,
21460         Ada.Exceptions'UET_Address,
21461         Gnat.Heap_Sort_A'UET_Address,
21462         System.Exception_Table'UET_Address,
21463         System.Machine_State_Operations'UET_Address,
21464         System.Secondary_Stack'UET_Address,
21465         System.Parameters'UET_Address,
21466         System.Soft_Links'UET_Address,
21467         System.Stack_Checking'UET_Address,
21468         System.Traceback'UET_Address,
21469         Ada.Streams'UET_Address,
21470         Ada.Tags'UET_Address,
21471         System.String_Ops'UET_Address,
21472         Interfaces.C_Streams'UET_Address,
21473         System.File_Io'UET_Address,
21474         Ada.Finalization'UET_Address,
21475         System.Finalization_Root'UET_Address,
21476         System.Finalization_Implementation'UET_Address,
21477         System.String_Ops_Concat_3'UET_Address,
21478         System.Stream_Attributes'UET_Address,
21479         System.File_Control_Block'UET_Address,
21480         Ada.Finalization.List_Controller'UET_Address);
21482       --  Table of addresses of elaboration routines. Used for
21483       --  zero cost exception handling to make sure these
21484       --  addresses are included in the top level procedure
21485       --  address table.
21487       EA : aliased constant array (1 .. 23) of System.Address := (
21488         adainit'Code_Address,
21489         Do_Finalize'Code_Address,
21490         Ada.Exceptions'Elab_Spec'Address,
21491         System.Exceptions'Elab_Spec'Address,
21492         Interfaces.C_Streams'Elab_Spec'Address,
21493         System.Exception_Table'Elab_Body'Address,
21494         Ada.Io_Exceptions'Elab_Spec'Address,
21495         System.Stack_Checking'Elab_Spec'Address,
21496         System.Soft_Links'Elab_Body'Address,
21497         System.Secondary_Stack'Elab_Body'Address,
21498         Ada.Tags'Elab_Spec'Address,
21499         Ada.Tags'Elab_Body'Address,
21500         Ada.Streams'Elab_Spec'Address,
21501         System.Finalization_Root'Elab_Spec'Address,
21502         Ada.Exceptions'Elab_Body'Address,
21503         System.Finalization_Implementation'Elab_Spec'Address,
21504         System.Finalization_Implementation'Elab_Body'Address,
21505         Ada.Finalization'Elab_Spec'Address,
21506         Ada.Finalization.List_Controller'Elab_Spec'Address,
21507         System.File_Control_Block'Elab_Spec'Address,
21508         System.File_Io'Elab_Body'Address,
21509         Ada.Text_Io'Elab_Spec'Address,
21510         Ada.Text_Io'Elab_Body'Address);
21512    --  Start of processing for adainit
21514    begin
21516       --  Call SDP_Table_Build to build the top level procedure
21517       --  table for zero cost exception handling (omitted in
21518       --  longjmp/setjump mode).
21520       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21522       --  Call Set_Globals to record various information for
21523       --  this partition.  The values are derived by the binder
21524       --  from information stored in the ali files by the compiler.
21526 @findex __gnat_set_globals
21527       Set_Globals
21528         (Main_Priority            => -1,
21529          --  Priority of main program, -1 if no pragma Priority used
21531          Time_Slice_Value         => -1,
21532          --  Time slice from Time_Slice pragma, -1 if none used
21534          WC_Encoding              => 'b',
21535          --  Wide_Character encoding used, default is brackets
21537          Locking_Policy           => ' ',
21538          --  Locking_Policy used, default of space means not
21539          --  specified, otherwise it is the first character of
21540          --  the policy name.
21542          Queuing_Policy           => ' ',
21543          --  Queuing_Policy used, default of space means not
21544          --  specified, otherwise it is the first character of
21545          --  the policy name.
21547          Task_Dispatching_Policy  => ' ',
21548          --  Task_Dispatching_Policy used, default of space means
21549          --  not specified, otherwise first character of the
21550          --  policy name.
21552          Adafinal                 => System.Null_Address,
21553          --  Address of Adafinal routine, not used anymore
21555          Unreserve_All_Interrupts => 0,
21556          --  Set true if pragma Unreserve_All_Interrupts was used
21558          Exception_Tracebacks     => 0);
21559          --  Indicates if exception tracebacks are enabled
21561       Elab_Final_Code := 1;
21563       --  Now we have the elaboration calls for all units in the partition.
21564       --  The Elab_Spec and Elab_Body attributes generate references to the
21565       --  implicit elaboration procedures generated by the compiler for
21566       --  each unit that requires elaboration.
21568       if not E040 then
21569          Interfaces.C_Streams'Elab_Spec;
21570       end if;
21571       E040 := True;
21572       if not E008 then
21573          Ada.Exceptions'Elab_Spec;
21574       end if;
21575       if not E014 then
21576          System.Exception_Table'Elab_Body;
21577          E014 := True;
21578       end if;
21579       if not E053 then
21580          Ada.Io_Exceptions'Elab_Spec;
21581          E053 := True;
21582       end if;
21583       if not E017 then
21584          System.Exceptions'Elab_Spec;
21585          E017 := True;
21586       end if;
21587       if not E030 then
21588          System.Stack_Checking'Elab_Spec;
21589       end if;
21590       if not E028 then
21591          System.Soft_Links'Elab_Body;
21592          E028 := True;
21593       end if;
21594       E030 := True;
21595       if not E024 then
21596          System.Secondary_Stack'Elab_Body;
21597          E024 := True;
21598       end if;
21599       if not E035 then
21600          Ada.Tags'Elab_Spec;
21601       end if;
21602       if not E035 then
21603          Ada.Tags'Elab_Body;
21604          E035 := True;
21605       end if;
21606       if not E033 then
21607          Ada.Streams'Elab_Spec;
21608          E033 := True;
21609       end if;
21610       if not E046 then
21611          System.Finalization_Root'Elab_Spec;
21612       end if;
21613       E046 := True;
21614       if not E008 then
21615          Ada.Exceptions'Elab_Body;
21616          E008 := True;
21617       end if;
21618       if not E048 then
21619          System.Finalization_Implementation'Elab_Spec;
21620       end if;
21621       if not E048 then
21622          System.Finalization_Implementation'Elab_Body;
21623          E048 := True;
21624       end if;
21625       if not E044 then
21626          Ada.Finalization'Elab_Spec;
21627       end if;
21628       E044 := True;
21629       if not E057 then
21630          Ada.Finalization.List_Controller'Elab_Spec;
21631       end if;
21632       E057 := True;
21633       if not E055 then
21634          System.File_Control_Block'Elab_Spec;
21635          E055 := True;
21636       end if;
21637       if not E042 then
21638          System.File_Io'Elab_Body;
21639          E042 := True;
21640       end if;
21641       if not E006 then
21642          Ada.Text_Io'Elab_Spec;
21643       end if;
21644       if not E006 then
21645          Ada.Text_Io'Elab_Body;
21646          E006 := True;
21647       end if;
21649       Elab_Final_Code := 0;
21650    end adainit;
21652    --------------
21653    -- adafinal --
21654    --------------
21656 @findex adafinal
21657    procedure adafinal is
21658    begin
21659       Do_Finalize;
21660    end adafinal;
21662    ----------
21663    -- main --
21664    ----------
21666    --  main is actually a function, as in the ANSI C standard,
21667    --  defined to return the exit status. The three parameters
21668    --  are the argument count, argument values and environment
21669    --  pointer.
21671 @findex Main Program
21672    function main
21673      (argc : Integer;
21674       argv : System.Address;
21675       envp : System.Address)
21676       return Integer
21677    is
21678       --  The initialize routine performs low level system
21679       --  initialization using a standard library routine which
21680       --  sets up signal handling and performs any other
21681       --  required setup. The routine can be found in file
21682       --  a-init.c.
21684 @findex __gnat_initialize
21685       procedure initialize;
21686       pragma Import (C, initialize, "__gnat_initialize");
21688       --  The finalize routine performs low level system
21689       --  finalization using a standard library routine. The
21690       --  routine is found in file a-final.c and in the standard
21691       --  distribution is a dummy routine that does nothing, so
21692       --  really this is a hook for special user finalization.
21694 @findex __gnat_finalize
21695       procedure finalize;
21696       pragma Import (C, finalize, "__gnat_finalize");
21698       --  We get to the main program of the partition by using
21699       --  pragma Import because if we try to with the unit and
21700       --  call it Ada style, then not only do we waste time
21701       --  recompiling it, but also, we don't really know the right
21702       --  switches (e.g. identifier character set) to be used
21703       --  to compile it.
21705       procedure Ada_Main_Program;
21706       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
21708    --  Start of processing for main
21710    begin
21711       --  Save global variables
21713       gnat_argc := argc;
21714       gnat_argv := argv;
21715       gnat_envp := envp;
21717       --  Call low level system initialization
21719       Initialize;
21721       --  Call our generated Ada initialization routine
21723       adainit;
21725       --  This is the point at which we want the debugger to get
21726       --  control
21728       Break_Start;
21730       --  Now we call the main program of the partition
21732       Ada_Main_Program;
21734       --  Perform Ada finalization
21736       adafinal;
21738       --  Perform low level system finalization
21740       Finalize;
21742       --  Return the proper exit status
21743       return (gnat_exit_status);
21744    end;
21746 --  This section is entirely comments, so it has no effect on the
21747 --  compilation of the Ada_Main package. It provides the list of
21748 --  object files and linker options, as well as some standard
21749 --  libraries needed for the link. The gnatlink utility parses
21750 --  this b~hello.adb file to read these comment lines to generate
21751 --  the appropriate command line arguments for the call to the
21752 --  system linker. The BEGIN/END lines are used for sentinels for
21753 --  this parsing operation.
21755 --  The exact file names will of course depend on the environment,
21756 --  host/target and location of files on the host system.
21758 @findex Object file list
21759 -- BEGIN Object file/option list
21760    --   ./hello.o
21761    --   -L./
21762    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
21763    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
21764 -- END Object file/option list
21766 end ada_main;
21767 @end smallexample
21769 @noindent
21770 The Ada code in the above example is exactly what is generated by the
21771 binder. We have added comments to more clearly indicate the function
21772 of each part of the generated @code{Ada_Main} package.
21774 The code is standard Ada in all respects, and can be processed by any
21775 tools that handle Ada. In particular, it is possible to use the debugger
21776 in Ada mode to debug the generated @code{Ada_Main} package. For example,
21777 suppose that for reasons that you do not understand, your program is crashing
21778 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
21779 you can place a breakpoint on the call:
21781 @smallexample @c ada
21782 Ada.Text_Io'Elab_Body;
21783 @end smallexample
21785 @noindent
21786 and trace the elaboration routine for this package to find out where
21787 the problem might be (more usually of course you would be debugging
21788 elaboration code in your own application).
21791 @node Elaboration Order Handling in GNAT
21792 @appendix Elaboration Order Handling in GNAT
21793 @cindex Order of elaboration
21794 @cindex Elaboration control
21796 @menu
21797 * Elaboration Code in Ada 95::
21798 * Checking the Elaboration Order in Ada 95::
21799 * Controlling the Elaboration Order in Ada 95::
21800 * Controlling Elaboration in GNAT - Internal Calls::
21801 * Controlling Elaboration in GNAT - External Calls::
21802 * Default Behavior in GNAT - Ensuring Safety::
21803 * Treatment of Pragma Elaborate::
21804 * Elaboration Issues for Library Tasks::
21805 * Mixing Elaboration Models::
21806 * What to Do If the Default Elaboration Behavior Fails::
21807 * Elaboration for Access-to-Subprogram Values::
21808 * Summary of Procedures for Elaboration Control::
21809 * Other Elaboration Order Considerations::
21810 @end menu
21812 @noindent
21813 This chapter describes the handling of elaboration code in Ada 95 and
21814 in GNAT, and discusses how the order of elaboration of program units can
21815 be controlled in GNAT, either automatically or with explicit programming
21816 features.
21818 @node Elaboration Code in Ada 95
21819 @section Elaboration Code in Ada 95
21821 @noindent
21822 Ada 95 provides rather general mechanisms for executing code at elaboration
21823 time, that is to say before the main program starts executing. Such code arises
21824 in three contexts:
21826 @table @asis
21827 @item Initializers for variables.
21828 Variables declared at the library level, in package specs or bodies, can
21829 require initialization that is performed at elaboration time, as in:
21830 @smallexample @c ada
21831 @cartouche
21832 Sqrt_Half : Float := Sqrt (0.5);
21833 @end cartouche
21834 @end smallexample
21836 @item Package initialization code
21837 Code in a @code{BEGIN-END} section at the outer level of a package body is
21838 executed as part of the package body elaboration code.
21840 @item Library level task allocators
21841 Tasks that are declared using task allocators at the library level
21842 start executing immediately and hence can execute at elaboration time.
21843 @end table
21845 @noindent
21846 Subprogram calls are possible in any of these contexts, which means that
21847 any arbitrary part of the program may be executed as part of the elaboration
21848 code. It is even possible to write a program which does all its work at
21849 elaboration time, with a null main program, although stylistically this
21850 would usually be considered an inappropriate way to structure
21851 a program.
21853 An important concern arises in the context of elaboration code:
21854 we have to be sure that it is executed in an appropriate order. What we
21855 have is a series of elaboration code sections, potentially one section
21856 for each unit in the program. It is important that these execute
21857 in the correct order. Correctness here means that, taking the above
21858 example of the declaration of @code{Sqrt_Half},
21859 if some other piece of
21860 elaboration code references @code{Sqrt_Half},
21861 then it must run after the
21862 section of elaboration code that contains the declaration of
21863 @code{Sqrt_Half}.
21865 There would never be any order of elaboration problem if we made a rule
21866 that whenever you @code{with} a unit, you must elaborate both the spec and body
21867 of that unit before elaborating the unit doing the @code{with}'ing:
21869 @smallexample @c ada
21870 @group
21871 @cartouche
21872 with Unit_1;
21873 package Unit_2 is ...
21874 @end cartouche
21875 @end group
21876 @end smallexample
21878 @noindent
21879 would require that both the body and spec of @code{Unit_1} be elaborated
21880 before the spec of @code{Unit_2}. However, a rule like that would be far too
21881 restrictive. In particular, it would make it impossible to have routines
21882 in separate packages that were mutually recursive.
21884 You might think that a clever enough compiler could look at the actual
21885 elaboration code and determine an appropriate correct order of elaboration,
21886 but in the general case, this is not possible. Consider the following
21887 example.
21889 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
21890 that references
21891 the variable @code{Sqrt_1}, which is declared in the elaboration code
21892 of the body of @code{Unit_1}:
21894 @smallexample @c ada
21895 @cartouche
21896 Sqrt_1 : Float := Sqrt (0.1);
21897 @end cartouche
21898 @end smallexample
21900 @noindent
21901 The elaboration code of the body of @code{Unit_1} also contains:
21903 @smallexample @c ada
21904 @group
21905 @cartouche
21906 if expression_1 = 1 then
21907    Q := Unit_2.Func_2;
21908 end if;
21909 @end cartouche
21910 @end group
21911 @end smallexample
21913 @noindent
21914 @code{Unit_2} is exactly parallel,
21915 it has a procedure @code{Func_2} that references
21916 the variable @code{Sqrt_2}, which is declared in the elaboration code of
21917 the body @code{Unit_2}:
21919 @smallexample @c ada
21920 @cartouche
21921 Sqrt_2 : Float := Sqrt (0.1);
21922 @end cartouche
21923 @end smallexample
21925 @noindent
21926 The elaboration code of the body of @code{Unit_2} also contains:
21928 @smallexample @c ada
21929 @group
21930 @cartouche
21931 if expression_2 = 2 then
21932    Q := Unit_1.Func_1;
21933 end if;
21934 @end cartouche
21935 @end group
21936 @end smallexample
21938 @noindent
21939 Now the question is, which of the following orders of elaboration is
21940 acceptable:
21942 @smallexample
21943 @group
21944 Spec of Unit_1
21945 Spec of Unit_2
21946 Body of Unit_1
21947 Body of Unit_2
21948 @end group
21949 @end smallexample
21951 @noindent
21954 @smallexample
21955 @group
21956 Spec of Unit_2
21957 Spec of Unit_1
21958 Body of Unit_2
21959 Body of Unit_1
21960 @end group
21961 @end smallexample
21963 @noindent
21964 If you carefully analyze the flow here, you will see that you cannot tell
21965 at compile time the answer to this question.
21966 If @code{expression_1} is not equal to 1,
21967 and @code{expression_2} is not equal to 2,
21968 then either order is acceptable, because neither of the function calls is
21969 executed. If both tests evaluate to true, then neither order is acceptable
21970 and in fact there is no correct order.
21972 If one of the two expressions is true, and the other is false, then one
21973 of the above orders is correct, and the other is incorrect. For example,
21974 if @code{expression_1} = 1 and @code{expression_2} /= 2,
21975 then the call to @code{Func_2}
21976 will occur, but not the call to @code{Func_1.}
21977 This means that it is essential
21978 to elaborate the body of @code{Unit_1} before
21979 the body of @code{Unit_2}, so the first
21980 order of elaboration is correct and the second is wrong.
21982 By making @code{expression_1} and @code{expression_2}
21983 depend on input data, or perhaps
21984 the time of day, we can make it impossible for the compiler or binder
21985 to figure out which of these expressions will be true, and hence it
21986 is impossible to guarantee a safe order of elaboration at run time.
21988 @node Checking the Elaboration Order in Ada 95
21989 @section Checking the Elaboration Order in Ada 95
21991 @noindent
21992 In some languages that involve the same kind of elaboration problems,
21993 e.g. Java and C++, the programmer is expected to worry about these
21994 ordering problems himself, and it is common to
21995 write a program in which an incorrect elaboration order  gives
21996 surprising results, because it references variables before they
21997 are initialized.
21998 Ada 95 is designed to be a safe language, and a programmer-beware approach is
21999 clearly not sufficient. Consequently, the language provides three lines
22000 of defense:
22002 @table @asis
22003 @item Standard rules
22004 Some standard rules restrict the possible choice of elaboration
22005 order. In particular, if you @code{with} a unit, then its spec is always
22006 elaborated before the unit doing the @code{with}. Similarly, a parent
22007 spec is always elaborated before the child spec, and finally
22008 a spec is always elaborated before its corresponding body.
22010 @item Dynamic elaboration checks
22011 @cindex Elaboration checks
22012 @cindex Checks, elaboration
22013 Dynamic checks are made at run time, so that if some entity is accessed
22014 before it is elaborated (typically  by means of a subprogram call)
22015 then the exception (@code{Program_Error}) is raised.
22017 @item Elaboration control
22018 Facilities are provided for the programmer to specify the desired order
22019 of elaboration.
22020 @end table
22022 Let's look at these facilities in more detail. First, the rules for
22023 dynamic checking. One possible rule would be simply to say that the
22024 exception is raised if you access a variable which has not yet been
22025 elaborated. The trouble with this approach is that it could require
22026 expensive checks on every variable reference. Instead Ada 95 has two
22027 rules which are a little more restrictive, but easier to check, and
22028 easier to state:
22030 @table @asis
22031 @item Restrictions on calls
22032 A subprogram can only be called at elaboration time if its body
22033 has been elaborated. The rules for elaboration given above guarantee
22034 that the spec of the subprogram has been elaborated before the
22035 call, but not the body. If this rule is violated, then the
22036 exception @code{Program_Error} is raised.
22038 @item Restrictions on instantiations
22039 A generic unit can only be instantiated if the body of the generic
22040 unit has been elaborated. Again, the rules for elaboration given above
22041 guarantee that the spec of the generic unit has been elaborated
22042 before the instantiation, but not the body. If this rule is
22043 violated, then the exception @code{Program_Error} is raised.
22044 @end table
22046 @noindent
22047 The idea is that if the body has been elaborated, then any variables
22048 it references must have been elaborated; by checking for the body being
22049 elaborated we guarantee that none of its references causes any
22050 trouble. As we noted above, this is a little too restrictive, because a
22051 subprogram that has no non-local references in its body may in fact be safe
22052 to call. However, it really would be unsafe to rely on this, because
22053 it would mean that the caller was aware of details of the implementation
22054 in the body. This goes against the basic tenets of Ada.
22056 A plausible implementation can be described as follows.
22057 A Boolean variable is associated with each subprogram
22058 and each generic unit. This variable is initialized to False, and is set to
22059 True at the point body is elaborated. Every call or instantiation checks the
22060 variable, and raises @code{Program_Error} if the variable is False.
22062 Note that one might think that it would be good enough to have one Boolean
22063 variable for each package, but that would not deal with cases of trying
22064 to call a body in the same package as the call
22065 that has not been elaborated yet.
22066 Of course a compiler may be able to do enough analysis to optimize away
22067 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22068 does such optimizations, but still the easiest conceptual model is to
22069 think of there being one variable per subprogram.
22071 @node Controlling the Elaboration Order in Ada 95
22072 @section Controlling the Elaboration Order in Ada 95
22074 @noindent
22075 In the previous section we discussed the rules in Ada 95 which ensure
22076 that @code{Program_Error} is raised if an incorrect elaboration order is
22077 chosen. This prevents erroneous executions, but we need mechanisms to
22078 specify a correct execution and avoid the exception altogether.
22079 To achieve this, Ada 95 provides a number of features for controlling
22080 the order of elaboration. We discuss these features in this section.
22082 First, there are several ways of indicating to the compiler that a given
22083 unit has no elaboration problems:
22085 @table @asis
22086 @item packages that do not require a body
22087 In Ada 95, a library package that does not require a body does not permit
22088 a body. This means that if we have a such a package, as in:
22090 @smallexample @c ada
22091 @group
22092 @cartouche
22093 package Definitions is
22094    generic
22095       type m is new integer;
22096    package Subp is
22097       type a is array (1 .. 10) of m;
22098       type b is array (1 .. 20) of m;
22099    end Subp;
22100 end Definitions;
22101 @end cartouche
22102 @end group
22103 @end smallexample
22105 @noindent
22106 A package that @code{with}'s @code{Definitions} may safely instantiate
22107 @code{Definitions.Subp} because the compiler can determine that there
22108 definitely is no package body to worry about in this case
22110 @item pragma Pure
22111 @cindex pragma Pure
22112 @findex Pure
22113 Places sufficient restrictions on a unit to guarantee that
22114 no call to any subprogram in the unit can result in an
22115 elaboration problem. This means that the compiler does not need
22116 to worry about the point of elaboration of such units, and in
22117 particular, does not need to check any calls to any subprograms
22118 in this unit.
22120 @item pragma Preelaborate
22121 @findex Preelaborate
22122 @cindex pragma Preelaborate
22123 This pragma places slightly less stringent restrictions on a unit than
22124 does pragma Pure,
22125 but these restrictions are still sufficient to ensure that there
22126 are no elaboration problems with any calls to the unit.
22128 @item pragma Elaborate_Body
22129 @findex Elaborate_Body
22130 @cindex pragma Elaborate_Body
22131 This pragma requires that the body of a unit be elaborated immediately
22132 after its spec. Suppose a unit @code{A} has such a pragma,
22133 and unit @code{B} does
22134 a @code{with} of unit @code{A}. Recall that the standard rules require
22135 the spec of unit @code{A}
22136 to be elaborated before the @code{with}'ing unit; given the pragma in
22137 @code{A}, we also know that the body of @code{A}
22138 will be elaborated before @code{B}, so
22139 that calls to @code{A} are safe and do not need a check.
22140 @end table
22142 @noindent
22143 Note that,
22144 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22145 the use of
22146 @code{Elaborate_Body} does not guarantee that the program is
22147 free of elaboration problems, because it may not be possible
22148 to satisfy the requested elaboration order.
22149 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22150 If a programmer
22151 marks @code{Unit_1} as @code{Elaborate_Body},
22152 and not @code{Unit_2,} then the order of
22153 elaboration will be:
22155 @smallexample
22156 @group
22157 Spec of Unit_2
22158 Spec of Unit_1
22159 Body of Unit_1
22160 Body of Unit_2
22161 @end group
22162 @end smallexample
22164 @noindent
22165 Now that means that the call to @code{Func_1} in @code{Unit_2}
22166 need not be checked,
22167 it must be safe. But the call to @code{Func_2} in
22168 @code{Unit_1} may still fail if
22169 @code{Expression_1} is equal to 1,
22170 and the programmer must still take
22171 responsibility for this not being the case.
22173 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22174 eliminated, except for calls entirely within a body, which are
22175 in any case fully under programmer control. However, using the pragma
22176 everywhere is not always possible.
22177 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22178 we marked both of them as having pragma @code{Elaborate_Body}, then
22179 clearly there would be no possible elaboration order.
22181 The above pragmas allow a server to guarantee safe use by clients, and
22182 clearly this is the preferable approach. Consequently a good rule in
22183 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22184 and if this is not possible,
22185 mark them as @code{Elaborate_Body} if possible.
22186 As we have seen, there are situations where neither of these
22187 three pragmas can be used.
22188 So we also provide methods for clients to control the
22189 order of elaboration of the servers on which they depend:
22191 @table @asis
22192 @item pragma Elaborate (unit)
22193 @findex Elaborate
22194 @cindex pragma Elaborate
22195 This pragma is placed in the context clause, after a @code{with} clause,
22196 and it requires that the body of the named unit be elaborated before
22197 the unit in which the pragma occurs. The idea is to use this pragma
22198 if the current unit calls at elaboration time, directly or indirectly,
22199 some subprogram in the named unit.
22201 @item pragma Elaborate_All (unit)
22202 @findex Elaborate_All
22203 @cindex pragma Elaborate_All
22204 This is a stronger version of the Elaborate pragma. Consider the
22205 following example:
22207 @smallexample
22208 Unit A @code{with}'s unit B and calls B.Func in elab code
22209 Unit B @code{with}'s unit C, and B.Func calls C.Func
22210 @end smallexample
22212 @noindent
22213 Now if we put a pragma @code{Elaborate (B)}
22214 in unit @code{A}, this ensures that the
22215 body of @code{B} is elaborated before the call, but not the
22216 body of @code{C}, so
22217 the call to @code{C.Func} could still cause @code{Program_Error} to
22218 be raised.
22220 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22221 not only that the body of the named unit be elaborated before the
22222 unit doing the @code{with}, but also the bodies of all units that the
22223 named unit uses, following @code{with} links transitively. For example,
22224 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22225 then it requires
22226 not only that the body of @code{B} be elaborated before @code{A},
22227 but also the
22228 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22229 @end table
22231 @noindent
22232 We are now in a position to give a usage rule in Ada 95 for avoiding
22233 elaboration problems, at least if dynamic dispatching and access to
22234 subprogram values are not used. We will handle these cases separately
22235 later.
22237 The rule is simple. If a unit has elaboration code that can directly or
22238 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22239 a generic unit in a @code{with}'ed unit,
22240 then if the @code{with}'ed unit does not have
22241 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22242 a pragma @code{Elaborate_All}
22243 for the @code{with}'ed unit. By following this rule a client is
22244 assured that calls can be made without risk of an exception.
22245 If this rule is not followed, then a program may be in one of four
22246 states:
22248 @table @asis
22249 @item No order exists
22250 No order of elaboration exists which follows the rules, taking into
22251 account any @code{Elaborate}, @code{Elaborate_All},
22252 or @code{Elaborate_Body} pragmas. In
22253 this case, an Ada 95 compiler must diagnose the situation at bind
22254 time, and refuse to build an executable program.
22256 @item One or more orders exist, all incorrect
22257 One or more acceptable elaboration orders exists, and all of them
22258 generate an elaboration order problem. In this case, the binder
22259 can build an executable program, but @code{Program_Error} will be raised
22260 when the program is run.
22262 @item Several orders exist, some right, some incorrect
22263 One or more acceptable elaboration orders exists, and some of them
22264 work, and some do not. The programmer has not controlled
22265 the order of elaboration, so the binder may or may not pick one of
22266 the correct orders, and the program may or may not raise an
22267 exception when it is run. This is the worst case, because it means
22268 that the program may fail when moved to another compiler, or even
22269 another version of the same compiler.
22271 @item One or more orders exists, all correct
22272 One ore more acceptable elaboration orders exist, and all of them
22273 work. In this case the program runs successfully. This state of
22274 affairs can be guaranteed by following the rule we gave above, but
22275 may be true even if the rule is not followed.
22276 @end table
22278 @noindent
22279 Note that one additional advantage of following our Elaborate_All rule
22280 is that the program continues to stay in the ideal (all orders OK) state
22281 even if maintenance
22282 changes some bodies of some subprograms. Conversely, if a program that does
22283 not follow this rule happens to be safe at some point, this state of affairs
22284 may deteriorate silently as a result of maintenance changes.
22286 You may have noticed that the above discussion did not mention
22287 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22288 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22289 code in the body makes calls to some other unit, so it is still necessary
22290 to use @code{Elaborate_All} on such units.
22292 @node Controlling Elaboration in GNAT - Internal Calls
22293 @section Controlling Elaboration in GNAT - Internal Calls
22295 @noindent
22296 In the case of internal calls, i.e. calls within a single package, the
22297 programmer has full control over the order of elaboration, and it is up
22298 to the programmer to elaborate declarations in an appropriate order. For
22299 example writing:
22301 @smallexample @c ada
22302 @group
22303 @cartouche
22304 function One return Float;
22306 Q : Float := One;
22308 function One return Float is
22309 begin
22310      return 1.0;
22311 end One;
22312 @end cartouche
22313 @end group
22314 @end smallexample
22316 @noindent
22317 will obviously raise @code{Program_Error} at run time, because function
22318 One will be called before its body is elaborated. In this case GNAT will
22319 generate a warning that the call will raise @code{Program_Error}:
22321 @smallexample
22322 @group
22323 @cartouche
22324  1. procedure y is
22325  2.    function One return Float;
22326  3.
22327  4.    Q : Float := One;
22328                     |
22329     >>> warning: cannot call "One" before body is elaborated
22330     >>> warning: Program_Error will be raised at run time
22332  5.
22333  6.    function One return Float is
22334  7.    begin
22335  8.         return 1.0;
22336  9.    end One;
22338 11. begin
22339 12.    null;
22340 13. end;
22341 @end cartouche
22342 @end group
22343 @end smallexample
22345 @noindent
22346 Note that in this particular case, it is likely that the call is safe, because
22347 the function @code{One} does not access any global variables.
22348 Nevertheless in Ada 95, we do not want the validity of the check to depend on
22349 the contents of the body (think about the separate compilation case), so this
22350 is still wrong, as we discussed in the previous sections.
22352 The error is easily corrected by rearranging the declarations so that the
22353 body of One appears before the declaration containing the call
22354 (note that in Ada 95,
22355 declarations can appear in any order, so there is no restriction that
22356 would prevent this reordering, and if we write:
22358 @smallexample @c ada
22359 @group
22360 @cartouche
22361 function One return Float;
22363 function One return Float is
22364 begin
22365      return 1.0;
22366 end One;
22368 Q : Float := One;
22369 @end cartouche
22370 @end group
22371 @end smallexample
22373 @noindent
22374 then all is well, no warning is generated, and no
22375 @code{Program_Error} exception
22376 will be raised.
22377 Things are more complicated when a chain of subprograms is executed:
22379 @smallexample @c ada
22380 @group
22381 @cartouche
22382 function A return Integer;
22383 function B return Integer;
22384 function C return Integer;
22386 function B return Integer is begin return A; end;
22387 function C return Integer is begin return B; end;
22389 X : Integer := C;
22391 function A return Integer is begin return 1; end;
22392 @end cartouche
22393 @end group
22394 @end smallexample
22396 @noindent
22397 Now the call to @code{C}
22398 at elaboration time in the declaration of @code{X} is correct, because
22399 the body of @code{C} is already elaborated,
22400 and the call to @code{B} within the body of
22401 @code{C} is correct, but the call
22402 to @code{A} within the body of @code{B} is incorrect, because the body
22403 of @code{A} has not been elaborated, so @code{Program_Error}
22404 will be raised on the call to @code{A}.
22405 In this case GNAT will generate a
22406 warning that @code{Program_Error} may be
22407 raised at the point of the call. Let's look at the warning:
22409 @smallexample
22410 @group
22411 @cartouche
22412  1. procedure x is
22413  2.    function A return Integer;
22414  3.    function B return Integer;
22415  4.    function C return Integer;
22416  5.
22417  6.    function B return Integer is begin return A; end;
22418                                                     |
22419     >>> warning: call to "A" before body is elaborated may
22420                  raise Program_Error
22421     >>> warning: "B" called at line 7
22422     >>> warning: "C" called at line 9
22424  7.    function C return Integer is begin return B; end;
22425  8.
22426  9.    X : Integer := C;
22428 11.    function A return Integer is begin return 1; end;
22430 13. begin
22431 14.    null;
22432 15. end;
22433 @end cartouche
22434 @end group
22435 @end smallexample
22437 @noindent
22438 Note that the message here says ``may raise'', instead of the direct case,
22439 where the message says ``will be raised''. That's because whether
22440 @code{A} is
22441 actually called depends in general on run-time flow of control.
22442 For example, if the body of @code{B} said
22444 @smallexample @c ada
22445 @group
22446 @cartouche
22447 function B return Integer is
22448 begin
22449    if some-condition-depending-on-input-data then
22450       return A;
22451    else
22452       return 1;
22453    end if;
22454 end B;
22455 @end cartouche
22456 @end group
22457 @end smallexample
22459 @noindent
22460 then we could not know until run time whether the incorrect call to A would
22461 actually occur, so @code{Program_Error} might
22462 or might not be raised. It is possible for a compiler to
22463 do a better job of analyzing bodies, to
22464 determine whether or not @code{Program_Error}
22465 might be raised, but it certainly
22466 couldn't do a perfect job (that would require solving the halting problem
22467 and is provably impossible), and because this is a warning anyway, it does
22468 not seem worth the effort to do the analysis. Cases in which it
22469 would be relevant are rare.
22471 In practice, warnings of either of the forms given
22472 above will usually correspond to
22473 real errors, and should be examined carefully and eliminated.
22474 In the rare case where a warning is bogus, it can be suppressed by any of
22475 the following methods:
22477 @itemize @bullet
22478 @item
22479 Compile with the @option{-gnatws} switch set
22481 @item
22482 Suppress @code{Elaboration_Check} for the called subprogram
22484 @item
22485 Use pragma @code{Warnings_Off} to turn warnings off for the call
22486 @end itemize
22488 @noindent
22489 For the internal elaboration check case,
22490 GNAT by default generates the
22491 necessary run-time checks to ensure
22492 that @code{Program_Error} is raised if any
22493 call fails an elaboration check. Of course this can only happen if a
22494 warning has been issued as described above. The use of pragma
22495 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22496 some of these checks, meaning that it may be possible (but is not
22497 guaranteed) for a program to be able to call a subprogram whose body
22498 is not yet elaborated, without raising a @code{Program_Error} exception.
22500 @node Controlling Elaboration in GNAT - External Calls
22501 @section Controlling Elaboration in GNAT - External Calls
22503 @noindent
22504 The previous section discussed the case in which the execution of a
22505 particular thread of elaboration code occurred entirely within a
22506 single unit. This is the easy case to handle, because a programmer
22507 has direct and total control over the order of elaboration, and
22508 furthermore, checks need only be generated in cases which are rare
22509 and which the compiler can easily detect.
22510 The situation is more complex when separate compilation is taken into account.
22511 Consider the following:
22513 @smallexample @c ada
22514 @cartouche
22515 @group
22516 package Math is
22517    function Sqrt (Arg : Float) return Float;
22518 end Math;
22520 package body Math is
22521    function Sqrt (Arg : Float) return Float is
22522    begin
22523          ...
22524    end Sqrt;
22525 end Math;
22526 @end group
22527 @group
22528 with Math;
22529 package Stuff is
22530    X : Float := Math.Sqrt (0.5);
22531 end Stuff;
22533 with Stuff;
22534 procedure Main is
22535 begin
22536    ...
22537 end Main;
22538 @end group
22539 @end cartouche
22540 @end smallexample
22542 @noindent
22543 where @code{Main} is the main program. When this program is executed, the
22544 elaboration code must first be executed, and one of the jobs of the
22545 binder is to determine the order in which the units of a program are
22546 to be elaborated. In this case we have four units: the spec and body
22547 of @code{Math},
22548 the spec of @code{Stuff} and the body of @code{Main}).
22549 In what order should the four separate sections of elaboration code
22550 be executed?
22552 There are some restrictions in the order of elaboration that the binder
22553 can choose. In particular, if unit U has a @code{with}
22554 for a package @code{X}, then you
22555 are assured that the spec of @code{X}
22556 is elaborated before U , but you are
22557 not assured that the body of @code{X}
22558 is elaborated before U.
22559 This means that in the above case, the binder is allowed to choose the
22560 order:
22562 @smallexample
22563 spec of Math
22564 spec of Stuff
22565 body of Math
22566 body of Main
22567 @end smallexample
22569 @noindent
22570 but that's not good, because now the call to @code{Math.Sqrt}
22571 that happens during
22572 the elaboration of the @code{Stuff}
22573 spec happens before the body of @code{Math.Sqrt} is
22574 elaborated, and hence causes @code{Program_Error} exception to be raised.
22575 At first glance, one might say that the binder is misbehaving, because
22576 obviously you want to elaborate the body of something you @code{with}
22577 first, but
22578 that is not a general rule that can be followed in all cases. Consider
22580 @smallexample @c ada
22581 @group
22582 @cartouche
22583 package X is ...
22585 package Y is ...
22587 with X;
22588 package body Y is ...
22590 with Y;
22591 package body X is ...
22592 @end cartouche
22593 @end group
22594 @end smallexample
22596 @noindent
22597 This is a common arrangement, and, apart from the order of elaboration
22598 problems that might arise in connection with elaboration code, this works fine.
22599 A rule that says that you must first elaborate the body of anything you
22600 @code{with} cannot work in this case:
22601 the body of @code{X} @code{with}'s @code{Y},
22602 which means you would have to
22603 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
22604 which means
22605 you have to elaborate the body of @code{X} first, but ... and we have a
22606 loop that cannot be broken.
22608 It is true that the binder can in many cases guess an order of elaboration
22609 that is unlikely to cause a @code{Program_Error}
22610 exception to be raised, and it tries to do so (in the
22611 above example of @code{Math/Stuff/Spec}, the GNAT binder will
22612 by default
22613 elaborate the body of @code{Math} right after its spec, so all will be well).
22615 However, a program that blindly relies on the binder to be helpful can
22616 get into trouble, as we discussed in the previous sections, so
22617 GNAT
22618 provides a number of facilities for assisting the programmer in
22619 developing programs that are robust with respect to elaboration order.
22621 @node Default Behavior in GNAT - Ensuring Safety
22622 @section Default Behavior in GNAT - Ensuring Safety
22624 @noindent
22625 The default behavior in GNAT ensures elaboration safety. In its
22626 default mode GNAT implements the
22627 rule we previously described as the right approach. Let's restate it:
22629 @itemize
22630 @item
22631 @emph{If a unit has elaboration code that can directly or indirectly make a
22632 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
22633 in a @code{with}'ed unit, then if the @code{with}'ed unit
22634 does not have pragma @code{Pure} or
22635 @code{Preelaborate}, then the client should have an
22636 @code{Elaborate_All} for the @code{with}'ed unit.}
22637 @end itemize
22639 @noindent
22640 By following this rule a client is assured that calls and instantiations
22641 can be made without risk of an exception.
22643 In this mode GNAT traces all calls that are potentially made from
22644 elaboration code, and puts in any missing implicit @code{Elaborate_All}
22645 pragmas.
22646 The advantage of this approach is that no elaboration problems
22647 are possible if the binder can find an elaboration order that is
22648 consistent with these implicit @code{Elaborate_All} pragmas. The
22649 disadvantage of this approach is that no such order may exist.
22651 If the binder does not generate any diagnostics, then it means that it
22652 has found an elaboration order that is guaranteed to be safe. However,
22653 the binder may still be relying on implicitly generated
22654 @code{Elaborate_All} pragmas so portability to other compilers than
22655 GNAT is not guaranteed.
22657 If it is important to guarantee portability, then the compilations should
22658 use the
22659 @option{-gnatwl}
22660 (warn on elaboration problems) switch. This will cause warning messages
22661 to be generated indicating the missing @code{Elaborate_All} pragmas.
22662 Consider the following source program:
22664 @smallexample @c ada
22665 @group
22666 @cartouche
22667 with k;
22668 package j is
22669   m : integer := k.r;
22670 end;
22671 @end cartouche
22672 @end group
22673 @end smallexample
22675 @noindent
22676 where it is clear that there
22677 should be a pragma @code{Elaborate_All}
22678 for unit @code{k}. An implicit pragma will be generated, and it is
22679 likely that the binder will be able to honor it. However, if you want
22680 to port this program to some other Ada compiler than GNAT.
22681 it is safer to include the pragma explicitly in the source. If this
22682 unit is compiled with the
22683 @option{-gnatwl}
22684 switch, then the compiler outputs a warning:
22686 @smallexample
22687 @group
22688 @cartouche
22689 1. with k;
22690 2. package j is
22691 3.   m : integer := k.r;
22692                      |
22693    >>> warning: call to "r" may raise Program_Error
22694    >>> warning: missing pragma Elaborate_All for "k"
22696 4. end;
22697 @end cartouche
22698 @end group
22699 @end smallexample
22701 @noindent
22702 and these warnings can be used as a guide for supplying manually
22703 the missing pragmas. It is usually a bad idea to use this warning
22704 option during development. That's because it will warn you when
22705 you need to put in a pragma, but cannot warn you when it is time
22706 to take it out. So the use of pragma Elaborate_All may lead to
22707 unnecessary dependencies and even false circularities.
22709 This default mode is more restrictive than the Ada Reference
22710 Manual, and it is possible to construct programs which will compile
22711 using the dynamic model described there, but will run into a
22712 circularity using the safer static model we have described.
22714 Of course any Ada compiler must be able to operate in a mode
22715 consistent with the requirements of the Ada Reference Manual,
22716 and in particular must have the capability of implementing the
22717 standard dynamic model of elaboration with run-time checks.
22719 In GNAT, this standard mode can be achieved either by the use of
22720 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
22721 command, or by the use of the configuration pragma:
22723 @smallexample @c ada
22724 pragma Elaboration_Checks (RM);
22725 @end smallexample
22727 @noindent
22728 Either approach will cause the unit affected to be compiled using the
22729 standard dynamic run-time elaboration checks described in the Ada
22730 Reference Manual. The static model is generally preferable, since it
22731 is clearly safer to rely on compile and link time checks rather than
22732 run-time checks. However, in the case of legacy code, it may be
22733 difficult to meet the requirements of the static model. This
22734 issue is further discussed in
22735 @ref{What to Do If the Default Elaboration Behavior Fails}.
22737 Note that the static model provides a strict subset of the allowed
22738 behavior and programs of the Ada Reference Manual, so if you do
22739 adhere to the static model and no circularities exist,
22740 then you are assured that your program will
22741 work using the dynamic model, providing that you remove any
22742 pragma Elaborate statements from the source.
22744 @node Treatment of Pragma Elaborate
22745 @section Treatment of Pragma Elaborate
22746 @cindex Pragma Elaborate
22748 @noindent
22749 The use of @code{pragma Elaborate}
22750 should generally be avoided in Ada 95 programs.
22751 The reason for this is that there is no guarantee that transitive calls
22752 will be properly handled. Indeed at one point, this pragma was placed
22753 in Annex J (Obsolescent Features), on the grounds that it is never useful.
22755 Now that's a bit restrictive. In practice, the case in which
22756 @code{pragma Elaborate} is useful is when the caller knows that there
22757 are no transitive calls, or that the called unit contains all necessary
22758 transitive @code{pragma Elaborate} statements, and legacy code often
22759 contains such uses.
22761 Strictly speaking the static mode in GNAT should ignore such pragmas,
22762 since there is no assurance at compile time that the necessary safety
22763 conditions are met. In practice, this would cause GNAT to be incompatible
22764 with correctly written Ada 83 code that had all necessary
22765 @code{pragma Elaborate} statements in place. Consequently, we made the
22766 decision that GNAT in its default mode will believe that if it encounters
22767 a @code{pragma Elaborate} then the programmer knows what they are doing,
22768 and it will trust that no elaboration errors can occur.
22770 The result of this decision is two-fold. First to be safe using the
22771 static mode, you should remove all @code{pragma Elaborate} statements.
22772 Second, when fixing circularities in existing code, you can selectively
22773 use @code{pragma Elaborate} statements to convince the static mode of
22774 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
22775 statement.
22777 When using the static mode with @option{-gnatwl}, any use of
22778 @code{pragma Elaborate} will generate a warning about possible
22779 problems.
22781 @node Elaboration Issues for Library Tasks
22782 @section Elaboration Issues for Library Tasks
22783 @cindex Library tasks, elaboration issues
22784 @cindex Elaboration of library tasks
22786 @noindent
22787 In this section we examine special elaboration issues that arise for
22788 programs that declare library level tasks.
22790 Generally the model of execution of an Ada program is that all units are
22791 elaborated, and then execution of the program starts. However, the
22792 declaration of library tasks definitely does not fit this model. The
22793 reason for this is that library tasks start as soon as they are declared
22794 (more precisely, as soon as the statement part of the enclosing package
22795 body is reached), that is to say before elaboration
22796 of the program is complete. This means that if such a task calls a
22797 subprogram, or an entry in another task, the callee may or may not be
22798 elaborated yet, and in the standard
22799 Reference Manual model of dynamic elaboration checks, you can even
22800 get timing dependent Program_Error exceptions, since there can be
22801 a race between the elaboration code and the task code.
22803 The static model of elaboration in GNAT seeks to avoid all such
22804 dynamic behavior, by being conservative, and the conservative
22805 approach in this particular case is to assume that all the code
22806 in a task body is potentially executed at elaboration time if
22807 a task is declared at the library level.
22809 This can definitely result in unexpected circularities. Consider
22810 the following example
22812 @smallexample @c ada
22813 package Decls is
22814   task Lib_Task is
22815      entry Start;
22816   end Lib_Task;
22818   type My_Int is new Integer;
22820   function Ident (M : My_Int) return My_Int;
22821 end Decls;
22823 with Utils;
22824 package body Decls is
22825   task body Lib_Task is
22826   begin
22827      accept Start;
22828      Utils.Put_Val (2);
22829   end Lib_Task;
22831   function Ident (M : My_Int) return My_Int is
22832   begin
22833      return M;
22834   end Ident;
22835 end Decls;
22837 with Decls;
22838 package Utils is
22839   procedure Put_Val (Arg : Decls.My_Int);
22840 end Utils;
22842 with Text_IO;
22843 package body Utils is
22844   procedure Put_Val (Arg : Decls.My_Int) is
22845   begin
22846      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
22847   end Put_Val;
22848 end Utils;
22850 with Decls;
22851 procedure Main is
22852 begin
22853    Decls.Lib_Task.Start;
22854 end;
22855 @end smallexample
22857 @noindent
22858 If the above example is compiled in the default static elaboration
22859 mode, then a circularity occurs. The circularity comes from the call
22860 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
22861 this call occurs in elaboration code, we need an implicit pragma
22862 @code{Elaborate_All} for @code{Utils}. This means that not only must
22863 the spec and body of @code{Utils} be elaborated before the body
22864 of @code{Decls}, but also the spec and body of any unit that is
22865 @code{with'ed} by the body of @code{Utils} must also be elaborated before
22866 the body of @code{Decls}. This is the transitive implication of
22867 pragma @code{Elaborate_All} and it makes sense, because in general
22868 the body of @code{Put_Val} might have a call to something in a
22869 @code{with'ed} unit.
22871 In this case, the body of Utils (actually its spec) @code{with's}
22872 @code{Decls}. Unfortunately this means that the body of @code{Decls}
22873 must be elaborated before itself, in case there is a call from the
22874 body of @code{Utils}.
22876 Here is the exact chain of events we are worrying about:
22878 @enumerate
22879 @item
22880 In the body of @code{Decls} a call is made from within the body of a library
22881 task to a subprogram in the package @code{Utils}. Since this call may
22882 occur at elaboration time (given that the task is activated at elaboration
22883 time), we have to assume the worst, i.e. that the
22884 call does happen at elaboration time.
22886 @item
22887 This means that the body and spec of @code{Util} must be elaborated before
22888 the body of @code{Decls} so that this call does not cause an access before
22889 elaboration.
22891 @item
22892 Within the body of @code{Util}, specifically within the body of
22893 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
22894 by this package.
22896 @item
22897 One such @code{with}'ed package is package @code{Decls}, so there
22898 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
22899 In fact there is such a call in this example, but we would have to
22900 assume that there was such a call even if it were not there, since
22901 we are not supposed to write the body of @code{Decls} knowing what
22902 is in the body of @code{Utils}; certainly in the case of the
22903 static elaboration model, the compiler does not know what is in
22904 other bodies and must assume the worst.
22906 @item
22907 This means that the spec and body of @code{Decls} must also be
22908 elaborated before we elaborate the unit containing the call, but
22909 that unit is @code{Decls}! This means that the body of @code{Decls}
22910 must be elaborated before itself, and that's a circularity.
22911 @end enumerate
22913 @noindent
22914 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
22915 the body of @code{Decls} you will get a true Ada Reference Manual
22916 circularity that makes the program illegal.
22918 In practice, we have found that problems with the static model of
22919 elaboration in existing code often arise from library tasks, so
22920 we must address this particular situation.
22922 Note that if we compile and run the program above, using the dynamic model of
22923 elaboration (that is to say use the @option{-gnatE} switch),
22924 then it compiles, binds,
22925 links, and runs, printing the expected result of 2. Therefore in some sense
22926 the circularity here is only apparent, and we need to capture
22927 the properties of this program that  distinguish it from other library-level
22928 tasks that have real elaboration problems.
22930 We have four possible answers to this question:
22932 @itemize @bullet
22934 @item
22935 Use the dynamic model of elaboration.
22937 If we use the @option{-gnatE} switch, then as noted above, the program works.
22938 Why is this? If we examine the task body, it is apparent that the task cannot
22939 proceed past the
22940 @code{accept} statement until after elaboration has been completed, because
22941 the corresponding entry call comes from the main program, not earlier.
22942 This is why the dynamic model works here. But that's really giving
22943 up on a precise analysis, and we prefer to take this approach only if we cannot
22944 solve the
22945 problem in any other manner. So let us examine two ways to reorganize
22946 the program to avoid the potential elaboration problem.
22948 @item
22949 Split library tasks into separate packages.
22951 Write separate packages, so that library tasks are isolated from
22952 other declarations as much as possible. Let us look at a variation on
22953 the above program.
22955 @smallexample @c ada
22956 package Decls1 is
22957   task Lib_Task is
22958      entry Start;
22959   end Lib_Task;
22960 end Decls1;
22962 with Utils;
22963 package body Decls1 is
22964   task body Lib_Task is
22965   begin
22966      accept Start;
22967      Utils.Put_Val (2);
22968   end Lib_Task;
22969 end Decls1;
22971 package Decls2 is
22972   type My_Int is new Integer;
22973   function Ident (M : My_Int) return My_Int;
22974 end Decls2;
22976 with Utils;
22977 package body Decls2 is
22978   function Ident (M : My_Int) return My_Int is
22979   begin
22980      return M;
22981   end Ident;
22982 end Decls2;
22984 with Decls2;
22985 package Utils is
22986   procedure Put_Val (Arg : Decls2.My_Int);
22987 end Utils;
22989 with Text_IO;
22990 package body Utils is
22991   procedure Put_Val (Arg : Decls2.My_Int) is
22992   begin
22993      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
22994   end Put_Val;
22995 end Utils;
22997 with Decls1;
22998 procedure Main is
22999 begin
23000    Decls1.Lib_Task.Start;
23001 end;
23002 @end smallexample
23004 @noindent
23005 All we have done is to split @code{Decls} into two packages, one
23006 containing the library task, and one containing everything else. Now
23007 there is no cycle, and the program compiles, binds, links and executes
23008 using the default static model of elaboration.
23010 @item
23011 Declare separate task types.
23013 A significant part of the problem arises because of the use of the
23014 single task declaration form. This means that the elaboration of
23015 the task type, and the elaboration of the task itself (i.e. the
23016 creation of the task) happen at the same time. A good rule
23017 of style in Ada 95 is to always create explicit task types. By
23018 following the additional step of placing task objects in separate
23019 packages from the task type declaration, many elaboration problems
23020 are avoided. Here is another modified example of the example program:
23022 @smallexample @c ada
23023 package Decls is
23024   task type Lib_Task_Type is
23025      entry Start;
23026   end Lib_Task_Type;
23028   type My_Int is new Integer;
23030   function Ident (M : My_Int) return My_Int;
23031 end Decls;
23033 with Utils;
23034 package body Decls is
23035   task body Lib_Task_Type is
23036   begin
23037      accept Start;
23038      Utils.Put_Val (2);
23039   end Lib_Task_Type;
23041   function Ident (M : My_Int) return My_Int is
23042   begin
23043      return M;
23044   end Ident;
23045 end Decls;
23047 with Decls;
23048 package Utils is
23049   procedure Put_Val (Arg : Decls.My_Int);
23050 end Utils;
23052 with Text_IO;
23053 package body Utils is
23054   procedure Put_Val (Arg : Decls.My_Int) is
23055   begin
23056      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23057   end Put_Val;
23058 end Utils;
23060 with Decls;
23061 package Declst is
23062    Lib_Task : Decls.Lib_Task_Type;
23063 end Declst;
23065 with Declst;
23066 procedure Main is
23067 begin
23068    Declst.Lib_Task.Start;
23069 end;
23070 @end smallexample
23072 @noindent
23073 What we have done here is to replace the @code{task} declaration in
23074 package @code{Decls} with a @code{task type} declaration. Then we
23075 introduce a separate package @code{Declst} to contain the actual
23076 task object. This separates the elaboration issues for
23077 the @code{task type}
23078 declaration, which causes no trouble, from the elaboration issues
23079 of the task object, which is also unproblematic, since it is now independent
23080 of the elaboration of  @code{Utils}.
23081 This separation of concerns also corresponds to
23082 a generally sound engineering principle of separating declarations
23083 from instances. This version of the program also compiles, binds, links,
23084 and executes, generating the expected output.
23086 @item
23087 Use No_Entry_Calls_In_Elaboration_Code restriction.
23088 @cindex No_Entry_Calls_In_Elaboration_Code
23090 The previous two approaches described how a program can be restructured
23091 to avoid the special problems caused by library task bodies. in practice,
23092 however, such restructuring may be difficult to apply to existing legacy code,
23093 so we must consider solutions that do not require massive rewriting.
23095 Let us consider more carefully why our original sample program works
23096 under the dynamic model of elaboration. The reason is that the code
23097 in the task body blocks immediately on the @code{accept}
23098 statement. Now of course there is nothing to prohibit elaboration
23099 code from making entry calls (for example from another library level task),
23100 so we cannot tell in isolation that
23101 the task will not execute the accept statement  during elaboration.
23103 However, in practice it is very unusual to see elaboration code
23104 make any entry calls, and the pattern of tasks starting
23105 at elaboration time and then immediately blocking on @code{accept} or
23106 @code{select} statements is very common. What this means is that
23107 the compiler is being too pessimistic when it analyzes the
23108 whole package body as though it might be executed at elaboration
23109 time.
23111 If we know that the elaboration code contains no entry calls, (a very safe
23112 assumption most of the time, that could almost be made the default
23113 behavior), then we can compile all units of the program under control
23114 of the following configuration pragma:
23116 @smallexample
23117 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23118 @end smallexample
23120 @noindent
23121 This pragma can be placed in the @file{gnat.adc} file in the usual
23122 manner. If we take our original unmodified program and compile it
23123 in the presence of a @file{gnat.adc} containing the above pragma,
23124 then once again, we can compile, bind, link, and execute, obtaining
23125 the expected result. In the presence of this pragma, the compiler does
23126 not trace calls in a task body, that appear after the first @code{accept}
23127 or @code{select} statement, and therefore does not report a potential
23128 circularity in the original program.
23130 The compiler will check to the extent it can that the above
23131 restriction is not violated, but it is not always possible to do a
23132 complete check at compile time, so it is important to use this
23133 pragma only if the stated restriction is in fact met, that is to say
23134 no task receives an entry call before elaboration of all units is completed.
23136 @end itemize
23138 @node Mixing Elaboration Models
23139 @section Mixing Elaboration Models
23140 @noindent
23141 So far, we have assumed that the entire program is either compiled
23142 using the dynamic model or static model, ensuring consistency. It
23143 is possible to mix the two models, but rules have to be followed
23144 if this mixing is done to ensure that elaboration checks are not
23145 omitted.
23147 The basic rule is that @emph{a unit compiled with the static model cannot
23148 be @code{with'ed} by a unit compiled with the dynamic model}. The
23149 reason for this is that in the static model, a unit assumes that
23150 its clients guarantee to use (the equivalent of) pragma
23151 @code{Elaborate_All} so that no elaboration checks are required
23152 in inner subprograms, and this assumption is violated if the
23153 client is compiled with dynamic checks.
23155 The precise rule is as follows. A unit that is compiled with dynamic
23156 checks can only @code{with} a unit that meets at least one of the
23157 following criteria:
23159 @itemize @bullet
23161 @item
23162 The @code{with'ed} unit is itself compiled with dynamic elaboration
23163 checks (that is with the @option{-gnatE} switch.
23165 @item
23166 The @code{with'ed} unit is an internal GNAT implementation unit from
23167 the System, Interfaces, Ada, or GNAT hierarchies.
23169 @item
23170 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23172 @item
23173 The @code{with'ing} unit (that is the client) has an explicit pragma
23174 @code{Elaborate_All} for the @code{with'ed} unit.
23176 @end itemize
23178 @noindent
23179 If this rule is violated, that is if a unit with dynamic elaboration
23180 checks @code{with's} a unit that does not meet one of the above four
23181 criteria, then the binder (@code{gnatbind}) will issue a warning
23182 similar to that in the following example:
23184 @smallexample
23185 warning: "x.ads" has dynamic elaboration checks and with's
23186 warning:   "y.ads" which has static elaboration checks
23187 @end smallexample
23189 @noindent
23190 These warnings indicate that the rule has been violated, and that as a result
23191 elaboration checks may be missed in the resulting executable file.
23192 This warning may be suppressed using the @option{-ws} binder switch
23193 in the usual manner.
23195 One useful application of this mixing rule is in the case of a subsystem
23196 which does not itself @code{with} units from the remainder of the
23197 application. In this case, the entire subsystem can be compiled with
23198 dynamic checks to resolve a circularity in the subsystem, while
23199 allowing the main application that uses this subsystem to be compiled
23200 using the more reliable default static model.
23202 @node What to Do If the Default Elaboration Behavior Fails
23203 @section What to Do If the Default Elaboration Behavior Fails
23205 @noindent
23206 If the binder cannot find an acceptable order, it outputs detailed
23207 diagnostics. For example:
23208 @smallexample
23209 @group
23210 @iftex
23211 @leftskip=0cm
23212 @end iftex
23213 error: elaboration circularity detected
23214 info:   "proc (body)" must be elaborated before "pack (body)"
23215 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23216 info:     recompile "pack (body)" with -gnatwl
23217 info:                             for full details
23218 info:       "proc (body)"
23219 info:         is needed by its spec:
23220 info:       "proc (spec)"
23221 info:         which is withed by:
23222 info:       "pack (body)"
23223 info:  "pack (body)" must be elaborated before "proc (body)"
23224 info:     reason: pragma Elaborate in unit "proc (body)"
23225 @end group
23227 @end smallexample
23229 @noindent
23230 In this case we have a cycle that the binder cannot break. On the one
23231 hand, there is an explicit pragma Elaborate in @code{proc} for
23232 @code{pack}. This means that the body of @code{pack} must be elaborated
23233 before the body of @code{proc}. On the other hand, there is elaboration
23234 code in @code{pack} that calls a subprogram in @code{proc}. This means
23235 that for maximum safety, there should really be a pragma
23236 Elaborate_All in @code{pack} for @code{proc} which would require that
23237 the body of @code{proc} be elaborated before the body of
23238 @code{pack}. Clearly both requirements cannot be satisfied.
23239 Faced with a circularity of this kind, you have three different options.
23241 @table @asis
23242 @item Fix the program
23243 The most desirable option from the point of view of long-term maintenance
23244 is to rearrange the program so that the elaboration problems are avoided.
23245 One useful technique is to place the elaboration code into separate
23246 child packages. Another is to move some of the initialization code to
23247 explicitly called subprograms, where the program controls the order
23248 of initialization explicitly. Although this is the most desirable option,
23249 it may be impractical and involve too much modification, especially in
23250 the case of complex legacy code.
23252 @item Perform dynamic checks
23253 If the compilations are done using the
23254 @option{-gnatE}
23255 (dynamic elaboration check) switch, then GNAT behaves in
23256 a quite different manner. Dynamic checks are generated for all calls
23257 that could possibly result in raising an exception. With this switch,
23258 the compiler does not generate implicit @code{Elaborate_All} pragmas.
23259 The behavior then is exactly as specified in the Ada 95 Reference Manual.
23260 The binder will generate an executable program that may or may not
23261 raise @code{Program_Error}, and then it is the programmer's job to ensure
23262 that it does not raise an exception. Note that it is important to
23263 compile all units with the switch, it cannot be used selectively.
23265 @item Suppress checks
23266 The drawback of dynamic checks is that they generate a
23267 significant overhead at run time, both in space and time. If you
23268 are absolutely sure that your program cannot raise any elaboration
23269 exceptions, and you still want to use the dynamic elaboration model,
23270 then you can use the configuration pragma
23271 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23272 example this pragma could be placed in the @file{gnat.adc} file.
23274 @item Suppress checks selectively
23275 When you know that certain calls in elaboration code cannot possibly
23276 lead to an elaboration error, and the binder nevertheless generates warnings
23277 on those calls and inserts Elaborate_All pragmas that lead to elaboration
23278 circularities, it is possible to remove those warnings locally and obtain
23279 a program that will bind. Clearly this can be unsafe, and it is the
23280 responsibility of the programmer to make sure that the resulting program has
23281 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
23282 be used with different granularity to suppress warnings and break
23283 elaboration circularities:
23285 @itemize @bullet
23286 @item
23287 Place the pragma that names the called subprogram in the declarative part
23288 that contains the call.
23290 @item
23291 Place the pragma in the declarative part, without naming an entity. This
23292 disables warnings on all calls in the corresponding  declarative region.
23294 @item
23295 Place the pragma in the package spec that declares the called subprogram,
23296 and name the subprogram. This disables warnings on all elaboration calls to
23297 that subprogram.
23299 @item
23300 Place the pragma in the package spec that declares the called subprogram,
23301 without naming any entity. This disables warnings on all elaboration calls to
23302 all subprograms declared in this spec.
23304 @item Use Pragma Elaborate
23305 As previously described in section @xref{Treatment of Pragma Elaborate},
23306 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23307 that no elaboration checks are required on calls to the designated unit.
23308 There may be cases in which the caller knows that no transitive calls
23309 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23310 case where @code{pragma Elaborate_All} would cause a circularity.
23311 @end itemize
23313 @noindent
23314 These five cases are listed in order of decreasing safety, and therefore
23315 require increasing programmer care in their application. Consider the
23316 following program:
23318 @smallexample @c adanocomment
23319 package Pack1 is
23320   function F1 return Integer;
23321   X1 : Integer;
23322 end Pack1;
23324 package Pack2 is
23325   function F2 return Integer;
23326   function Pure (x : integer) return integer;
23327   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23328   --  pragma Suppress (Elaboration_Check);              -- (4)
23329 end Pack2;
23331 with Pack2;
23332 package body Pack1 is
23333   function F1 return Integer is
23334   begin
23335     return 100;
23336   end F1;
23337   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23338 begin
23339   declare
23340     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23341     --  pragma Suppress(Elaboration_Check);             -- (2)
23342   begin
23343     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23344   end;
23345 end Pack1;
23347 with Pack1;
23348 package body Pack2 is
23349   function F2 return Integer is
23350   begin
23351      return Pack1.F1;
23352   end F2;
23353   function Pure (x : integer) return integer is
23354   begin
23355      return x ** 3 - 3 * x;
23356   end;
23357 end Pack2;
23359 with Pack1, Ada.Text_IO;
23360 procedure Proc3 is
23361 begin
23362   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23363 end Proc3;
23364 @end smallexample
23365 In the absence of any pragmas, an attempt to bind this program produces
23366 the following diagnostics:
23367 @smallexample
23368 @group
23369 @iftex
23370 @leftskip=.5cm
23371 @end iftex
23372 error: elaboration circularity detected
23373 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23374 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23375 info:       recompile "pack1 (body)" with -gnatwl for full details
23376 info:          "pack1 (body)"
23377 info:             must be elaborated along with its spec:
23378 info:          "pack1 (spec)"
23379 info:             which is withed by:
23380 info:          "pack2 (body)"
23381 info:             which must be elaborated along with its spec:
23382 info:          "pack2 (spec)"
23383 info:             which is withed by:
23384 info:          "pack1 (body)"
23385 @end group
23386 @end smallexample
23387 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23388 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23389 F2 is safe, even though F2 calls F1, because the call appears after the
23390 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23391 remove the warning on the call. It is also possible to use pragma (2)
23392 because there are no other potentially unsafe calls in the block.
23394 @noindent
23395 The call to @code{Pure} is safe because this function does not depend on the
23396 state of @code{Pack2}. Therefore any call to this function is safe, and it
23397 is correct to place pragma (3) in the corresponding package spec.
23399 @noindent
23400 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23401 warnings on all calls to functions declared therein. Note that this is not
23402 necessarily safe, and requires more detailed examination of the subprogram
23403 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23404 be already elaborated.
23405 @end table
23407 @noindent
23408 It is hard to generalize on which of these four approaches should be
23409 taken. Obviously if it is possible to fix the program so that the default
23410 treatment works, this is preferable, but this may not always be practical.
23411 It is certainly simple enough to use
23412 @option{-gnatE}
23413 but the danger in this case is that, even if the GNAT binder
23414 finds a correct elaboration order, it may not always do so,
23415 and certainly a binder from another Ada compiler might not. A
23416 combination of testing and analysis (for which the warnings generated
23417 with the
23418 @option{-gnatwl}
23419 switch can be useful) must be used to ensure that the program is free
23420 of errors. One switch that is useful in this testing is the
23421 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23422 switch for
23423 @code{gnatbind}.
23424 Normally the binder tries to find an order that has the best chance of
23425 of avoiding elaboration problems. With this switch, the binder
23426 plays a devil's advocate role, and tries to choose the order that
23427 has the best chance of failing. If your program works even with this
23428 switch, then it has a better chance of being error free, but this is still
23429 not a guarantee.
23431 For an example of this approach in action, consider the C-tests (executable
23432 tests) from the ACVC suite. If these are compiled and run with the default
23433 treatment, then all but one of them succeed without generating any error
23434 diagnostics from the binder. However, there is one test that fails, and
23435 this is not surprising, because the whole point of this test is to ensure
23436 that the compiler can handle cases where it is impossible to determine
23437 a correct order statically, and it checks that an exception is indeed
23438 raised at run time.
23440 This one test must be compiled and run using the
23441 @option{-gnatE}
23442 switch, and then it passes. Alternatively, the entire suite can
23443 be run using this switch. It is never wrong to run with the dynamic
23444 elaboration switch if your code is correct, and we assume that the
23445 C-tests are indeed correct (it is less efficient, but efficiency is
23446 not a factor in running the ACVC tests.)
23448 @node Elaboration for Access-to-Subprogram Values
23449 @section Elaboration for Access-to-Subprogram Values
23450 @cindex Access-to-subprogram
23452 @noindent
23453 The introduction of access-to-subprogram types in Ada 95 complicates
23454 the handling of elaboration. The trouble is that it becomes
23455 impossible to tell at compile time which procedure
23456 is being called. This means that it is not possible for the binder
23457 to analyze the elaboration requirements in this case.
23459 If at the point at which the access value is created
23460 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23461 the body of the subprogram is
23462 known to have been elaborated, then the access value is safe, and its use
23463 does not require a check. This may be achieved by appropriate arrangement
23464 of the order of declarations if the subprogram is in the current unit,
23465 or, if the subprogram is in another unit, by using pragma
23466 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23467 on the referenced unit.
23469 If the referenced body is not known to have been elaborated at the point
23470 the access value is created, then any use of the access value must do a
23471 dynamic check, and this dynamic check will fail and raise a
23472 @code{Program_Error} exception if the body has not been elaborated yet.
23473 GNAT will generate the necessary checks, and in addition, if the
23474 @option{-gnatwl}
23475 switch is set, will generate warnings that such checks are required.
23477 The use of dynamic dispatching for tagged types similarly generates
23478 a requirement for dynamic checks, and premature calls to any primitive
23479 operation of a tagged type before the body of the operation has been
23480 elaborated, will result in the raising of @code{Program_Error}.
23482 @node Summary of Procedures for Elaboration Control
23483 @section Summary of Procedures for Elaboration Control
23484 @cindex Elaboration control
23486 @noindent
23487 First, compile your program with the default options, using none of
23488 the special elaboration control switches. If the binder successfully
23489 binds your program, then you can be confident that, apart from issues
23490 raised by the use of access-to-subprogram types and dynamic dispatching,
23491 the program is free of elaboration errors. If it is important that the
23492 program be portable, then use the
23493 @option{-gnatwl}
23494 switch to generate warnings about missing @code{Elaborate_All}
23495 pragmas, and supply the missing pragmas.
23497 If the program fails to bind using the default static elaboration
23498 handling, then you can fix the program to eliminate the binder
23499 message, or recompile the entire program with the
23500 @option{-gnatE} switch to generate dynamic elaboration checks,
23501 and, if you are sure there really are no elaboration problems,
23502 use a global pragma @code{Suppress (Elaboration_Check)}.
23504 @node Other Elaboration Order Considerations
23505 @section Other Elaboration Order Considerations
23506 @noindent
23507 This section has been entirely concerned with the issue of finding a valid
23508 elaboration order, as defined by the Ada Reference Manual. In a case
23509 where several elaboration orders are valid, the task is to find one
23510 of the possible valid elaboration orders (and the static model in GNAT
23511 will ensure that this is achieved).
23513 The purpose of the elaboration rules in the Ada Reference Manual is to
23514 make sure that no entity is accessed before it has been elaborated. For
23515 a subprogram, this means that the spec and body must have been elaborated
23516 before the subprogram is called. For an object, this means that the object
23517 must have been elaborated before its value is read or written. A violation
23518 of either of these two requirements is an access before elaboration order,
23519 and this section has been all about avoiding such errors.
23521 In the case where more than one order of elaboration is possible, in the
23522 sense that access before elaboration errors are avoided, then any one of
23523 the orders is ``correct'' in the sense that it meets the requirements of
23524 the Ada Reference Manual, and no such error occurs.
23526 However, it may be the case for a given program, that there are
23527 constraints on the order of elaboration that come not from consideration
23528 of avoiding elaboration errors, but rather from extra-lingual logic
23529 requirements. Consider this example:
23531 @smallexample @c ada
23532 with Init_Constants;
23533 package Constants is
23534    X : Integer := 0;
23535    Y : Integer := 0;
23536 end Constants;
23538 package Init_Constants is
23539    procedure P; -- require a body
23540 end Init_Constants;
23542 with Constants;
23543 package body Init_Constants is
23544    procedure P is begin null; end;
23545 begin
23546    Constants.X := 3;
23547    Constants.Y := 4;
23548 end Init_Constants;
23550 with Constants;
23551 package Calc is
23552    Z : Integer := Constants.X + Constants.Y;
23553 end Calc;
23555 with Calc;
23556 with Text_IO; use Text_IO;
23557 procedure Main is
23558 begin
23559    Put_Line (Calc.Z'Img);
23560 end Main;
23561 @end smallexample
23563 @noindent
23564 In this example, there is more than one valid order of elaboration. For
23565 example both the following are correct orders:
23567 @smallexample
23568 Init_Constants spec
23569 Constants spec
23570 Calc spec
23571 Init_Constants body
23572 Main body
23574   and
23576 Init_Constants spec
23577 Init_Constants body
23578 Constants spec
23579 Calc spec
23580 Main body
23581 @end smallexample
23583 @noindent
23584 There is no language rule to prefer one or the other, both are correct
23585 from an order of elaboration point of view. But the programmatic effects
23586 of the two orders are very different. In the first, the elaboration routine
23587 of @code{Calc} initializes @code{Z} to zero, and then the main program
23588 runs with this value of zero. But in the second order, the elaboration
23589 routine of @code{Calc} runs after the body of Init_Constants has set
23590 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
23591 runs.
23593 One could perhaps by applying pretty clever non-artificial intelligence
23594 to the situation guess that it is more likely that the second order of
23595 elaboration is the one desired, but there is no formal linguistic reason
23596 to prefer one over the other. In fact in this particular case, GNAT will
23597 prefer the second order, because of the rule that bodies are elaborated
23598 as soon as possible, but it's just luck that this is what was wanted
23599 (if indeed the second order was preferred).
23601 If the program cares about the order of elaboration routines in a case like
23602 this, it is important to specify the order required. In this particular
23603 case, that could have been achieved by adding to the spec of Calc:
23605 @smallexample @c ada
23606 pragma Elaborate_All (Constants);
23607 @end smallexample
23609 @noindent
23610 which requires that the body (if any) and spec of @code{Constants},
23611 as well as the body and spec of any unit @code{with}'ed by
23612 @code{Constants} be elaborated before @code{Calc} is elaborated.
23614 Clearly no automatic method can always guess which alternative you require,
23615 and if you are working with legacy code that had constraints of this kind
23616 which were not properly specified by adding @code{Elaborate} or
23617 @code{Elaborate_All} pragmas, then indeed it is possible that two different
23618 compilers can choose different orders.
23620 The @code{gnatbind}
23621 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
23622 out problems. This switch causes bodies to be elaborated as late as possible
23623 instead of as early as possible. In the example above, it would have forced
23624 the choice of the first elaboration order. If you get different results
23625 when using this switch, and particularly if one set of results is right,
23626 and one is wrong as far as you are concerned, it shows that you have some
23627 missing @code{Elaborate} pragmas. For the example above, we have the
23628 following output:
23630 @smallexample
23631 gnatmake -f -q main
23632 main
23634 gnatmake -f -q main -bargs -p
23635 main
23637 @end smallexample
23639 @noindent
23640 It is of course quite unlikely that both these results are correct, so
23641 it is up to you in a case like this to investigate the source of the
23642 difference, by looking at the two elaboration orders that are chosen,
23643 and figuring out which is correct, and then adding the necessary
23644 @code{Elaborate_All} pragmas to ensure the desired order.
23647 @node Inline Assembler
23648 @appendix Inline Assembler
23650 @noindent
23651 If you need to write low-level software that interacts directly
23652 with the hardware, Ada provides two ways to incorporate assembly
23653 language code into your program.  First, you can import and invoke
23654 external routines written in assembly language, an Ada feature fully
23655 supported by GNAT.  However, for small sections of code it may be simpler
23656 or more efficient to include assembly language statements directly
23657 in your Ada source program, using the facilities of the implementation-defined
23658 package @code{System.Machine_Code}, which incorporates the gcc
23659 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
23660 including the following:
23662 @itemize @bullet
23663 @item No need to use non-Ada tools
23664 @item Consistent interface over different targets
23665 @item Automatic usage of the proper calling conventions
23666 @item Access to Ada constants and variables
23667 @item Definition of intrinsic routines
23668 @item Possibility of inlining a subprogram comprising assembler code
23669 @item Code optimizer can take Inline Assembler code into account
23670 @end itemize
23672 This chapter presents a series of examples to show you how to use
23673 the Inline Assembler.  Although it focuses on the Intel x86,
23674 the general approach applies also to other processors.
23675 It is assumed that you are familiar with Ada
23676 and with assembly language programming.
23678 @menu
23679 * Basic Assembler Syntax::
23680 * A Simple Example of Inline Assembler::
23681 * Output Variables in Inline Assembler::
23682 * Input Variables in Inline Assembler::
23683 * Inlining Inline Assembler Code::
23684 * Other Asm Functionality::
23685 * A Complete Example::
23686 @end menu
23688 @c ---------------------------------------------------------------------------
23689 @node Basic Assembler Syntax
23690 @section Basic Assembler Syntax
23692 @noindent
23693 The assembler used by GNAT and gcc is based not on the Intel assembly
23694 language, but rather on a language that descends from the AT&T Unix
23695 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
23696 The following table summarizes the main features of @emph{as} syntax
23697 and points out the differences from the Intel conventions.
23698 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
23699 pre-processor) documentation for further information.
23701 @table @asis
23702 @item Register names
23703 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
23705 Intel: No extra punctuation; for example @code{eax}
23707 @item Immediate operand
23708 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
23710 Intel: No extra punctuation; for example @code{4}
23712 @item Address
23713 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
23715 Intel: No extra punctuation; for example @code{loc}
23717 @item Memory contents
23718 gcc / @emph{as}: No extra punctuation; for example @code{loc}
23720 Intel: Square brackets; for example @code{[loc]}
23722 @item Register contents
23723 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
23725 Intel: Square brackets; for example @code{[eax]}
23727 @item Hexadecimal numbers
23728 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
23730 Intel: Trailing ``h''; for example @code{A0h}
23732 @item Operand size
23733 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
23734 a 16-bit word
23736 Intel: Implicit, deduced by assembler; for example @code{mov}
23738 @item Instruction repetition
23739 gcc / @emph{as}: Split into two lines; for example
23741 @code{rep}
23743 @code{stosl}
23745 Intel: Keep on one line; for example @code{rep stosl}
23747 @item Order of operands
23748 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
23750 Intel: Destination first; for example @code{mov eax, 4}
23751 @end table
23753 @c ---------------------------------------------------------------------------
23754 @node A Simple Example of Inline Assembler
23755 @section A Simple Example of Inline Assembler
23757 @noindent
23758 The following example will generate a single assembly language statement,
23759 @code{nop}, which does nothing.  Despite its lack of run-time effect,
23760 the example will be useful in illustrating the basics of
23761 the Inline Assembler facility.
23763 @smallexample @c ada
23764 @group
23765 with System.Machine_Code; use System.Machine_Code;
23766 procedure Nothing is
23767 begin
23768    Asm ("nop");
23769 end Nothing;
23770 @end group
23771 @end smallexample
23773 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
23774 here it takes one parameter, a @emph{template string} that must be a static
23775 expression and that will form the generated instruction.
23776 @code{Asm} may be regarded as a compile-time procedure that parses
23777 the template string and additional parameters (none here),
23778 from which it generates a sequence of assembly language instructions.
23780 The examples in this chapter will illustrate several of the forms
23781 for invoking @code{Asm}; a complete specification of the syntax
23782 is found in the @cite{GNAT Reference Manual}.
23784 Under the standard GNAT conventions, the @code{Nothing} procedure
23785 should be in a file named @file{nothing.adb}.
23786 You can build the executable in the usual way:
23787 @smallexample
23788 gnatmake nothing
23789 @end smallexample
23790 However, the interesting aspect of this example is not its run-time behavior
23791 but rather the generated assembly code.
23792 To see this output, invoke the compiler as follows:
23793 @smallexample
23794    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
23795 @end smallexample
23796 where the options are:
23798 @table @code
23799 @item -c
23800 compile only (no bind or link)
23801 @item -S
23802 generate assembler listing
23803 @item -fomit-frame-pointer
23804 do not set up separate stack frames
23805 @item -gnatp
23806 do not add runtime checks
23807 @end table
23809 This gives a human-readable assembler version of the code. The resulting
23810 file will have the same name as the Ada source file, but with a @code{.s}
23811 extension. In our example, the file @file{nothing.s} has the following
23812 contents:
23814 @smallexample
23815 @group
23816 .file "nothing.adb"
23817 gcc2_compiled.:
23818 ___gnu_compiled_ada:
23819 .text
23820    .align 4
23821 .globl __ada_nothing
23822 __ada_nothing:
23823 #APP
23824    nop
23825 #NO_APP
23826    jmp L1
23827    .align 2,0x90
23829    ret
23830 @end group
23831 @end smallexample
23833 The assembly code you included is clearly indicated by
23834 the compiler, between the @code{#APP} and @code{#NO_APP}
23835 delimiters. The character before the 'APP' and 'NOAPP'
23836 can differ on different targets. For example, GNU/Linux uses '#APP' while
23837 on NT you will see '/APP'.
23839 If you make a mistake in your assembler code (such as using the
23840 wrong size modifier, or using a wrong operand for the instruction) GNAT
23841 will report this error in a temporary file, which will be deleted when
23842 the compilation is finished.  Generating an assembler file will help
23843 in such cases, since you can assemble this file separately using the
23844 @emph{as} assembler that comes with gcc.
23846 Assembling the file using the command
23848 @smallexample
23849 as @file{nothing.s}
23850 @end smallexample
23851 @noindent
23852 will give you error messages whose lines correspond to the assembler
23853 input file, so you can easily find and correct any mistakes you made.
23854 If there are no errors, @emph{as} will generate an object file
23855 @file{nothing.out}.
23857 @c ---------------------------------------------------------------------------
23858 @node Output Variables in Inline Assembler
23859 @section Output Variables in Inline Assembler
23861 @noindent
23862 The examples in this section, showing how to access the processor flags,
23863 illustrate how to specify the destination operands for assembly language
23864 statements.
23866 @smallexample @c ada
23867 @group
23868 with Interfaces; use Interfaces;
23869 with Ada.Text_IO; use Ada.Text_IO;
23870 with System.Machine_Code; use System.Machine_Code;
23871 procedure Get_Flags is
23872    Flags : Unsigned_32;
23873    use ASCII;
23874 begin
23875    Asm ("pushfl"          & LF & HT & -- push flags on stack
23876         "popl %%eax"      & LF & HT & -- load eax with flags
23877         "movl %%eax, %0",             -- store flags in variable
23878         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23879    Put_Line ("Flags register:" & Flags'Img);
23880 end Get_Flags;
23881 @end group
23882 @end smallexample
23884 In order to have a nicely aligned assembly listing, we have separated
23885 multiple assembler statements in the Asm template string with linefeed
23886 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
23887 The resulting section of the assembly output file is:
23889 @smallexample
23890 @group
23891 #APP
23892    pushfl
23893    popl %eax
23894    movl %eax, -40(%ebp)
23895 #NO_APP
23896 @end group
23897 @end smallexample
23899 It would have been legal to write the Asm invocation as:
23901 @smallexample
23902 Asm ("pushfl popl %%eax movl %%eax, %0")
23903 @end smallexample
23905 but in the generated assembler file, this would come out as:
23907 @smallexample
23908 #APP
23909    pushfl popl %eax movl %eax, -40(%ebp)
23910 #NO_APP
23911 @end smallexample
23913 which is not so convenient for the human reader.
23915 We use Ada comments
23916 at the end of each line to explain what the assembler instructions
23917 actually do.  This is a useful convention.
23919 When writing Inline Assembler instructions, you need to precede each register
23920 and variable name with a percent sign.  Since the assembler already requires
23921 a percent sign at the beginning of a register name, you need two consecutive
23922 percent signs for such names in the Asm template string, thus @code{%%eax}.
23923 In the generated assembly code, one of the percent signs will be stripped off.
23925 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
23926 variables: operands you later define using @code{Input} or @code{Output}
23927 parameters to @code{Asm}.
23928 An output variable is illustrated in
23929 the third statement in the Asm template string:
23930 @smallexample
23931 movl %%eax, %0
23932 @end smallexample
23933 The intent is to store the contents of the eax register in a variable that can
23934 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
23935 necessarily work, since the compiler might optimize by using a register
23936 to hold Flags, and the expansion of the @code{movl} instruction would not be
23937 aware of this optimization.  The solution is not to store the result directly
23938 but rather to advise the compiler to choose the correct operand form;
23939 that is the purpose of the @code{%0} output variable.
23941 Information about the output variable is supplied in the @code{Outputs}
23942 parameter to @code{Asm}:
23943 @smallexample
23944 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23945 @end smallexample
23947 The output is defined by the @code{Asm_Output} attribute of the target type;
23948 the general format is
23949 @smallexample
23950 Type'Asm_Output (constraint_string, variable_name)
23951 @end smallexample
23953 The constraint string directs the compiler how
23954 to store/access the associated variable.  In the example
23955 @smallexample
23956 Unsigned_32'Asm_Output ("=m", Flags);
23957 @end smallexample
23958 the @code{"m"} (memory) constraint tells the compiler that the variable
23959 @code{Flags} should be stored in a memory variable, thus preventing
23960 the optimizer from keeping it in a register.  In contrast,
23961 @smallexample
23962 Unsigned_32'Asm_Output ("=r", Flags);
23963 @end smallexample
23964 uses the @code{"r"} (register) constraint, telling the compiler to
23965 store the variable in a register.
23967 If the constraint is preceded by the equal character (@strong{=}), it tells
23968 the compiler that the variable will be used to store data into it.
23970 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
23971 allowing the optimizer to choose whatever it deems best.
23973 There are a fairly large number of constraints, but the ones that are
23974 most useful (for the Intel x86 processor) are the following:
23976 @table @code
23977 @item =
23978 output constraint
23979 @item g
23980 global (i.e. can be stored anywhere)
23981 @item m
23982 in memory
23983 @item I
23984 a constant
23985 @item a
23986 use eax
23987 @item b
23988 use ebx
23989 @item c
23990 use ecx
23991 @item d
23992 use edx
23993 @item S
23994 use esi
23995 @item D
23996 use edi
23997 @item r
23998 use one of eax, ebx, ecx or edx
23999 @item q
24000 use one of eax, ebx, ecx, edx, esi or edi
24001 @end table
24003 The full set of constraints is described in the gcc and @emph{as}
24004 documentation; note that it is possible to combine certain constraints
24005 in one constraint string.
24007 You specify the association of an output variable with an assembler operand
24008 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24009 integer.  Thus in
24010 @smallexample @c ada
24011 @group
24012 Asm ("pushfl"          & LF & HT & -- push flags on stack
24013      "popl %%eax"      & LF & HT & -- load eax with flags
24014      "movl %%eax, %0",             -- store flags in variable
24015      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24016 @end group
24017 @end smallexample
24018 @noindent
24019 @code{%0} will be replaced in the expanded code by the appropriate operand,
24020 whatever
24021 the compiler decided for the @code{Flags} variable.
24023 In general, you may have any number of output variables:
24024 @itemize @bullet
24025 @item
24026 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24027 @item
24028 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24029 of @code{Asm_Output} attributes
24030 @end itemize
24032 For example:
24033 @smallexample @c ada
24034 @group
24035 Asm ("movl %%eax, %0" & LF & HT &
24036      "movl %%ebx, %1" & LF & HT &
24037      "movl %%ecx, %2",
24038      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24039                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24040                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24041 @end group
24042 @end smallexample
24043 @noindent
24044 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24045 in the Ada program.
24047 As a variation on the @code{Get_Flags} example, we can use the constraints
24048 string to direct the compiler to store the eax register into the @code{Flags}
24049 variable, instead of including the store instruction explicitly in the
24050 @code{Asm} template string:
24052 @smallexample @c ada
24053 @group
24054 with Interfaces; use Interfaces;
24055 with Ada.Text_IO; use Ada.Text_IO;
24056 with System.Machine_Code; use System.Machine_Code;
24057 procedure Get_Flags_2 is
24058    Flags : Unsigned_32;
24059    use ASCII;
24060 begin
24061    Asm ("pushfl"      & LF & HT & -- push flags on stack
24062         "popl %%eax",             -- save flags in eax
24063         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24064    Put_Line ("Flags register:" & Flags'Img);
24065 end Get_Flags_2;
24066 @end group
24067 @end smallexample
24069 @noindent
24070 The @code{"a"} constraint tells the compiler that the @code{Flags}
24071 variable will come from the eax register. Here is the resulting code:
24073 @smallexample
24074 @group
24075 #APP
24076    pushfl
24077    popl %eax
24078 #NO_APP
24079    movl %eax,-40(%ebp)
24080 @end group
24081 @end smallexample
24083 @noindent
24084 The compiler generated the store of eax into Flags after
24085 expanding the assembler code.
24087 Actually, there was no need to pop the flags into the eax register;
24088 more simply, we could just pop the flags directly into the program variable:
24090 @smallexample @c ada
24091 @group
24092 with Interfaces; use Interfaces;
24093 with Ada.Text_IO; use Ada.Text_IO;
24094 with System.Machine_Code; use System.Machine_Code;
24095 procedure Get_Flags_3 is
24096    Flags : Unsigned_32;
24097    use ASCII;
24098 begin
24099    Asm ("pushfl"  & LF & HT & -- push flags on stack
24100         "pop %0",             -- save flags in Flags
24101         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24102    Put_Line ("Flags register:" & Flags'Img);
24103 end Get_Flags_3;
24104 @end group
24105 @end smallexample
24107 @c ---------------------------------------------------------------------------
24108 @node Input Variables in Inline Assembler
24109 @section Input Variables in Inline Assembler
24111 @noindent
24112 The example in this section illustrates how to specify the source operands
24113 for assembly language statements.
24114 The program simply increments its input value by 1:
24116 @smallexample @c ada
24117 @group
24118 with Interfaces; use Interfaces;
24119 with Ada.Text_IO; use Ada.Text_IO;
24120 with System.Machine_Code; use System.Machine_Code;
24121 procedure Increment is
24123    function Incr (Value : Unsigned_32) return Unsigned_32 is
24124       Result : Unsigned_32;
24125    begin
24126       Asm ("incl %0",
24127            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24128            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24129       return Result;
24130    end Incr;
24132    Value : Unsigned_32;
24134 begin
24135    Value := 5;
24136    Put_Line ("Value before is" & Value'Img);
24137    Value := Incr (Value);
24138    Put_Line ("Value after is" & Value'Img);
24139 end Increment;
24140 @end group
24141 @end smallexample
24143 The @code{Outputs} parameter to @code{Asm} specifies
24144 that the result will be in the eax register and that it is to be stored
24145 in the @code{Result} variable.
24147 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
24148 but with an @code{Asm_Input} attribute.
24149 The @code{"="} constraint, indicating an output value, is not present.
24151 You can have multiple input variables, in the same way that you can have more
24152 than one output variable.
24154 The parameter count (%0, %1) etc, now starts at the first input
24155 statement, and continues with the output statements.
24156 When both parameters use the same variable, the
24157 compiler will treat them as the same %n operand, which is the case here.
24159 Just as the @code{Outputs} parameter causes the register to be stored into the
24160 target variable after execution of the assembler statements, so does the
24161 @code{Inputs} parameter cause its variable to be loaded into the register
24162 before execution of the assembler statements.
24164 Thus the effect of the @code{Asm} invocation is:
24165 @enumerate
24166 @item load the 32-bit value of @code{Value} into eax
24167 @item execute the @code{incl %eax} instruction
24168 @item store the contents of eax into the @code{Result} variable
24169 @end enumerate
24171 The resulting assembler file (with @option{-O2} optimization) contains:
24172 @smallexample
24173 @group
24174 _increment__incr.1:
24175    subl $4,%esp
24176    movl 8(%esp),%eax
24177 #APP
24178    incl %eax
24179 #NO_APP
24180    movl %eax,%edx
24181    movl %ecx,(%esp)
24182    addl $4,%esp
24183    ret
24184 @end group
24185 @end smallexample
24187 @c ---------------------------------------------------------------------------
24188 @node Inlining Inline Assembler Code
24189 @section Inlining Inline Assembler Code
24191 @noindent
24192 For a short subprogram such as the @code{Incr} function in the previous
24193 section, the overhead of the call and return (creating / deleting the stack
24194 frame) can be significant, compared to the amount of code in the subprogram
24195 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
24196 which directs the compiler to expand invocations of the subprogram at the
24197 point(s) of call, instead of setting up a stack frame for out-of-line calls.
24198 Here is the resulting program:
24200 @smallexample @c ada
24201 @group
24202 with Interfaces; use Interfaces;
24203 with Ada.Text_IO; use Ada.Text_IO;
24204 with System.Machine_Code; use System.Machine_Code;
24205 procedure Increment_2 is
24207    function Incr (Value : Unsigned_32) return Unsigned_32 is
24208       Result : Unsigned_32;
24209    begin
24210       Asm ("incl %0",
24211            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24212            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24213       return Result;
24214    end Incr;
24215    pragma Inline (Increment);
24217    Value : Unsigned_32;
24219 begin
24220    Value := 5;
24221    Put_Line ("Value before is" & Value'Img);
24222    Value := Increment (Value);
24223    Put_Line ("Value after is" & Value'Img);
24224 end Increment_2;
24225 @end group
24226 @end smallexample
24228 Compile the program with both optimization (@option{-O2}) and inlining
24229 enabled (@option{-gnatpn} instead of @option{-gnatp}).
24231 The @code{Incr} function is still compiled as usual, but at the
24232 point in @code{Increment} where our function used to be called:
24234 @smallexample
24235 @group
24236 pushl %edi
24237 call _increment__incr.1
24238 @end group
24239 @end smallexample
24241 @noindent
24242 the code for the function body directly appears:
24244 @smallexample
24245 @group
24246 movl %esi,%eax
24247 #APP
24248    incl %eax
24249 #NO_APP
24250    movl %eax,%edx
24251 @end group
24252 @end smallexample
24254 @noindent
24255 thus saving the overhead of stack frame setup and an out-of-line call.
24257 @c ---------------------------------------------------------------------------
24258 @node Other Asm Functionality
24259 @section Other @code{Asm} Functionality
24261 @noindent
24262 This section describes two important parameters to the @code{Asm}
24263 procedure: @code{Clobber}, which identifies register usage;
24264 and @code{Volatile}, which inhibits unwanted optimizations.
24266 @menu
24267 * The Clobber Parameter::
24268 * The Volatile Parameter::
24269 @end menu
24271 @c ---------------------------------------------------------------------------
24272 @node The Clobber Parameter
24273 @subsection The @code{Clobber} Parameter
24275 @noindent
24276 One of the dangers of intermixing assembly language and a compiled language
24277 such as Ada is that the compiler needs to be aware of which registers are
24278 being used by the assembly code.  In some cases, such as the earlier examples,
24279 the constraint string is sufficient to indicate register usage (e.g.,
24280 @code{"a"} for
24281 the eax register).  But more generally, the compiler needs an explicit
24282 identification of the registers that are used by the Inline Assembly
24283 statements.
24285 Using a register that the compiler doesn't know about
24286 could be a side effect of an instruction (like @code{mull}
24287 storing its result in both eax and edx).
24288 It can also arise from explicit register usage in your
24289 assembly code; for example:
24290 @smallexample
24291 @group
24292 Asm ("movl %0, %%ebx" & LF & HT &
24293      "movl %%ebx, %1",
24294      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24295      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
24296 @end group
24297 @end smallexample
24298 @noindent
24299 where the compiler (since it does not analyze the @code{Asm} template string)
24300 does not know you are using the ebx register.
24302 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
24303 to identify the registers that will be used by your assembly code:
24305 @smallexample
24306 @group
24307 Asm ("movl %0, %%ebx" & LF & HT &
24308      "movl %%ebx, %1",
24309      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24310      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
24311      Clobber => "ebx");
24312 @end group
24313 @end smallexample
24315 The Clobber parameter is a static string expression specifying the
24316 register(s) you are using.  Note that register names are @emph{not} prefixed
24317 by a percent sign. Also, if more than one register is used then their names
24318 are separated by commas; e.g., @code{"eax, ebx"}
24320 The @code{Clobber} parameter has several additional uses:
24321 @enumerate
24322 @item Use ``register'' name @code{cc} to indicate that flags might have changed
24323 @item Use ``register'' name @code{memory} if you changed a memory location
24324 @end enumerate
24326 @c ---------------------------------------------------------------------------
24327 @node The Volatile Parameter
24328 @subsection The @code{Volatile} Parameter
24329 @cindex Volatile parameter
24331 @noindent
24332 Compiler optimizations in the presence of Inline Assembler may sometimes have
24333 unwanted effects.  For example, when an @code{Asm} invocation with an input
24334 variable is inside a loop, the compiler might move the loading of the input
24335 variable outside the loop, regarding it as a one-time initialization.
24337 If this effect is not desired, you can disable such optimizations by setting
24338 the @code{Volatile} parameter to @code{True}; for example:
24340 @smallexample @c ada
24341 @group
24342 Asm ("movl %0, %%ebx" & LF & HT &
24343      "movl %%ebx, %1",
24344      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
24345      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
24346      Clobber  => "ebx",
24347      Volatile => True);
24348 @end group
24349 @end smallexample
24351 By default, @code{Volatile} is set to @code{False} unless there is no
24352 @code{Outputs} parameter.
24354 Although setting @code{Volatile} to @code{True} prevents unwanted
24355 optimizations, it will also disable other optimizations that might be
24356 important for efficiency. In general, you should set @code{Volatile}
24357 to @code{True} only if the compiler's optimizations have created
24358 problems.
24360 @c ---------------------------------------------------------------------------
24361 @node A Complete Example
24362 @section A Complete Example
24364 @noindent
24365 This section contains a complete program illustrating a realistic usage
24366 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
24367 @code{Check_CPU} and a package @code{Intel_CPU}.
24368 The package declares a collection of functions that detect the properties
24369 of the 32-bit x86 processor that is running the program.
24370 The main procedure invokes these functions and displays the information.
24372 The Intel_CPU package could be enhanced by adding functions to
24373 detect the type of x386 co-processor, the processor caching options and
24374 special operations such as the SIMD extensions.
24376 Although the Intel_CPU package has been written for 32-bit Intel
24377 compatible CPUs, it is OS neutral. It has been tested on DOS,
24378 Windows/NT and GNU/Linux.
24380 @menu
24381 * Check_CPU Procedure::
24382 * Intel_CPU Package Specification::
24383 * Intel_CPU Package Body::
24384 @end menu
24386 @c ---------------------------------------------------------------------------
24387 @node Check_CPU Procedure
24388 @subsection @code{Check_CPU} Procedure
24389 @cindex Check_CPU procedure
24391 @smallexample @c adanocomment
24392 ---------------------------------------------------------------------
24393 --                                                                 --
24394 --  Uses the Intel_CPU package to identify the CPU the program is  --
24395 --  running on, and some of the features it supports.              --
24396 --                                                                 --
24397 ---------------------------------------------------------------------
24399 with Intel_CPU;                     --  Intel CPU detection functions
24400 with Ada.Text_IO;                   --  Standard text I/O
24401 with Ada.Command_Line;              --  To set the exit status
24403 procedure Check_CPU is
24405    Type_Found : Boolean := False;
24406    --  Flag to indicate that processor was identified
24408    Features   : Intel_CPU.Processor_Features;
24409    --  The processor features
24411    Signature  : Intel_CPU.Processor_Signature;
24412    --  The processor type signature
24414 begin
24416    -----------------------------------
24417    --  Display the program banner.  --
24418    -----------------------------------
24420    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
24421                          ": check Intel CPU version and features, v1.0");
24422    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
24423    Ada.Text_IO.New_Line;
24425    -----------------------------------------------------------------------
24426    --  We can safely start with the assumption that we are on at least  --
24427    --  a x386 processor. If the CPUID instruction is present, then we   --
24428    --  have a later processor type.                                     --
24429    -----------------------------------------------------------------------
24431    if Intel_CPU.Has_CPUID = False then
24433       --  No CPUID instruction, so we assume this is indeed a x386
24434       --  processor. We can still check if it has a FP co-processor.
24435       if Intel_CPU.Has_FPU then
24436          Ada.Text_IO.Put_Line
24437            ("x386-type processor with a FP co-processor");
24438       else
24439          Ada.Text_IO.Put_Line
24440            ("x386-type processor without a FP co-processor");
24441       end if;  --  check for FPU
24443       --  Program done
24444       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24445       return;
24447    end if;  --  check for CPUID
24449    -----------------------------------------------------------------------
24450    --  If CPUID is supported, check if this is a true Intel processor,  --
24451    --  if it is not, display a warning.                                 --
24452    -----------------------------------------------------------------------
24454    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
24455       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
24456       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
24457    end if;  --  check if Intel
24459    ----------------------------------------------------------------------
24460    --  With the CPUID instruction present, we can assume at least a    --
24461    --  x486 processor. If the CPUID support level is < 1 then we have  --
24462    --  to leave it at that.                                            --
24463    ----------------------------------------------------------------------
24465    if Intel_CPU.CPUID_Level < 1 then
24467       --  Ok, this is a x486 processor. we still can get the Vendor ID
24468       Ada.Text_IO.Put_Line ("x486-type processor");
24469       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
24471       --  We can also check if there is a FPU present
24472       if Intel_CPU.Has_FPU then
24473          Ada.Text_IO.Put_Line ("Floating-Point support");
24474       else
24475          Ada.Text_IO.Put_Line ("No Floating-Point support");
24476       end if;  --  check for FPU
24478       --  Program done
24479       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24480       return;
24482    end if;  --  check CPUID level
24484    ---------------------------------------------------------------------
24485    --  With a CPUID level of 1 we can use the processor signature to  --
24486    --  determine it's exact type.                                     --
24487    ---------------------------------------------------------------------
24489    Signature := Intel_CPU.Signature;
24491    ----------------------------------------------------------------------
24492    --  Ok, now we go into a lot of messy comparisons to get the        --
24493    --  processor type. For clarity, no attememt to try to optimize the --
24494    --  comparisons has been made. Note that since Intel_CPU does not   --
24495    --  support getting cache info, we cannot distinguish between P5    --
24496    --  and Celeron types yet.                                          --
24497    ----------------------------------------------------------------------
24499    --  x486SL
24500    if Signature.Processor_Type = 2#00#   and
24501      Signature.Family          = 2#0100# and
24502      Signature.Model           = 2#0100# then
24503       Type_Found := True;
24504       Ada.Text_IO.Put_Line ("x486SL processor");
24505    end if;
24507    --  x486DX2 Write-Back
24508    if Signature.Processor_Type = 2#00#   and
24509      Signature.Family          = 2#0100# and
24510      Signature.Model           = 2#0111# then
24511       Type_Found := True;
24512       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
24513    end if;
24515    --  x486DX4
24516    if Signature.Processor_Type = 2#00#   and
24517      Signature.Family          = 2#0100# and
24518      Signature.Model           = 2#1000# then
24519       Type_Found := True;
24520       Ada.Text_IO.Put_Line ("x486DX4 processor");
24521    end if;
24523    --  x486DX4 Overdrive
24524    if Signature.Processor_Type = 2#01#   and
24525      Signature.Family          = 2#0100# and
24526      Signature.Model           = 2#1000# then
24527       Type_Found := True;
24528       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
24529    end if;
24531    --  Pentium (60, 66)
24532    if Signature.Processor_Type = 2#00#   and
24533      Signature.Family          = 2#0101# and
24534      Signature.Model           = 2#0001# then
24535       Type_Found := True;
24536       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
24537    end if;
24539    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
24540    if Signature.Processor_Type = 2#00#   and
24541      Signature.Family          = 2#0101# and
24542      Signature.Model           = 2#0010# then
24543       Type_Found := True;
24544       Ada.Text_IO.Put_Line
24545         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
24546    end if;
24548    --  Pentium OverDrive (60, 66)
24549    if Signature.Processor_Type = 2#01#   and
24550      Signature.Family          = 2#0101# and
24551      Signature.Model           = 2#0001# then
24552       Type_Found := True;
24553       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
24554    end if;
24556    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
24557    if Signature.Processor_Type = 2#01#   and
24558      Signature.Family          = 2#0101# and
24559      Signature.Model           = 2#0010# then
24560       Type_Found := True;
24561       Ada.Text_IO.Put_Line
24562         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
24563    end if;
24565    --  Pentium OverDrive processor for x486 processor-based systems
24566    if Signature.Processor_Type = 2#01#   and
24567      Signature.Family          = 2#0101# and
24568      Signature.Model           = 2#0011# then
24569       Type_Found := True;
24570       Ada.Text_IO.Put_Line
24571         ("Pentium OverDrive processor for x486 processor-based systems");
24572    end if;
24574    --  Pentium processor with MMX technology (166, 200)
24575    if Signature.Processor_Type = 2#00#   and
24576      Signature.Family          = 2#0101# and
24577      Signature.Model           = 2#0100# then
24578       Type_Found := True;
24579       Ada.Text_IO.Put_Line
24580         ("Pentium processor with MMX technology (166, 200)");
24581    end if;
24583    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
24584    if Signature.Processor_Type = 2#01#   and
24585      Signature.Family          = 2#0101# and
24586      Signature.Model           = 2#0100# then
24587       Type_Found := True;
24588       Ada.Text_IO.Put_Line
24589         ("Pentium OverDrive processor with MMX " &
24590          "technology for Pentium processor (75, 90, 100, 120, 133)");
24591    end if;
24593    --  Pentium Pro processor
24594    if Signature.Processor_Type = 2#00#   and
24595      Signature.Family          = 2#0110# and
24596      Signature.Model           = 2#0001# then
24597       Type_Found := True;
24598       Ada.Text_IO.Put_Line ("Pentium Pro processor");
24599    end if;
24601    --  Pentium II processor, model 3
24602    if Signature.Processor_Type = 2#00#   and
24603      Signature.Family          = 2#0110# and
24604      Signature.Model           = 2#0011# then
24605       Type_Found := True;
24606       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
24607    end if;
24609    --  Pentium II processor, model 5 or Celeron processor
24610    if Signature.Processor_Type = 2#00#   and
24611      Signature.Family          = 2#0110# and
24612      Signature.Model           = 2#0101# then
24613       Type_Found := True;
24614       Ada.Text_IO.Put_Line
24615         ("Pentium II processor, model 5 or Celeron processor");
24616    end if;
24618    --  Pentium Pro OverDrive processor
24619    if Signature.Processor_Type = 2#01#   and
24620      Signature.Family          = 2#0110# and
24621      Signature.Model           = 2#0011# then
24622       Type_Found := True;
24623       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
24624    end if;
24626    --  If no type recognized, we have an unknown. Display what
24627    --  we _do_ know
24628    if Type_Found = False then
24629       Ada.Text_IO.Put_Line ("Unknown processor");
24630    end if;
24632    -----------------------------------------
24633    --  Display processor stepping level.  --
24634    -----------------------------------------
24636    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
24638    ---------------------------------
24639    --  Display vendor ID string.  --
24640    ---------------------------------
24642    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
24644    ------------------------------------
24645    --  Get the processors features.  --
24646    ------------------------------------
24648    Features := Intel_CPU.Features;
24650    -----------------------------
24651    --  Check for a FPU unit.  --
24652    -----------------------------
24654    if Features.FPU = True then
24655       Ada.Text_IO.Put_Line ("Floating-Point unit available");
24656    else
24657       Ada.Text_IO.Put_Line ("no Floating-Point unit");
24658    end if;  --  check for FPU
24660    --------------------------------
24661    --  List processor features.  --
24662    --------------------------------
24664    Ada.Text_IO.Put_Line ("Supported features: ");
24666    --  Virtual Mode Extension
24667    if Features.VME = True then
24668       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
24669    end if;
24671    --  Debugging Extension
24672    if Features.DE = True then
24673       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
24674    end if;
24676    --  Page Size Extension
24677    if Features.PSE = True then
24678       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
24679    end if;
24681    --  Time Stamp Counter
24682    if Features.TSC = True then
24683       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
24684    end if;
24686    --  Model Specific Registers
24687    if Features.MSR = True then
24688       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
24689    end if;
24691    --  Physical Address Extension
24692    if Features.PAE = True then
24693       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
24694    end if;
24696    --  Machine Check Extension
24697    if Features.MCE = True then
24698       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
24699    end if;
24701    --  CMPXCHG8 instruction supported
24702    if Features.CX8 = True then
24703       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
24704    end if;
24706    --  on-chip APIC hardware support
24707    if Features.APIC = True then
24708       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
24709    end if;
24711    --  Fast System Call
24712    if Features.SEP = True then
24713       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
24714    end if;
24716    --  Memory Type Range Registers
24717    if Features.MTRR = True then
24718       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
24719    end if;
24721    --  Page Global Enable
24722    if Features.PGE = True then
24723       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
24724    end if;
24726    --  Machine Check Architecture
24727    if Features.MCA = True then
24728       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
24729    end if;
24731    --  Conditional Move Instruction Supported
24732    if Features.CMOV = True then
24733       Ada.Text_IO.Put_Line
24734         ("    CMOV   - Conditional Move Instruction Supported");
24735    end if;
24737    --  Page Attribute Table
24738    if Features.PAT = True then
24739       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
24740    end if;
24742    --  36-bit Page Size Extension
24743    if Features.PSE_36 = True then
24744       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
24745    end if;
24747    --  MMX technology supported
24748    if Features.MMX = True then
24749       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
24750    end if;
24752    --  Fast FP Save and Restore
24753    if Features.FXSR = True then
24754       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
24755    end if;
24757    ---------------------
24758    --  Program done.  --
24759    ---------------------
24761    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24763 exception
24765    when others =>
24766       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
24767       raise;
24769 end Check_CPU;
24770 @end smallexample
24772 @c ---------------------------------------------------------------------------
24773 @node Intel_CPU Package Specification
24774 @subsection @code{Intel_CPU} Package Specification
24775 @cindex Intel_CPU package specification
24777 @smallexample @c adanocomment
24778 -------------------------------------------------------------------------
24779 --                                                                     --
24780 --  file: intel_cpu.ads                                                --
24781 --                                                                     --
24782 --           *********************************************             --
24783 --           * WARNING: for 32-bit Intel processors only *             --
24784 --           *********************************************             --
24785 --                                                                     --
24786 --  This package contains a number of subprograms that are useful in   --
24787 --  determining the Intel x86 CPU (and the features it supports) on    --
24788 --  which the program is running.                                      --
24789 --                                                                     --
24790 --  The package is based upon the information given in the Intel       --
24791 --  Application Note AP-485: "Intel Processor Identification and the   --
24792 --  CPUID Instruction" as of April 1998. This application note can be  --
24793 --  found on www.intel.com.                                            --
24794 --                                                                     --
24795 --  It currently deals with 32-bit processors only, will not detect    --
24796 --  features added after april 1998, and does not guarantee proper     --
24797 --  results on Intel-compatible processors.                            --
24798 --                                                                     --
24799 --  Cache info and x386 fpu type detection are not supported.          --
24800 --                                                                     --
24801 --  This package does not use any privileged instructions, so should   --
24802 --  work on any OS running on a 32-bit Intel processor.                --
24803 --                                                                     --
24804 -------------------------------------------------------------------------
24806 with Interfaces;             use Interfaces;
24807 --  for using unsigned types
24809 with System.Machine_Code;    use System.Machine_Code;
24810 --  for using inline assembler code
24812 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
24813 --  for inserting control characters
24815 package Intel_CPU is
24817    ----------------------
24818    --  Processor bits  --
24819    ----------------------
24821    subtype Num_Bits is Natural range 0 .. 31;
24822    --  the number of processor bits (32)
24824    --------------------------
24825    --  Processor register  --
24826    --------------------------
24828    --  define a processor register type for easy access to
24829    --  the individual bits
24831    type Processor_Register is array (Num_Bits) of Boolean;
24832    pragma Pack (Processor_Register);
24833    for Processor_Register'Size use 32;
24835    -------------------------
24836    --  Unsigned register  --
24837    -------------------------
24839    --  define a processor register type for easy access to
24840    --  the individual bytes
24842    type Unsigned_Register is
24843       record
24844          L1 : Unsigned_8;
24845          H1 : Unsigned_8;
24846          L2 : Unsigned_8;
24847          H2 : Unsigned_8;
24848       end record;
24850    for Unsigned_Register use
24851       record
24852          L1 at 0 range  0 ..  7;
24853          H1 at 0 range  8 .. 15;
24854          L2 at 0 range 16 .. 23;
24855          H2 at 0 range 24 .. 31;
24856       end record;
24858    for Unsigned_Register'Size use 32;
24860    ---------------------------------
24861    --  Intel processor vendor ID  --
24862    ---------------------------------
24864    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
24865    --  indicates an Intel manufactured processor
24867    ------------------------------------
24868    --  Processor signature register  --
24869    ------------------------------------
24871    --  a register type to hold the processor signature
24873    type Processor_Signature is
24874       record
24875          Stepping       : Natural range 0 .. 15;
24876          Model          : Natural range 0 .. 15;
24877          Family         : Natural range 0 .. 15;
24878          Processor_Type : Natural range 0 .. 3;
24879          Reserved       : Natural range 0 .. 262143;
24880       end record;
24882    for Processor_Signature use
24883       record
24884          Stepping       at 0 range  0 ..  3;
24885          Model          at 0 range  4 ..  7;
24886          Family         at 0 range  8 .. 11;
24887          Processor_Type at 0 range 12 .. 13;
24888          Reserved       at 0 range 14 .. 31;
24889       end record;
24891    for Processor_Signature'Size use 32;
24893    -----------------------------------
24894    --  Processor features register  --
24895    -----------------------------------
24897    --  a processor register to hold the processor feature flags
24899    type Processor_Features is
24900       record
24901          FPU    : Boolean;                --  floating point unit on chip
24902          VME    : Boolean;                --  virtual mode extension
24903          DE     : Boolean;                --  debugging extension
24904          PSE    : Boolean;                --  page size extension
24905          TSC    : Boolean;                --  time stamp counter
24906          MSR    : Boolean;                --  model specific registers
24907          PAE    : Boolean;                --  physical address extension
24908          MCE    : Boolean;                --  machine check extension
24909          CX8    : Boolean;                --  cmpxchg8 instruction
24910          APIC   : Boolean;                --  on-chip apic hardware
24911          Res_1  : Boolean;                --  reserved for extensions
24912          SEP    : Boolean;                --  fast system call
24913          MTRR   : Boolean;                --  memory type range registers
24914          PGE    : Boolean;                --  page global enable
24915          MCA    : Boolean;                --  machine check architecture
24916          CMOV   : Boolean;                --  conditional move supported
24917          PAT    : Boolean;                --  page attribute table
24918          PSE_36 : Boolean;                --  36-bit page size extension
24919          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
24920          MMX    : Boolean;                --  MMX technology supported
24921          FXSR   : Boolean;                --  fast FP save and restore
24922          Res_3  : Natural range 0 .. 127; --  reserved for extensions
24923       end record;
24925    for Processor_Features use
24926       record
24927          FPU    at 0 range  0 ..  0;
24928          VME    at 0 range  1 ..  1;
24929          DE     at 0 range  2 ..  2;
24930          PSE    at 0 range  3 ..  3;
24931          TSC    at 0 range  4 ..  4;
24932          MSR    at 0 range  5 ..  5;
24933          PAE    at 0 range  6 ..  6;
24934          MCE    at 0 range  7 ..  7;
24935          CX8    at 0 range  8 ..  8;
24936          APIC   at 0 range  9 ..  9;
24937          Res_1  at 0 range 10 .. 10;
24938          SEP    at 0 range 11 .. 11;
24939          MTRR   at 0 range 12 .. 12;
24940          PGE    at 0 range 13 .. 13;
24941          MCA    at 0 range 14 .. 14;
24942          CMOV   at 0 range 15 .. 15;
24943          PAT    at 0 range 16 .. 16;
24944          PSE_36 at 0 range 17 .. 17;
24945          Res_2  at 0 range 18 .. 22;
24946          MMX    at 0 range 23 .. 23;
24947          FXSR   at 0 range 24 .. 24;
24948          Res_3  at 0 range 25 .. 31;
24949       end record;
24951    for Processor_Features'Size use 32;
24953    -------------------
24954    --  Subprograms  --
24955    -------------------
24957    function Has_FPU return Boolean;
24958    --  return True if a FPU is found
24959    --  use only if CPUID is not supported
24961    function Has_CPUID return Boolean;
24962    --  return True if the processor supports the CPUID instruction
24964    function CPUID_Level return Natural;
24965    --  return the CPUID support level (0, 1 or 2)
24966    --  can only be called if the CPUID instruction is supported
24968    function Vendor_ID return String;
24969    --  return the processor vendor identification string
24970    --  can only be called if the CPUID instruction is supported
24972    function Signature return Processor_Signature;
24973    --  return the processor signature
24974    --  can only be called if the CPUID instruction is supported
24976    function Features return Processor_Features;
24977    --  return the processors features
24978    --  can only be called if the CPUID instruction is supported
24980 private
24982    ------------------------
24983    --  EFLAGS bit names  --
24984    ------------------------
24986    ID_Flag : constant Num_Bits := 21;
24987    --  ID flag bit
24989 end Intel_CPU;
24990 @end smallexample
24992 @c ---------------------------------------------------------------------------
24993 @node Intel_CPU Package Body
24994 @subsection @code{Intel_CPU} Package Body
24995 @cindex Intel_CPU package body
24997 @smallexample @c adanocomment
24998 package body Intel_CPU is
25000    ---------------------------
25001    --  Detect FPU presence  --
25002    ---------------------------
25004    --  There is a FPU present if we can set values to the FPU Status
25005    --  and Control Words.
25007    function Has_FPU return Boolean is
25009       Register : Unsigned_16;
25010       --  processor register to store a word
25012    begin
25014       --  check if we can change the status word
25015       Asm (
25017            --  the assembler code
25018            "finit"              & LF & HT &    --  reset status word
25019            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25020            "fnstsw %0"          & LF & HT &    --  save status word
25021            "movw %%ax, %0",                    --  store status word
25023            --  output stored in Register
25024            --  register must be a memory location
25025            Outputs => Unsigned_16'Asm_output ("=m", Register),
25027            --  tell compiler that we used eax
25028            Clobber => "eax");
25030       --  if the status word is zero, there is no FPU
25031       if Register = 0 then
25032          return False;   --  no status word
25033       end if;  --  check status word value
25035       --  check if we can get the control word
25036       Asm (
25038            --  the assembler code
25039            "fnstcw %0",   --  save the control word
25041            --  output into Register
25042            --  register must be a memory location
25043            Outputs => Unsigned_16'Asm_output ("=m", Register));
25045       --  check the relevant bits
25046       if (Register and 16#103F#) /= 16#003F# then
25047          return False;   --  no control word
25048       end if;  --  check control word value
25050       --  FPU found
25051       return True;
25053    end Has_FPU;
25055    --------------------------------
25056    --  Detect CPUID instruction  --
25057    --------------------------------
25059    --  The processor supports the CPUID instruction if it is possible
25060    --  to change the value of ID flag bit in the EFLAGS register.
25062    function Has_CPUID return Boolean is
25064       Original_Flags, Modified_Flags : Processor_Register;
25065       --  EFLAG contents before and after changing the ID flag
25067    begin
25069       --  try flipping the ID flag in the EFLAGS register
25070       Asm (
25072            --  the assembler code
25073            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25074            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
25075            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
25076            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
25077            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
25078            "popfl"                & LF & HT &     --  load EFLAGS register
25079            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25080            "pop %1",                              --  save EFLAGS content
25082            --  output values, may be anything
25083            --  Original_Flags is %0
25084            --  Modified_Flags is %1
25085            Outputs =>
25086               (Processor_Register'Asm_output ("=g", Original_Flags),
25087                Processor_Register'Asm_output ("=g", Modified_Flags)),
25089            --  tell compiler eax is destroyed
25090            Clobber => "eax");
25092       --  check if CPUID is supported
25093       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
25094          return True;   --  ID flag was modified
25095       else
25096          return False;  --  ID flag unchanged
25097       end if;  --  check for CPUID
25099    end Has_CPUID;
25101    -------------------------------
25102    --  Get CPUID support level  --
25103    -------------------------------
25105    function CPUID_Level return Natural is
25107       Level : Unsigned_32;
25108       --  returned support level
25110    begin
25112       --  execute CPUID, storing the results in the Level register
25113       Asm (
25115            --  the assembler code
25116            "cpuid",    --  execute CPUID
25118            --  zero is stored in eax
25119            --  returning the support level in eax
25120            Inputs => Unsigned_32'Asm_input ("a", 0),
25122            --  eax is stored in Level
25123            Outputs => Unsigned_32'Asm_output ("=a", Level),
25125            --  tell compiler ebx, ecx and edx registers are destroyed
25126            Clobber => "ebx, ecx, edx");
25128       --  return the support level
25129       return Natural (Level);
25131    end CPUID_Level;
25133    --------------------------------
25134    --  Get CPU Vendor ID String  --
25135    --------------------------------
25137    --  The vendor ID string is returned in the ebx, ecx and edx register
25138    --  after executing the CPUID instruction with eax set to zero.
25139    --  In case of a true Intel processor the string returned is
25140    --  "GenuineIntel"
25142    function Vendor_ID return String is
25144       Ebx, Ecx, Edx : Unsigned_Register;
25145       --  registers containing the vendor ID string
25147       Vendor_ID : String (1 .. 12);
25148       -- the vendor ID string
25150    begin
25152       --  execute CPUID, storing the results in the processor registers
25153       Asm (
25155            --  the assembler code
25156            "cpuid",    --  execute CPUID
25158            --  zero stored in eax
25159            --  vendor ID string returned in ebx, ecx and edx
25160            Inputs => Unsigned_32'Asm_input ("a", 0),
25162            --  ebx is stored in Ebx
25163            --  ecx is stored in Ecx
25164            --  edx is stored in Edx
25165            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
25166                        Unsigned_Register'Asm_output ("=c", Ecx),
25167                        Unsigned_Register'Asm_output ("=d", Edx)));
25169       --  now build the vendor ID string
25170       Vendor_ID( 1) := Character'Val (Ebx.L1);
25171       Vendor_ID( 2) := Character'Val (Ebx.H1);
25172       Vendor_ID( 3) := Character'Val (Ebx.L2);
25173       Vendor_ID( 4) := Character'Val (Ebx.H2);
25174       Vendor_ID( 5) := Character'Val (Edx.L1);
25175       Vendor_ID( 6) := Character'Val (Edx.H1);
25176       Vendor_ID( 7) := Character'Val (Edx.L2);
25177       Vendor_ID( 8) := Character'Val (Edx.H2);
25178       Vendor_ID( 9) := Character'Val (Ecx.L1);
25179       Vendor_ID(10) := Character'Val (Ecx.H1);
25180       Vendor_ID(11) := Character'Val (Ecx.L2);
25181       Vendor_ID(12) := Character'Val (Ecx.H2);
25183       --  return string
25184       return Vendor_ID;
25186    end Vendor_ID;
25188    -------------------------------
25189    --  Get processor signature  --
25190    -------------------------------
25192    function Signature return Processor_Signature is
25194       Result : Processor_Signature;
25195       --  processor signature returned
25197    begin
25199       --  execute CPUID, storing the results in the Result variable
25200       Asm (
25202            --  the assembler code
25203            "cpuid",    --  execute CPUID
25205            --  one is stored in eax
25206            --  processor signature returned in eax
25207            Inputs => Unsigned_32'Asm_input ("a", 1),
25209            --  eax is stored in Result
25210            Outputs => Processor_Signature'Asm_output ("=a", Result),
25212            --  tell compiler that ebx, ecx and edx are also destroyed
25213            Clobber => "ebx, ecx, edx");
25215       --  return processor signature
25216       return Result;
25218    end Signature;
25220    ------------------------------
25221    --  Get processor features  --
25222    ------------------------------
25224    function Features return Processor_Features is
25226       Result : Processor_Features;
25227       --  processor features returned
25229    begin
25231       --  execute CPUID, storing the results in the Result variable
25232       Asm (
25234            --  the assembler code
25235            "cpuid",    --  execute CPUID
25237            --  one stored in eax
25238            --  processor features returned in edx
25239            Inputs => Unsigned_32'Asm_input ("a", 1),
25241            --  edx is stored in Result
25242            Outputs => Processor_Features'Asm_output ("=d", Result),
25244            --  tell compiler that ebx and ecx are also destroyed
25245            Clobber => "ebx, ecx");
25247       --  return processor signature
25248       return Result;
25250    end Features;
25252 end Intel_CPU;
25253 @end smallexample
25254 @c END OF INLINE ASSEMBLER CHAPTER
25255 @c ===============================
25259 @c ***********************************
25260 @c * Compatibility and Porting Guide *
25261 @c ***********************************
25262 @node Compatibility and Porting Guide
25263 @appendix Compatibility and Porting Guide
25265 @noindent
25266 This chapter describes the compatibility issues that may arise between
25267 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25268 can expedite porting
25269 applications developed in other Ada environments.
25271 @menu
25272 * Compatibility with Ada 83::
25273 * Implementation-dependent characteristics::
25274 * Compatibility with DEC Ada 83::
25275 * Compatibility with Other Ada 95 Systems::
25276 * Representation Clauses::
25277 @end menu
25279 @node Compatibility with Ada 83
25280 @section Compatibility with Ada 83
25281 @cindex Compatibility (between Ada 83 and Ada 95)
25283 @noindent
25284 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25285 particular, the design intention is that the difficulties associated
25286 with moving from Ada 83 to Ada 95 should be no greater than those
25287 that occur when moving from one Ada 83 system to another.
25289 However, there are a number of points at which there are minor
25290 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25291 full details of these issues,
25292 and should be consulted for a complete treatment.
25293 In practice the
25294 following subsections treat the most likely issues to be encountered.
25296 @menu
25297 * Legal Ada 83 programs that are illegal in Ada 95::
25298 * More deterministic semantics::
25299 * Changed semantics::
25300 * Other language compatibility issues::
25301 @end menu
25303 @node Legal Ada 83 programs that are illegal in Ada 95
25304 @subsection Legal Ada 83 programs that are illegal in Ada 95
25306 @table @asis
25307 @item Character literals
25308 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25309 @code{Wide_Character} as a new predefined character type, some uses of
25310 character literals that were legal in Ada 83 are illegal in Ada 95.
25311 For example:
25312 @smallexample @c ada
25313    for Char in 'A' .. 'Z' loop ... end loop;
25314 @end smallexample
25315 @noindent
25316 The problem is that @code{'A'} and @code{'Z'} could be from either
25317 @code{Character} or @code{Wide_Character}.  The simplest correction
25318 is to make the type explicit; e.g.:
25319 @smallexample @c ada
25320    for Char in Character range 'A' .. 'Z' loop ... end loop;
25321 @end smallexample
25323 @item New reserved words
25324 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25325 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25326 Existing Ada 83 code using any of these identifiers must be edited to
25327 use some alternative name.
25329 @item Freezing rules
25330 The rules in Ada 95 are slightly different with regard to the point at
25331 which entities are frozen, and representation pragmas and clauses are
25332 not permitted past the freeze point.  This shows up most typically in
25333 the form of an error message complaining that a representation item
25334 appears too late, and the appropriate corrective action is to move
25335 the item nearer to the declaration of the entity to which it refers.
25337 A particular case is that representation pragmas
25338 @ifset vms
25339 (including the
25340 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25341 @end ifset
25342 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25343 declaration must be introduced to which the pragma can be applied.
25345 @item Optional bodies for library packages
25346 In Ada 83, a package that did not require a package body was nevertheless
25347 allowed to have one.  This lead to certain surprises in compiling large
25348 systems (situations in which the body could be unexpectedly ignored by the
25349 binder).  In Ada 95, if a package does not require a body then it is not
25350 permitted to have a body.  To fix this problem, simply remove a redundant
25351 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25352 into the spec that makes the body required.  One approach is to add a private
25353 part to the package declaration (if necessary), and define a parameterless
25354 procedure called @code{Requires_Body}, which must then be given a dummy
25355 procedure body in the package body, which then becomes required.
25356 Another approach (assuming that this does not introduce elaboration
25357 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25358 since one effect of this pragma is to require the presence of a package body.
25360 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25361 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25362 @code{Constraint_Error}.
25363 This means that it is illegal to have separate exception handlers for
25364 the two exceptions.  The fix is simply to remove the handler for the
25365 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25366 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25368 @item Indefinite subtypes in generics
25369 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25370 as the actual for a generic formal private type, but then the instantiation
25371 would be illegal if there were any instances of declarations of variables
25372 of this type in the generic body.  In Ada 95, to avoid this clear violation
25373 of the methodological principle known as the ``contract model'',
25374 the generic declaration explicitly indicates whether
25375 or not such instantiations are permitted.  If a generic formal parameter
25376 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25377 type name, then it can be instantiated with indefinite types, but no
25378 stand-alone variables can be declared of this type.  Any attempt to declare
25379 such a variable will result in an illegality at the time the generic is
25380 declared.  If the @code{(<>)} notation is not used, then it is illegal
25381 to instantiate the generic with an indefinite type.
25382 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25383 It will show up as a compile time error, and
25384 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25385 @end table
25387 @node More deterministic semantics
25388 @subsection More deterministic semantics
25390 @table @asis
25391 @item Conversions
25392 Conversions from real types to integer types round away from 0.  In Ada 83
25393 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25394 implementation freedom was intended to support unbiased rounding in
25395 statistical applications, but in practice it interfered with portability.
25396 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25397 is required.  Numeric code may be affected by this change in semantics.
25398 Note, though, that this issue is no worse than already existed in Ada 83
25399 when porting code from one vendor to another.
25401 @item Tasking
25402 The Real-Time Annex introduces a set of policies that define the behavior of
25403 features that were implementation dependent in Ada 83, such as the order in
25404 which open select branches are executed.
25405 @end table
25407 @node Changed semantics
25408 @subsection Changed semantics
25410 @noindent
25411 The worst kind of incompatibility is one where a program that is legal in
25412 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25413 possible in Ada 83.  Fortunately this is extremely rare, but the one
25414 situation that you should be alert to is the change in the predefined type
25415 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25417 @table @asis
25418 @item range of @code{Character}
25419 The range of @code{Standard.Character} is now the full 256 characters
25420 of Latin-1, whereas in most Ada 83 implementations it was restricted
25421 to 128 characters. Although some of the effects of
25422 this change will be manifest in compile-time rejection of legal
25423 Ada 83 programs it is possible for a working Ada 83 program to have
25424 a different effect in Ada 95, one that was not permitted in Ada 83.
25425 As an example, the expression
25426 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25427 delivers @code{255} as its value.
25428 In general, you should look at the logic of any
25429 character-processing Ada 83 program and see whether it needs to be adapted
25430 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25431 character handling package that may be relevant if code needs to be adapted
25432 to account for the additional Latin-1 elements.
25433 The desirable fix is to
25434 modify the program to accommodate the full character set, but in some cases
25435 it may be convenient to define a subtype or derived type of Character that
25436 covers only the restricted range.
25437 @cindex Latin-1
25438 @end table
25440 @node Other language compatibility issues
25441 @subsection Other language compatibility issues
25442 @table @asis
25443 @item @option{-gnat83 switch}
25444 All implementations of GNAT provide a switch that causes GNAT to operate
25445 in Ada 83 mode.  In this mode, some but not all compatibility problems
25446 of the type described above are handled automatically.  For example, the
25447 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25448 However,
25449 in practice, it is usually advisable to make the necessary modifications
25450 to the program to remove the need for using this switch.
25451 See @ref{Compiling Ada 83 Programs}.
25453 @item Support for removed Ada 83 pragmas and attributes
25454 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25455 generally because they have been replaced by other mechanisms.  Ada 95
25456 compilers are allowed, but not required, to implement these missing
25457 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25458 such pragmas and attributes, eliminating this compatibility concern.  These
25459 include @code{pragma Interface} and the floating point type attributes
25460 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25461 @end table
25464 @node Implementation-dependent characteristics
25465 @section Implementation-dependent characteristics
25466 @noindent
25467 Although the Ada language defines the semantics of each construct as
25468 precisely as practical, in some situations (for example for reasons of
25469 efficiency, or where the effect is heavily dependent on the host or target
25470 platform) the implementation is allowed some freedom.  In porting Ada 83
25471 code to GNAT, you need to be aware of whether / how the existing code
25472 exercised such implementation dependencies.  Such characteristics fall into
25473 several categories, and GNAT offers specific support in assisting the
25474 transition from certain Ada 83 compilers.
25476 @menu
25477 * Implementation-defined pragmas::
25478 * Implementation-defined attributes::
25479 * Libraries::
25480 * Elaboration order::
25481 * Target-specific aspects::
25482 @end menu
25485 @node Implementation-defined pragmas
25486 @subsection Implementation-defined pragmas
25488 @noindent
25489 Ada compilers are allowed to supplement the language-defined pragmas, and
25490 these are a potential source of non-portability.  All GNAT-defined pragmas
25491 are described in the GNAT Reference Manual, and these include several that
25492 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25493 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25495 compatibility with DEC Ada 83, GNAT supplies the pragmas
25496 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25497 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25498 and @code{Volatile}.
25499 Other relevant pragmas include @code{External} and @code{Link_With}.
25500 Some vendor-specific
25501 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25502 recognized, thus
25503 avoiding compiler rejection of units that contain such pragmas; they are not
25504 relevant in a GNAT context and hence are not otherwise implemented.
25506 @node Implementation-defined attributes
25507 @subsection Implementation-defined attributes
25509 Analogous to pragmas, the set of attributes may be extended by an
25510 implementation.  All GNAT-defined attributes are described in the
25511 @cite{GNAT Reference Manual}, and these include several that are specifically
25512 intended
25513 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25514 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25515 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25516 @code{Type_Class}.
25518 @node Libraries
25519 @subsection Libraries
25520 @noindent
25521 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25522 code uses vendor-specific libraries then there are several ways to manage
25523 this in Ada 95:
25524 @enumerate
25525 @item
25526 If the source code for the libraries (specifications and bodies) are
25527 available, then the libraries can be migrated in the same way as the
25528 application.
25529 @item
25530 If the source code for the specifications but not the bodies are
25531 available, then you can reimplement the bodies.
25532 @item
25533 Some new Ada 95 features obviate the need for library support.  For
25534 example most Ada 83 vendors supplied a package for unsigned integers.  The
25535 Ada 95 modular type feature is the preferred way to handle this need, so
25536 instead of migrating or reimplementing the unsigned integer package it may
25537 be preferable to retrofit the application using modular types.
25538 @end enumerate
25540 @node Elaboration order
25541 @subsection Elaboration order
25542 @noindent
25543 The implementation can choose any elaboration order consistent with the unit
25544 dependency relationship.  This freedom means that some orders can result in
25545 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25546 to invoke a subprogram its body has been elaborated, or to instantiate a
25547 generic before the generic body has been elaborated.  By default GNAT
25548 attempts to choose a safe order (one that will not encounter access before
25549 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25550 needed.  However, this can lead to the creation of elaboration circularities
25551 and a resulting rejection of the program by gnatbind.  This issue is
25552 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25553 In brief, there are several
25554 ways to deal with this situation:
25556 @itemize @bullet
25557 @item
25558 Modify the program to eliminate the circularities, e.g. by moving
25559 elaboration-time code into explicitly-invoked procedures
25560 @item
25561 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25562 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25563 @code{Elaborate_All}
25564 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25565 (by selectively suppressing elaboration checks via pragma
25566 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25567 @end itemize
25569 @node Target-specific aspects
25570 @subsection Target-specific aspects
25571 @noindent
25572 Low-level applications need to deal with machine addresses, data
25573 representations, interfacing with assembler code, and similar issues.  If
25574 such an Ada 83 application is being ported to different target hardware (for
25575 example where the byte endianness has changed) then you will need to
25576 carefully examine the program logic; the porting effort will heavily depend
25577 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25578 incompatible with typical Ada 83 compiler practices regarding implicit
25579 packing, the meaning of the Size attribute, and the size of access values.
25580 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25583 @node Compatibility with Other Ada 95 Systems
25584 @section Compatibility with Other Ada 95 Systems
25586 @noindent
25587 Providing that programs avoid the use of implementation dependent and
25588 implementation defined features of Ada 95, as documented in the Ada 95
25589 reference manual, there should be a high degree of portability between
25590 GNAT and other Ada 95 systems.  The following are specific items which
25591 have proved troublesome in moving GNAT programs to other Ada 95
25592 compilers, but do not affect porting code to GNAT@.
25594 @table @asis
25595 @item Ada 83 Pragmas and Attributes
25596 Ada 95 compilers are allowed, but not required, to implement the missing
25597 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25598 GNAT implements all such pragmas and attributes, eliminating this as
25599 a compatibility concern, but some other Ada 95 compilers reject these
25600 pragmas and attributes.
25602 @item Special-needs Annexes
25603 GNAT implements the full set of special needs annexes.  At the
25604 current time, it is the only Ada 95 compiler to do so.  This means that
25605 programs making use of these features may not be portable to other Ada
25606 95 compilation systems.
25608 @item Representation Clauses
25609 Some other Ada 95 compilers implement only the minimal set of
25610 representation clauses required by the Ada 95 reference manual.  GNAT goes
25611 far beyond this minimal set, as described in the next section.
25612 @end table
25614 @node Representation Clauses
25615 @section Representation Clauses
25617 @noindent
25618 The Ada 83 reference manual was quite vague in describing both the minimal
25619 required implementation of representation clauses, and also their precise
25620 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25621 set of capabilities required in Ada 95 is quite limited.
25623 GNAT implements the full required set of capabilities described in the
25624 Ada 95 reference manual, but also goes much beyond this, and in particular
25625 an effort has been made to be compatible with existing Ada 83 usage to the
25626 greatest extent possible.
25628 A few cases exist in which Ada 83 compiler behavior is incompatible with
25629 requirements in the Ada 95 reference manual.  These are instances of
25630 intentional or accidental dependence on specific implementation dependent
25631 characteristics of these Ada 83 compilers.  The following is a list of
25632 the cases most likely to arise in existing legacy Ada 83 code.
25634 @table @asis
25635 @item Implicit Packing
25636 Some Ada 83 compilers allowed a Size specification to cause implicit
25637 packing of an array or record.  This could cause expensive implicit
25638 conversions for change of representation in the presence of derived
25639 types, and the Ada design intends to avoid this possibility.
25640 Subsequent AI's were issued to make it clear that such implicit
25641 change of representation in response to a Size clause is inadvisable,
25642 and this recommendation is represented explicitly in the Ada 95 RM
25643 as implementation advice that is followed by GNAT@.
25644 The problem will show up as an error
25645 message rejecting the size clause.  The fix is simply to provide
25646 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25647 a Component_Size clause.
25649 @item Meaning of Size Attribute
25650 The Size attribute in Ada 95 for discrete types is defined as being the
25651 minimal number of bits required to hold values of the type.  For example,
25652 on a 32-bit machine, the size of Natural will typically be 31 and not
25653 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25654 some 32 in this situation.  This problem will usually show up as a compile
25655 time error, but not always.  It is a good idea to check all uses of the
25656 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25657 Object_Size can provide a useful way of duplicating the behavior of
25658 some Ada 83 compiler systems.
25660 @item Size of Access Types
25661 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25662 and that therefore it will be the same size as a System.Address value.  This
25663 assumption is true for GNAT in most cases with one exception.  For the case of
25664 a pointer to an unconstrained array type (where the bounds may vary from one
25665 value of the access type to another), the default is to use a ``fat pointer'',
25666 which is represented as two separate pointers, one to the bounds, and one to
25667 the array.  This representation has a number of advantages, including improved
25668 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25669 code which makes the assumption that, for example, pointers fit in 32 bits on
25670 a machine with 32-bit addressing.
25672 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25673 access types in this case (where the designated type is an unconstrained array
25674 type).  These thin pointers are indeed the same size as a System.Address value.
25675 To specify a thin pointer, use a size clause for the type, for example:
25677 @smallexample @c ada
25678 type X is access all String;
25679 for X'Size use Standard'Address_Size;
25680 @end smallexample
25682 @noindent
25683 which will cause the type X to be represented using a single pointer.
25684 When using this representation, the bounds are right behind the array.
25685 This representation is slightly less efficient, and does not allow quite
25686 such flexibility in the use of foreign pointers or in using the
25687 Unrestricted_Access attribute to create pointers to non-aliased objects.
25688 But for any standard portable use of the access type it will work in
25689 a functionally correct manner and allow porting of existing code.
25690 Note that another way of forcing a thin pointer representation
25691 is to use a component size clause for the element size in an array,
25692 or a record representation clause for an access field in a record.
25693 @end table
25695 @node Compatibility with DEC Ada 83
25696 @section Compatibility with DEC Ada 83
25698 @noindent
25699 The VMS version of GNAT fully implements all the pragmas and attributes
25700 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25701 libraries, including Starlet.  In addition, data layouts and parameter
25702 passing conventions are highly compatible.  This means that porting
25703 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25704 most other porting efforts.  The following are some of the most
25705 significant differences between GNAT and DEC Ada 83.
25707 @table @asis
25708 @item Default floating-point representation
25709 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25710 it is VMS format.  GNAT does implement the necessary pragmas
25711 (Long_Float, Float_Representation) for changing this default.
25713 @item System
25714 The package System in GNAT exactly corresponds to the definition in the
25715 Ada 95 reference manual, which means that it excludes many of the
25716 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
25717 that contains the additional definitions, and a special pragma,
25718 Extend_System allows this package to be treated transparently as an
25719 extension of package System.
25721 @item To_Address
25722 The definitions provided by Aux_DEC are exactly compatible with those
25723 in the DEC Ada 83 version of System, with one exception.
25724 DEC Ada provides the following declarations:
25726 @smallexample @c ada
25727 TO_ADDRESS (INTEGER)
25728 TO_ADDRESS (UNSIGNED_LONGWORD)
25729 TO_ADDRESS (universal_integer)
25730 @end smallexample
25732 @noindent
25733 The version of TO_ADDRESS taking a universal integer argument is in fact
25734 an extension to Ada 83 not strictly compatible with the reference manual.
25735 In GNAT, we are constrained to be exactly compatible with the standard,
25736 and this means we cannot provide this capability.  In DEC Ada 83, the
25737 point of this definition is to deal with a call like:
25739 @smallexample @c ada
25740 TO_ADDRESS (16#12777#);
25741 @end smallexample
25743 @noindent
25744 Normally, according to the Ada 83 standard, one would expect this to be
25745 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25746 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
25747 definition using universal_integer takes precedence.
25749 In GNAT, since the version with universal_integer cannot be supplied, it is
25750 not possible to be 100% compatible.  Since there are many programs using
25751 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25752 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25753 declarations provided in the GNAT version of AUX_Dec are:
25755 @smallexample @c ada
25756 function To_Address (X : Integer) return Address;
25757 pragma Pure_Function (To_Address);
25759 function To_Address_Long (X : Unsigned_Longword)
25760  return Address;
25761 pragma Pure_Function (To_Address_Long);
25762 @end smallexample
25764 @noindent
25765 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25766 change the name to TO_ADDRESS_LONG@.
25768 @item Task_Id values
25769 The Task_Id values assigned will be different in the two systems, and GNAT
25770 does not provide a specified value for the Task_Id of the environment task,
25771 which in GNAT is treated like any other declared task.
25772 @end table
25774 For full details on these and other less significant compatibility issues,
25775 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
25776 Overview and Comparison on DIGITAL Platforms}.
25778 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
25779 attributes are recognized, although only a subset of them can sensibly
25780 be implemented.  The description of pragmas in this reference manual
25781 indicates whether or not they are applicable to non-VMS systems.
25785 @ifset unw
25786 @node Microsoft Windows Topics
25787 @appendix Microsoft Windows Topics
25788 @cindex Windows NT
25789 @cindex Windows 95
25790 @cindex Windows 98
25792 @noindent
25793 This chapter describes topics that are specific to the Microsoft Windows
25794 platforms (NT, 2000, and XP Professional).
25796 @menu
25797 * Using GNAT on Windows::
25798 * Using a network installation of GNAT::
25799 * CONSOLE and WINDOWS subsystems::
25800 * Temporary Files::
25801 * Mixed-Language Programming on Windows::
25802 * Windows Calling Conventions::
25803 * Introduction to Dynamic Link Libraries (DLLs)::
25804 * Using DLLs with GNAT::
25805 * Building DLLs with GNAT::
25806 * GNAT and Windows Resources::
25807 * Debugging a DLL::
25808 * GNAT and COM/DCOM Objects::
25809 @end menu
25811 @node Using GNAT on Windows
25812 @section Using GNAT on Windows
25814 @noindent
25815 One of the strengths of the GNAT technology is that its tool set
25816 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
25817 @code{gdb} debugger, etc.) is used in the same way regardless of the
25818 platform.
25820 On Windows this tool set is complemented by a number of Microsoft-specific
25821 tools that have been provided to facilitate interoperability with Windows
25822 when this is required. With these tools:
25824 @itemize @bullet
25826 @item
25827 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
25828 subsystems.
25830 @item
25831 You can use any Dynamically Linked Library (DLL) in your Ada code (both
25832 relocatable and non-relocatable DLLs are supported).
25834 @item
25835 You can build Ada DLLs for use in other applications. These applications
25836 can be written in a language other than Ada (e.g., C, C++, etc). Again both
25837 relocatable and non-relocatable Ada DLLs are supported.
25839 @item
25840 You can include Windows resources in your Ada application.
25842 @item
25843 You can use or create COM/DCOM objects.
25844 @end itemize
25846 @noindent
25847 Immediately below are listed all known general GNAT-for-Windows restrictions.
25848 Other restrictions about specific features like Windows Resources and DLLs
25849 are listed in separate sections below.
25851 @itemize @bullet
25853 @item
25854 It is not possible to use @code{GetLastError} and @code{SetLastError}
25855 when tasking, protected records, or exceptions are used. In these
25856 cases, in order to implement Ada semantics, the GNAT run-time system
25857 calls certain Win32 routines that set the last error variable to 0 upon
25858 success. It should be possible to use @code{GetLastError} and
25859 @code{SetLastError} when tasking, protected record, and exception
25860 features are not used, but it is not guaranteed to work.
25862 @item
25863 It is not possible to link against Microsoft libraries except for
25864 import libraries. The library must be built to be compatible with
25865 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
25866 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
25867 not be compatible with the GNAT runtime. Even if the library is
25868 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
25870 @item
25871 When the compilation environment is located on FAT32 drives, users may
25872 experience recompilations of the source files that have not changed if
25873 Daylight Saving Time (DST) state has changed since the last time files
25874 were compiled. NTFS drives do not have this problem.
25876 @item
25877 No components of the GNAT toolset use any entries in the Windows
25878 registry. The only entries that can be created are file associations and
25879 PATH settings, provided the user has chosen to create them at installation
25880 time, as well as some minimal book-keeping information needed to correctly
25881 uninstall or integrate different GNAT products.
25882 @end itemize
25884 @node Using a network installation of GNAT
25885 @section Using a network installation of GNAT
25887 @noindent
25888 Make sure the system on which GNAT is installed is accessible from the
25889 current machine, i.e. the install location is shared over the network.
25890 Shared resources are accessed on Windows by means of UNC paths, which
25891 have the format @code{\\server\sharename\path}
25893 In order to use such a network installation, simply add the UNC path of the
25894 @file{bin} directory of your GNAT installation in front of your PATH. For
25895 example, if GNAT is installed in @file{\GNAT} directory of a share location
25896 called @file{c-drive} on a machine @file{LOKI}, the following command will
25897 make it available:
25899 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
25901 Be aware that every compilation using the network installation results in the
25902 transfer of large amounts of data across the network and will likely cause
25903 serious performance penalty.
25905 @node CONSOLE and WINDOWS subsystems
25906 @section CONSOLE and WINDOWS subsystems
25907 @cindex CONSOLE Subsystem
25908 @cindex WINDOWS Subsystem
25909 @cindex -mwindows
25911 @noindent
25912 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
25913 (which is the default subsystem) will always create a console when
25914 launching the application. This is not something desirable when the
25915 application has a Windows GUI. To get rid of this console the
25916 application must be using the @code{WINDOWS} subsystem. To do so
25917 the @option{-mwindows} linker option must be specified.
25919 @smallexample
25920 $ gnatmake winprog -largs -mwindows
25921 @end smallexample
25923 @node Temporary Files
25924 @section Temporary Files
25925 @cindex Temporary files
25927 @noindent
25928 It is possible to control where temporary files gets created by setting
25929 the TMP environment variable. The file will be created:
25931 @itemize
25932 @item Under the directory pointed to by the TMP environment variable if
25933 this directory exists.
25935 @item Under c:\temp, if the TMP environment variable is not set (or not
25936 pointing to a directory) and if this directory exists.
25938 @item Under the current working directory otherwise.
25939 @end itemize
25941 @noindent
25942 This allows you to determine exactly where the temporary
25943 file will be created. This is particularly useful in networked
25944 environments where you may not have write access to some
25945 directories.
25947 @node Mixed-Language Programming on Windows
25948 @section Mixed-Language Programming on Windows
25950 @noindent
25951 Developing pure Ada applications on Windows is no different than on
25952 other GNAT-supported platforms. However, when developing or porting an
25953 application that contains a mix of Ada and C/C++, the choice of your
25954 Windows C/C++ development environment conditions your overall
25955 interoperability strategy.
25957 If you use @code{gcc} to compile the non-Ada part of your application,
25958 there are no Windows-specific restrictions that affect the overall
25959 interoperability with your Ada code. If you plan to use
25960 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
25961 the following limitations:
25963 @itemize @bullet
25964 @item
25965 You cannot link your Ada code with an object or library generated with
25966 Microsoft tools if these use the @code{.tls} section (Thread Local
25967 Storage section) since the GNAT linker does not yet support this section.
25969 @item
25970 You cannot link your Ada code with an object or library generated with
25971 Microsoft tools if these use I/O routines other than those provided in
25972 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
25973 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
25974 libraries can cause a conflict with @code{msvcrt.dll} services. For
25975 instance Visual C++ I/O stream routines conflict with those in
25976 @code{msvcrt.dll}.
25977 @end itemize
25979 @noindent
25980 If you do want to use the Microsoft tools for your non-Ada code and hit one
25981 of the above limitations, you have two choices:
25983 @enumerate
25984 @item
25985 Encapsulate your non Ada code in a DLL to be linked with your Ada
25986 application. In this case, use the Microsoft or whatever environment to
25987 build the DLL and use GNAT to build your executable
25988 (@pxref{Using DLLs with GNAT}).
25990 @item
25991 Or you can encapsulate your Ada code in a DLL to be linked with the
25992 other part of your application. In this case, use GNAT to build the DLL
25993 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
25994 environment to build your executable.
25995 @end enumerate
25997 @node Windows Calling Conventions
25998 @section Windows Calling Conventions
25999 @findex Stdcall
26000 @findex APIENTRY
26002 @menu
26003 * C Calling Convention::
26004 * Stdcall Calling Convention::
26005 * DLL Calling Convention::
26006 @end menu
26008 @noindent
26009 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26010 (callee), there are several ways to push @code{G}'s parameters on the
26011 stack and there are several possible scenarios to clean up the stack
26012 upon @code{G}'s return. A calling convention is an agreed upon software
26013 protocol whereby the responsibilities between the caller (@code{F}) and
26014 the callee (@code{G}) are clearly defined. Several calling conventions
26015 are available for Windows:
26017 @itemize @bullet
26018 @item
26019 @code{C} (Microsoft defined)
26021 @item
26022 @code{Stdcall} (Microsoft defined)
26024 @item
26025 @code{DLL} (GNAT specific)
26026 @end itemize
26028 @node C Calling Convention
26029 @subsection @code{C} Calling Convention
26031 @noindent
26032 This is the default calling convention used when interfacing to C/C++
26033 routines compiled with either @code{gcc} or Microsoft Visual C++.
26035 In the @code{C} calling convention subprogram parameters are pushed on the
26036 stack by the caller from right to left. The caller itself is in charge of
26037 cleaning up the stack after the call. In addition, the name of a routine
26038 with @code{C} calling convention is mangled by adding a leading underscore.
26040 The name to use on the Ada side when importing (or exporting) a routine
26041 with @code{C} calling convention is the name of the routine. For
26042 instance the C function:
26044 @smallexample
26045 int get_val (long);
26046 @end smallexample
26048 @noindent
26049 should be imported from Ada as follows:
26051 @smallexample @c ada
26052 @group
26053 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26054 pragma Import (C, Get_Val, External_Name => "get_val");
26055 @end group
26056 @end smallexample
26058 @noindent
26059 Note that in this particular case the @code{External_Name} parameter could
26060 have been omitted since, when missing, this parameter is taken to be the
26061 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26062 is missing, as in the above example, this parameter is set to be the
26063 @code{External_Name} with a leading underscore.
26065 When importing a variable defined in C, you should always use the @code{C}
26066 calling convention unless the object containing the variable is part of a
26067 DLL (in which case you should use the @code{DLL} calling convention,
26068 @pxref{DLL Calling Convention}).
26070 @node Stdcall Calling Convention
26071 @subsection @code{Stdcall} Calling Convention
26073 @noindent
26074 This convention, which was the calling convention used for Pascal
26075 programs, is used by Microsoft for all the routines in the Win32 API for
26076 efficiency reasons. It must be used to import any routine for which this
26077 convention was specified.
26079 In the @code{Stdcall} calling convention subprogram parameters are pushed
26080 on the stack by the caller from right to left. The callee (and not the
26081 caller) is in charge of cleaning the stack on routine exit. In addition,
26082 the name of a routine with @code{Stdcall} calling convention is mangled by
26083 adding a leading underscore (as for the @code{C} calling convention) and a
26084 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26085 bytes) of the parameters passed to the routine.
26087 The name to use on the Ada side when importing a C routine with a
26088 @code{Stdcall} calling convention is the name of the C routine. The leading
26089 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26090 the compiler. For instance the Win32 function:
26092 @smallexample
26093 @b{APIENTRY} int get_val (long);
26094 @end smallexample
26096 @noindent
26097 should be imported from Ada as follows:
26099 @smallexample @c ada
26100 @group
26101 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26102 pragma Import (Stdcall, Get_Val);
26103 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26104 @end group
26105 @end smallexample
26107 @noindent
26108 As for the @code{C} calling convention, when the @code{External_Name}
26109 parameter is missing, it is taken to be the name of the Ada entity in lower
26110 case. If instead of writing the above import pragma you write:
26112 @smallexample @c ada
26113 @group
26114 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26115 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26116 @end group
26117 @end smallexample
26119 @noindent
26120 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26121 of specifying the @code{External_Name} parameter you specify the
26122 @code{Link_Name} as in the following example:
26124 @smallexample @c ada
26125 @group
26126 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26127 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26128 @end group
26129 @end smallexample
26131 @noindent
26132 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26133 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26134 added at the end of the @code{Link_Name} by the compiler.
26136 @noindent
26137 Note, that in some special cases a DLL's entry point name lacks a trailing
26138 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26139 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26140 to handle those cases (see the description of the switches in
26141 @pxref{Using gnatdll} section).
26143 @node DLL Calling Convention
26144 @subsection @code{DLL} Calling Convention
26146 @noindent
26147 This convention, which is GNAT-specific, must be used when you want to
26148 import in Ada a variables defined in a DLL. For functions and procedures
26149 this convention is equivalent to the @code{Stdcall} convention. As an
26150 example, if a DLL contains a variable defined as:
26152 @smallexample
26153 int my_var;
26154 @end smallexample
26156 @noindent
26157 then, to access this variable from Ada you should write:
26159 @smallexample @c ada
26160 @group
26161 My_Var : Interfaces.C.int;
26162 pragma Import (DLL, My_Var);
26163 @end group
26164 @end smallexample
26166 The remarks concerning the @code{External_Name} and @code{Link_Name}
26167 parameters given in the previous sections equally apply to the @code{DLL}
26168 calling convention.
26170 @node Introduction to Dynamic Link Libraries (DLLs)
26171 @section Introduction to Dynamic Link Libraries (DLLs)
26172 @findex DLL
26174 @noindent
26175 A Dynamically Linked Library (DLL) is a library that can be shared by
26176 several applications running under Windows. A DLL can contain any number of
26177 routines and variables.
26179 One advantage of DLLs is that you can change and enhance them without
26180 forcing all the applications that depend on them to be relinked or
26181 recompiled. However, you should be aware than all calls to DLL routines are
26182 slower since, as you will understand below, such calls are indirect.
26184 To illustrate the remainder of this section, suppose that an application
26185 wants to use the services of a DLL @file{API.dll}. To use the services
26186 provided by @file{API.dll} you must statically link against an import
26187 library which contains a jump table with an entry for each routine and
26188 variable exported by the DLL. In the Microsoft world this import library is
26189 called @file{API.lib}. When using GNAT this import library is called either
26190 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26192 After you have statically linked your application with the import library
26193 and you run your application, here is what happens:
26195 @enumerate
26196 @item
26197 Your application is loaded into memory.
26199 @item
26200 The DLL @file{API.dll} is mapped into the address space of your
26201 application. This means that:
26203 @itemize @bullet
26204 @item
26205 The DLL will use the stack of the calling thread.
26207 @item
26208 The DLL will use the virtual address space of the calling process.
26210 @item
26211 The DLL will allocate memory from the virtual address space of the calling
26212 process.
26214 @item
26215 Handles (pointers) can be safely exchanged between routines in the DLL
26216 routines and routines in the application using the DLL.
26217 @end itemize
26219 @item
26220 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
26221 part of your application are initialized with the addresses of the routines
26222 and variables in @file{API.dll}.
26224 @item
26225 If present in @file{API.dll}, routines @code{DllMain} or
26226 @code{DllMainCRTStartup} are invoked. These routines typically contain
26227 the initialization code needed for the well-being of the routines and
26228 variables exported by the DLL.
26229 @end enumerate
26231 @noindent
26232 There is an additional point which is worth mentioning. In the Windows
26233 world there are two kind of DLLs: relocatable and non-relocatable
26234 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26235 in the target application address space. If the addresses of two
26236 non-relocatable DLLs overlap and these happen to be used by the same
26237 application, a conflict will occur and the application will run
26238 incorrectly. Hence, when possible, it is always preferable to use and
26239 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26240 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26241 User's Guide) removes the debugging symbols from the DLL but the DLL can
26242 still be relocated.
26244 As a side note, an interesting difference between Microsoft DLLs and
26245 Unix shared libraries, is the fact that on most Unix systems all public
26246 routines are exported by default in a Unix shared library, while under
26247 Windows the exported routines must be listed explicitly in a definition
26248 file (@pxref{The Definition File}).
26250 @node Using DLLs with GNAT
26251 @section Using DLLs with GNAT
26253 @menu
26254 * Creating an Ada Spec for the DLL Services::
26255 * Creating an Import Library::
26256 @end menu
26258 @noindent
26259 To use the services of a DLL, say @file{API.dll}, in your Ada application
26260 you must have:
26262 @enumerate
26263 @item
26264 The Ada spec for the routines and/or variables you want to access in
26265 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26266 header files provided with the DLL.
26268 @item
26269 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26270 mentioned an import library is a statically linked library containing the
26271 import table which will be filled at load time to point to the actual
26272 @file{API.dll} routines. Sometimes you don't have an import library for the
26273 DLL you want to use. The following sections will explain how to build one.
26275 @item
26276 The actual DLL, @file{API.dll}.
26277 @end enumerate
26279 @noindent
26280 Once you have all the above, to compile an Ada application that uses the
26281 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26282 you simply issue the command
26284 @smallexample
26285 $ gnatmake my_ada_app -largs -lAPI
26286 @end smallexample
26288 @noindent
26289 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
26290 tells the GNAT linker to look first for a library named @file{API.lib}
26291 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26292 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26293 contains the following pragma
26295 @smallexample @c ada
26296 pragma Linker_Options ("-lAPI");
26297 @end smallexample
26299 @noindent
26300 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
26301 command.
26303 If any one of the items above is missing you will have to create it
26304 yourself. The following sections explain how to do so using as an
26305 example a fictitious DLL called @file{API.dll}.
26307 @node Creating an Ada Spec for the DLL Services
26308 @subsection Creating an Ada Spec for the DLL Services
26310 @noindent
26311 A DLL typically comes with a C/C++ header file which provides the
26312 definitions of the routines and variables exported by the DLL. The Ada
26313 equivalent of this header file is a package spec that contains definitions
26314 for the imported entities. If the DLL you intend to use does not come with
26315 an Ada spec you have to generate one such spec yourself. For example if
26316 the header file of @file{API.dll} is a file @file{api.h} containing the
26317 following two definitions:
26319 @smallexample
26320 @group
26321 @cartouche
26322 int some_var;
26323 int get (char *);
26324 @end cartouche
26325 @end group
26326 @end smallexample
26328 @noindent
26329 then the equivalent Ada spec could be:
26331 @smallexample @c ada
26332 @group
26333 @cartouche
26334 with Interfaces.C.Strings;
26335 package API is
26336    use Interfaces;
26338    Some_Var : C.int;
26339    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26341 private
26342    pragma Import (C, Get);
26343    pragma Import (DLL, Some_Var);
26344 end API;
26345 @end cartouche
26346 @end group
26347 @end smallexample
26349 @noindent
26350 Note that a variable is @strong{always imported with a DLL convention}. A
26351 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26352 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26353 (@pxref{Windows Calling Conventions}).
26355 @node Creating an Import Library
26356 @subsection Creating an Import Library
26357 @cindex Import library
26359 @menu
26360 * The Definition File::
26361 * GNAT-Style Import Library::
26362 * Microsoft-Style Import Library::
26363 @end menu
26365 @noindent
26366 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26367 import library @file{libAPI.a} is available with @file{API.dll} you
26368 can skip this section. Otherwise read on.
26370 @node The Definition File
26371 @subsubsection The Definition File
26372 @cindex Definition file
26373 @findex .def
26375 @noindent
26376 As previously mentioned, and unlike Unix systems, the list of symbols
26377 that are exported from a DLL must be provided explicitly in Windows.
26378 The main goal of a definition file is precisely that: list the symbols
26379 exported by a DLL. A definition file (usually a file with a @code{.def}
26380 suffix) has the following structure:
26382 @smallexample
26383 @group
26384 @cartouche
26385 [LIBRARY @i{name}]
26386 [DESCRIPTION @i{string}]
26387 EXPORTS
26388    @i{symbol1}
26389    @i{symbol2}
26390    ...
26391 @end cartouche
26392 @end group
26393 @end smallexample
26395 @table @code
26396 @item LIBRARY @i{name}
26397 This section, which is optional, gives the name of the DLL.
26399 @item DESCRIPTION @i{string}
26400 This section, which is optional, gives a description string that will be
26401 embedded in the import library.
26403 @item EXPORTS
26404 This section gives the list of exported symbols (procedures, functions or
26405 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26406 section of @file{API.def} looks like:
26408 @smallexample
26409 @group
26410 @cartouche
26411 EXPORTS
26412    some_var
26413    get
26414 @end cartouche
26415 @end group
26416 @end smallexample
26417 @end table
26419 @noindent
26420 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26421 (@pxref{Windows Calling Conventions}) for a Stdcall
26422 calling convention function in the exported symbols list.
26424 @noindent
26425 There can actually be other sections in a definition file, but these
26426 sections are not relevant to the discussion at hand.
26428 @node GNAT-Style Import Library
26429 @subsubsection GNAT-Style Import Library
26431 @noindent
26432 To create a static import library from @file{API.dll} with the GNAT tools
26433 you should proceed as follows:
26435 @enumerate
26436 @item
26437 Create the definition file @file{API.def} (@pxref{The Definition File}).
26438 For that use the @code{dll2def} tool as follows:
26440 @smallexample
26441 $ dll2def API.dll > API.def
26442 @end smallexample
26444 @noindent
26445 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26446 to standard output the list of entry points in the DLL. Note that if
26447 some routines in the DLL have the @code{Stdcall} convention
26448 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26449 suffix then you'll have to edit @file{api.def} to add it.
26451 @noindent
26452 Here are some hints to find the right @code{@@}@i{nn} suffix.
26454 @enumerate
26455 @item
26456 If you have the Microsoft import library (.lib), it is possible to get
26457 the right symbols by using Microsoft @code{dumpbin} tool (see the
26458 corresponding Microsoft documentation for further details).
26460 @smallexample
26461 $ dumpbin /exports api.lib
26462 @end smallexample
26464 @item
26465 If you have a message about a missing symbol at link time the compiler
26466 tells you what symbol is expected. You just have to go back to the
26467 definition file and add the right suffix.
26468 @end enumerate
26470 @item
26471 Build the import library @code{libAPI.a}, using @code{gnatdll}
26472 (@pxref{Using gnatdll}) as follows:
26474 @smallexample
26475 $ gnatdll -e API.def -d API.dll
26476 @end smallexample
26478 @noindent
26479 @code{gnatdll} takes as input a definition file @file{API.def} and the
26480 name of the DLL containing the services listed in the definition file
26481 @file{API.dll}. The name of the static import library generated is
26482 computed from the name of the definition file as follows: if the
26483 definition file name is @i{xyz}@code{.def}, the import library name will
26484 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26485 @option{-e} could have been removed because the name of the definition
26486 file (before the ``@code{.def}'' suffix) is the same as the name of the
26487 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26488 @end enumerate
26490 @node Microsoft-Style Import Library
26491 @subsubsection Microsoft-Style Import Library
26493 @noindent
26494 With GNAT you can either use a GNAT-style or Microsoft-style import
26495 library. A Microsoft import library is needed only if you plan to make an
26496 Ada DLL available to applications developed with Microsoft
26497 tools (@pxref{Mixed-Language Programming on Windows}).
26499 To create a Microsoft-style import library for @file{API.dll} you
26500 should proceed as follows:
26502 @enumerate
26503 @item
26504 Create the definition file @file{API.def} from the DLL. For this use either
26505 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26506 tool (see the corresponding Microsoft documentation for further details).
26508 @item
26509 Build the actual import library using Microsoft's @code{lib} utility:
26511 @smallexample
26512 $ lib -machine:IX86 -def:API.def -out:API.lib
26513 @end smallexample
26515 @noindent
26516 If you use the above command the definition file @file{API.def} must
26517 contain a line giving the name of the DLL:
26519 @smallexample
26520 LIBRARY      "API"
26521 @end smallexample
26523 @noindent
26524 See the Microsoft documentation for further details about the usage of
26525 @code{lib}.
26526 @end enumerate
26528 @node Building DLLs with GNAT
26529 @section Building DLLs with GNAT
26530 @cindex DLLs, building
26532 @menu
26533 * Limitations When Using Ada DLLs from Ada::
26534 * Exporting Ada Entities::
26535 * Ada DLLs and Elaboration::
26536 * Ada DLLs and Finalization::
26537 * Creating a Spec for Ada DLLs::
26538 * Creating the Definition File::
26539 * Using gnatdll::
26540 @end menu
26542 @noindent
26543 This section explains how to build DLLs containing Ada code. These DLLs
26544 will be referred to as Ada DLLs in the remainder of this section.
26546 The steps required to build an Ada DLL that is to be used by Ada as well as
26547 non-Ada applications are as follows:
26549 @enumerate
26550 @item
26551 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
26552 @code{Stdcall} calling convention to avoid any Ada name mangling for the
26553 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
26554 skip this step if you plan to use the Ada DLL only from Ada applications.
26556 @item
26557 Your Ada code must export an initialization routine which calls the routine
26558 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
26559 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
26560 routine exported by the Ada DLL must be invoked by the clients of the DLL
26561 to initialize the DLL.
26563 @item
26564 When useful, the DLL should also export a finalization routine which calls
26565 routine @code{adafinal} generated by @code{gnatbind} to perform the
26566 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
26567 The finalization routine exported by the Ada DLL must be invoked by the
26568 clients of the DLL when the DLL services are no further needed.
26570 @item
26571 You must provide a spec for the services exported by the Ada DLL in each
26572 of the programming languages to which you plan to make the DLL available.
26574 @item
26575 You must provide a definition file listing the exported entities
26576 (@pxref{The Definition File}).
26578 @item
26579 Finally you must use @code{gnatdll} to produce the DLL and the import
26580 library (@pxref{Using gnatdll}).
26581 @end enumerate
26583 @noindent
26584 Note that a relocatable DLL stripped using the @code{strip} binutils
26585 tool will not be relocatable anymore. To build a DLL without debug
26586 information pass @code{-largs -s} to @code{gnatdll}.
26588 @node Limitations When Using Ada DLLs from Ada
26589 @subsection Limitations When Using Ada DLLs from Ada
26591 @noindent
26592 When using Ada DLLs from Ada applications there is a limitation users
26593 should be aware of. Because on Windows the GNAT run time is not in a DLL of
26594 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
26595 each Ada DLL includes the services of the GNAT run time that are necessary
26596 to the Ada code inside the DLL. As a result, when an Ada program uses an
26597 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
26598 one in the main program.
26600 It is therefore not possible to exchange GNAT run-time objects between the
26601 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
26602 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
26603 types, etc.
26605 It is completely safe to exchange plain elementary, array or record types,
26606 Windows object handles, etc.
26608 @node Exporting Ada Entities
26609 @subsection Exporting Ada Entities
26610 @cindex Export table
26612 @noindent
26613 Building a DLL is a way to encapsulate a set of services usable from any
26614 application. As a result, the Ada entities exported by a DLL should be
26615 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
26616 any Ada name mangling. Please note that the @code{Stdcall} convention
26617 should only be used for subprograms, not for variables. As an example here
26618 is an Ada package @code{API}, spec and body, exporting two procedures, a
26619 function, and a variable:
26621 @smallexample @c ada
26622 @group
26623 @cartouche
26624 with Interfaces.C; use Interfaces;
26625 package API is
26626    Count : C.int := 0;
26627    function Factorial (Val : C.int) return C.int;
26629    procedure Initialize_API;
26630    procedure Finalize_API;
26631    --  Initialization & Finalization routines. More in the next section.
26632 private
26633    pragma Export (C, Initialize_API);
26634    pragma Export (C, Finalize_API);
26635    pragma Export (C, Count);
26636    pragma Export (C, Factorial);
26637 end API;
26638 @end cartouche
26639 @end group
26640 @end smallexample
26642 @smallexample @c ada
26643 @group
26644 @cartouche
26645 package body API is
26646    function Factorial (Val : C.int) return C.int is
26647       Fact : C.int := 1;
26648    begin
26649       Count := Count + 1;
26650       for K in 1 .. Val loop
26651          Fact := Fact * K;
26652       end loop;
26653       return Fact;
26654    end Factorial;
26656    procedure Initialize_API is
26657       procedure Adainit;
26658       pragma Import (C, Adainit);
26659    begin
26660       Adainit;
26661    end Initialize_API;
26663    procedure Finalize_API is
26664       procedure Adafinal;
26665       pragma Import (C, Adafinal);
26666    begin
26667       Adafinal;
26668    end Finalize_API;
26669 end API;
26670 @end cartouche
26671 @end group
26672 @end smallexample
26674 @noindent
26675 If the Ada DLL you are building will only be used by Ada applications
26676 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
26677 convention. As an example, the previous package could be written as
26678 follows:
26680 @smallexample @c ada
26681 @group
26682 @cartouche
26683 package API is
26684    Count : Integer := 0;
26685    function Factorial (Val : Integer) return Integer;
26687    procedure Initialize_API;
26688    procedure Finalize_API;
26689    --  Initialization and Finalization routines.
26690 end API;
26691 @end cartouche
26692 @end group
26693 @end smallexample
26695 @smallexample @c ada
26696 @group
26697 @cartouche
26698 package body API is
26699    function Factorial (Val : Integer) return Integer is
26700       Fact : Integer := 1;
26701    begin
26702       Count := Count + 1;
26703       for K in 1 .. Val loop
26704          Fact := Fact * K;
26705       end loop;
26706       return Fact;
26707    end Factorial;
26709    ...
26710    --  The remainder of this package body is unchanged.
26711 end API;
26712 @end cartouche
26713 @end group
26714 @end smallexample
26716 @noindent
26717 Note that if you do not export the Ada entities with a @code{C} or
26718 @code{Stdcall} convention you will have to provide the mangled Ada names
26719 in the definition file of the Ada DLL
26720 (@pxref{Creating the Definition File}).
26722 @node Ada DLLs and Elaboration
26723 @subsection Ada DLLs and Elaboration
26724 @cindex DLLs and elaboration
26726 @noindent
26727 The DLL that you are building contains your Ada code as well as all the
26728 routines in the Ada library that are needed by it. The first thing a
26729 user of your DLL must do is elaborate the Ada code
26730 (@pxref{Elaboration Order Handling in GNAT}).
26732 To achieve this you must export an initialization routine
26733 (@code{Initialize_API} in the previous example), which must be invoked
26734 before using any of the DLL services. This elaboration routine must call
26735 the Ada elaboration routine @code{adainit} generated by the GNAT binder
26736 (@pxref{Binding with Non-Ada Main Programs}). See the body of
26737 @code{Initialize_Api} for an example. Note that the GNAT binder is
26738 automatically invoked during the DLL build process by the @code{gnatdll}
26739 tool (@pxref{Using gnatdll}).
26741 When a DLL is loaded, Windows systematically invokes a routine called
26742 @code{DllMain}. It would therefore be possible to call @code{adainit}
26743 directly from @code{DllMain} without having to provide an explicit
26744 initialization routine. Unfortunately, it is not possible to call
26745 @code{adainit} from the @code{DllMain} if your program has library level
26746 tasks because access to the @code{DllMain} entry point is serialized by
26747 the system (that is, only a single thread can execute ``through'' it at a
26748 time), which means that the GNAT run time will deadlock waiting for the
26749 newly created task to complete its initialization.
26751 @node Ada DLLs and Finalization
26752 @subsection Ada DLLs and Finalization
26753 @cindex DLLs and finalization
26755 @noindent
26756 When the services of an Ada DLL are no longer needed, the client code should
26757 invoke the DLL finalization routine, if available. The DLL finalization
26758 routine is in charge of releasing all resources acquired by the DLL. In the
26759 case of the Ada code contained in the DLL, this is achieved by calling
26760 routine @code{adafinal} generated by the GNAT binder
26761 (@pxref{Binding with Non-Ada Main Programs}).
26762 See the body of @code{Finalize_Api} for an
26763 example. As already pointed out the GNAT binder is automatically invoked
26764 during the DLL build process by the @code{gnatdll} tool
26765 (@pxref{Using gnatdll}).
26767 @node Creating a Spec for Ada DLLs
26768 @subsection Creating a Spec for Ada DLLs
26770 @noindent
26771 To use the services exported by the Ada DLL from another programming
26772 language (e.g. C), you have to translate the specs of the exported Ada
26773 entities in that language. For instance in the case of @code{API.dll},
26774 the corresponding C header file could look like:
26776 @smallexample
26777 @group
26778 @cartouche
26779 extern int *_imp__count;
26780 #define count (*_imp__count)
26781 int factorial (int);
26782 @end cartouche
26783 @end group
26784 @end smallexample
26786 @noindent
26787 It is important to understand that when building an Ada DLL to be used by
26788 other Ada applications, you need two different specs for the packages
26789 contained in the DLL: one for building the DLL and the other for using
26790 the DLL. This is because the @code{DLL} calling convention is needed to
26791 use a variable defined in a DLL, but when building the DLL, the variable
26792 must have either the @code{Ada} or @code{C} calling convention. As an
26793 example consider a DLL comprising the following package @code{API}:
26795 @smallexample @c ada
26796 @group
26797 @cartouche
26798 package API is
26799    Count : Integer := 0;
26800    ...
26801    --  Remainder of the package omitted.
26802 end API;
26803 @end cartouche
26804 @end group
26805 @end smallexample
26807 @noindent
26808 After producing a DLL containing package @code{API}, the spec that
26809 must be used to import @code{API.Count} from Ada code outside of the
26810 DLL is:
26812 @smallexample @c ada
26813 @group
26814 @cartouche
26815 package API is
26816    Count : Integer;
26817    pragma Import (DLL, Count);
26818 end API;
26819 @end cartouche
26820 @end group
26821 @end smallexample
26823 @node Creating the Definition File
26824 @subsection Creating the Definition File
26826 @noindent
26827 The definition file is the last file needed to build the DLL. It lists
26828 the exported symbols. As an example, the definition file for a DLL
26829 containing only package @code{API} (where all the entities are exported
26830 with a @code{C} calling convention) is:
26832 @smallexample
26833 @group
26834 @cartouche
26835 EXPORTS
26836     count
26837     factorial
26838     finalize_api
26839     initialize_api
26840 @end cartouche
26841 @end group
26842 @end smallexample
26844 @noindent
26845 If the @code{C} calling convention is missing from package @code{API},
26846 then the definition file contains the mangled Ada names of the above
26847 entities, which in this case are:
26849 @smallexample
26850 @group
26851 @cartouche
26852 EXPORTS
26853     api__count
26854     api__factorial
26855     api__finalize_api
26856     api__initialize_api
26857 @end cartouche
26858 @end group
26859 @end smallexample
26861 @node Using gnatdll
26862 @subsection Using @code{gnatdll}
26863 @findex gnatdll
26865 @menu
26866 * gnatdll Example::
26867 * gnatdll behind the Scenes::
26868 * Using dlltool::
26869 @end menu
26871 @noindent
26872 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
26873 and non-Ada sources that make up your DLL have been compiled.
26874 @code{gnatdll} is actually in charge of two distinct tasks: build the
26875 static import library for the DLL and the actual DLL. The form of the
26876 @code{gnatdll} command is
26878 @smallexample
26879 @cartouche
26880 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
26881 @end cartouche
26882 @end smallexample
26884 @noindent
26885 where @i{list-of-files} is a list of ALI and object files. The object
26886 file list must be the exact list of objects corresponding to the non-Ada
26887 sources whose services are to be included in the DLL. The ALI file list
26888 must be the exact list of ALI files for the corresponding Ada sources
26889 whose services are to be included in the DLL. If @i{list-of-files} is
26890 missing, only the static import library is generated.
26892 @noindent
26893 You may specify any of the following switches to @code{gnatdll}:
26895 @table @code
26896 @item -a[@var{address}]
26897 @cindex @option{-a} (@code{gnatdll})
26898 Build a non-relocatable DLL at @var{address}. If @var{address} is not
26899 specified the default address @var{0x11000000} will be used. By default,
26900 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
26901 advise the reader to build relocatable DLL.
26903 @item -b @var{address}
26904 @cindex @option{-b} (@code{gnatdll})
26905 Set the relocatable DLL base address. By default the address is
26906 @var{0x11000000}.
26908 @item -bargs @var{opts}
26909 @cindex @option{-bargs} (@code{gnatdll})
26910 Binder options. Pass @var{opts} to the binder.
26912 @item -d @var{dllfile}
26913 @cindex @option{-d} (@code{gnatdll})
26914 @var{dllfile} is the name of the DLL. This switch must be present for
26915 @code{gnatdll} to do anything. The name of the generated import library is
26916 obtained algorithmically from @var{dllfile} as shown in the following
26917 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
26918 @code{libxyz.a}. The name of the definition file to use (if not specified
26919 by option @option{-e}) is obtained algorithmically from @var{dllfile}
26920 as shown in the following example:
26921 if @var{dllfile} is @code{xyz.dll}, the definition
26922 file used is @code{xyz.def}.
26924 @item -e @var{deffile}
26925 @cindex @option{-e} (@code{gnatdll})
26926 @var{deffile} is the name of the definition file.
26928 @item -g
26929 @cindex @option{-g} (@code{gnatdll})
26930 Generate debugging information. This information is stored in the object
26931 file and copied from there to the final DLL file by the linker,
26932 where it can be read by the debugger. You must use the
26933 @option{-g} switch if you plan on using the debugger or the symbolic
26934 stack traceback.
26936 @item -h
26937 @cindex @option{-h} (@code{gnatdll})
26938 Help mode. Displays @code{gnatdll} switch usage information.
26940 @item -Idir
26941 @cindex @option{-I} (@code{gnatdll})
26942 Direct @code{gnatdll} to search the @var{dir} directory for source and
26943 object files needed to build the DLL.
26944 (@pxref{Search Paths and the Run-Time Library (RTL)}).
26946 @item -k
26947 @cindex @option{-k} (@code{gnatdll})
26948 Removes the @code{@@}@i{nn} suffix from the import library's exported
26949 names. You must specified this option if you want to use a
26950 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
26951 has been removed. This is the case for most of the Windows NT DLL for
26952 example. This option has no effect when @option{-n} option is specified.
26954 @item -l @var{file}
26955 @cindex @option{-l} (@code{gnatdll})
26956 The list of ALI and object files used to build the DLL are listed in
26957 @var{file}, instead of being given in the command line. Each line in
26958 @var{file} contains the name of an ALI or object file.
26960 @item -n
26961 @cindex @option{-n} (@code{gnatdll})
26962 No Import. Do not create the import library.
26964 @item -q
26965 @cindex @option{-q} (@code{gnatdll})
26966 Quiet mode. Do not display unnecessary messages.
26968 @item -v
26969 @cindex @option{-v} (@code{gnatdll})
26970 Verbose mode. Display extra information.
26972 @item -largs @var{opts}
26973 @cindex @option{-largs} (@code{gnatdll})
26974 Linker options. Pass @var{opts} to the linker.
26975 @end table
26977 @node gnatdll Example
26978 @subsubsection @code{gnatdll} Example
26980 @noindent
26981 As an example the command to build a relocatable DLL from @file{api.adb}
26982 once @file{api.adb} has been compiled and @file{api.def} created is
26984 @smallexample
26985 $ gnatdll -d api.dll api.ali
26986 @end smallexample
26988 @noindent
26989 The above command creates two files: @file{libapi.a} (the import
26990 library) and @file{api.dll} (the actual DLL). If you want to create
26991 only the DLL, just type:
26993 @smallexample
26994 $ gnatdll -d api.dll -n api.ali
26995 @end smallexample
26997 @noindent
26998 Alternatively if you want to create just the import library, type:
27000 @smallexample
27001 $ gnatdll -d api.dll
27002 @end smallexample
27004 @node gnatdll behind the Scenes
27005 @subsubsection @code{gnatdll} behind the Scenes
27007 @noindent
27008 This section details the steps involved in creating a DLL. @code{gnatdll}
27009 does these steps for you. Unless you are interested in understanding what
27010 goes on behind the scenes, you should skip this section.
27012 We use the previous example of a DLL containing the Ada package @code{API},
27013 to illustrate the steps necessary to build a DLL. The starting point is a
27014 set of objects that will make up the DLL and the corresponding ALI
27015 files. In the case of this example this means that @file{api.o} and
27016 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27017 the following:
27019 @enumerate
27020 @item
27021 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27022 the information necessary to generate relocation information for the
27023 DLL.
27025 @smallexample
27026 @group
27027 $ gnatbind -n api
27028 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27029 @end group
27030 @end smallexample
27032 @noindent
27033 In addition to the base file, the @code{gnatlink} command generates an
27034 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27035 asks @code{gnatlink} to generate the routines @code{DllMain} and
27036 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27037 is loaded into memory.
27039 @item
27040 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27041 export table (@file{api.exp}). The export table contains the relocation
27042 information in a form which can be used during the final link to ensure
27043 that the Windows loader is able to place the DLL anywhere in memory.
27045 @smallexample
27046 @group
27047 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27048           --output-exp api.exp
27049 @end group
27050 @end smallexample
27052 @item
27053 @code{gnatdll} builds the base file using the new export table. Note that
27054 @code{gnatbind} must be called once again since the binder generated file
27055 has been deleted during the previous call to @code{gnatlink}.
27057 @smallexample
27058 @group
27059 $ gnatbind -n api
27060 $ gnatlink api -o api.jnk api.exp -mdll
27061       -Wl,--base-file,api.base
27062 @end group
27063 @end smallexample
27065 @item
27066 @code{gnatdll} builds the new export table using the new base file and
27067 generates the DLL import library @file{libAPI.a}.
27069 @smallexample
27070 @group
27071 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27072           --output-exp api.exp --output-lib libAPI.a
27073 @end group
27074 @end smallexample
27076 @item
27077 Finally @code{gnatdll} builds the relocatable DLL using the final export
27078 table.
27080 @smallexample
27081 @group
27082 $ gnatbind -n api
27083 $ gnatlink api api.exp -o api.dll -mdll
27084 @end group
27085 @end smallexample
27086 @end enumerate
27088 @node Using dlltool
27089 @subsubsection Using @code{dlltool}
27091 @noindent
27092 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27093 DLLs and static import libraries. This section summarizes the most
27094 common @code{dlltool} switches. The form of the @code{dlltool} command
27097 @smallexample
27098 $ dlltool [@var{switches}]
27099 @end smallexample
27101 @noindent
27102 @code{dlltool} switches include:
27104 @table @option
27105 @item --base-file @var{basefile}
27106 @cindex @option{--base-file} (@command{dlltool})
27107 Read the base file @var{basefile} generated by the linker. This switch
27108 is used to create a relocatable DLL.
27110 @item --def @var{deffile}
27111 @cindex @option{--def} (@command{dlltool})
27112 Read the definition file.
27114 @item --dllname @var{name}
27115 @cindex @option{--dllname} (@command{dlltool})
27116 Gives the name of the DLL. This switch is used to embed the name of the
27117 DLL in the static import library generated by @code{dlltool} with switch
27118 @option{--output-lib}.
27120 @item -k
27121 @cindex @option{-k} (@command{dlltool})
27122 Kill @code{@@}@i{nn} from exported names
27123 (@pxref{Windows Calling Conventions}
27124 for a discussion about @code{Stdcall}-style symbols.
27126 @item --help
27127 @cindex @option{--help} (@command{dlltool})
27128 Prints the @code{dlltool} switches with a concise description.
27130 @item --output-exp @var{exportfile}
27131 @cindex @option{--output-exp} (@command{dlltool})
27132 Generate an export file @var{exportfile}. The export file contains the
27133 export table (list of symbols in the DLL) and is used to create the DLL.
27135 @item --output-lib @i{libfile}
27136 @cindex @option{--output-lib} (@command{dlltool})
27137 Generate a static import library @var{libfile}.
27139 @item -v
27140 @cindex @option{-v} (@command{dlltool})
27141 Verbose mode.
27143 @item --as @i{assembler-name}
27144 @cindex @option{--as} (@command{dlltool})
27145 Use @i{assembler-name} as the assembler. The default is @code{as}.
27146 @end table
27148 @node GNAT and Windows Resources
27149 @section GNAT and Windows Resources
27150 @cindex Resources, windows
27152 @menu
27153 * Building Resources::
27154 * Compiling Resources::
27155 * Using Resources::
27156 @end menu
27158 @noindent
27159 Resources are an easy way to add Windows specific objects to your
27160 application. The objects that can be added as resources include:
27162 @itemize @bullet
27163 @item
27164 menus
27166 @item
27167 accelerators
27169 @item
27170 dialog boxes
27172 @item
27173 string tables
27175 @item
27176 bitmaps
27178 @item
27179 cursors
27181 @item
27182 icons
27184 @item
27185 fonts
27186 @end itemize
27188 @noindent
27189 This section explains how to build, compile and use resources.
27191 @node Building Resources
27192 @subsection Building Resources
27193 @cindex Resources, building
27195 @noindent
27196 A resource file is an ASCII file. By convention resource files have an
27197 @file{.rc} extension.
27198 The easiest way to build a resource file is to use Microsoft tools
27199 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27200 @code{dlgedit.exe} to build dialogs.
27201 It is always possible to build an @file{.rc} file yourself by writing a
27202 resource script.
27204 It is not our objective to explain how to write a resource file. A
27205 complete description of the resource script language can be found in the
27206 Microsoft documentation.
27208 @node Compiling Resources
27209 @subsection Compiling Resources
27210 @findex rc
27211 @findex windres
27212 @cindex Resources, compiling
27214 @noindent
27215 This section describes how to build a GNAT-compatible (COFF) object file
27216 containing the resources. This is done using the Resource Compiler
27217 @code{windres} as follows:
27219 @smallexample
27220 $ windres -i myres.rc -o myres.o
27221 @end smallexample
27223 @noindent
27224 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
27225 file. You can specify an alternate preprocessor (usually named
27226 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27227 parameter. A list of all possible options may be obtained by entering
27228 the command @code{windres} @option{--help}.
27230 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27231 to produce a @file{.res} file (binary resource file). See the
27232 corresponding Microsoft documentation for further details. In this case
27233 you need to use @code{windres} to translate the @file{.res} file to a
27234 GNAT-compatible object file as follows:
27236 @smallexample
27237 $ windres -i myres.res -o myres.o
27238 @end smallexample
27240 @node Using Resources
27241 @subsection Using Resources
27242 @cindex Resources, using
27244 @noindent
27245 To include the resource file in your program just add the
27246 GNAT-compatible object file for the resource(s) to the linker
27247 arguments. With @code{gnatmake} this is done by using the @option{-largs}
27248 option:
27250 @smallexample
27251 $ gnatmake myprog -largs myres.o
27252 @end smallexample
27254 @node Debugging a DLL
27255 @section Debugging a DLL
27256 @cindex DLL debugging
27258 @menu
27259 * Program and DLL Both Built with GCC/GNAT::
27260 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27261 @end menu
27263 @noindent
27264 Debugging a DLL is similar to debugging a standard program. But
27265 we have to deal with two different executable parts: the DLL and the
27266 program that uses it. We have the following four possibilities:
27268 @enumerate 1
27269 @item
27270 The program and the DLL are built with @code{GCC/GNAT}.
27271 @item
27272 The program is built with foreign tools and the DLL is built with
27273 @code{GCC/GNAT}.
27274 @item
27275 The program is built with @code{GCC/GNAT} and the DLL is built with
27276 foreign tools.
27277 @item
27278 @end enumerate
27280 @noindent
27281 In this section we address only cases one and two above.
27282 There is no point in trying to debug
27283 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27284 information in it. To do so you must use a debugger compatible with the
27285 tools suite used to build the DLL.
27287 @node Program and DLL Both Built with GCC/GNAT
27288 @subsection Program and DLL Both Built with GCC/GNAT
27290 @noindent
27291 This is the simplest case. Both the DLL and the program have @code{GDB}
27292 compatible debugging information. It is then possible to break anywhere in
27293 the process. Let's suppose here that the main procedure is named
27294 @code{ada_main} and that in the DLL there is an entry point named
27295 @code{ada_dll}.
27297 @noindent
27298 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27299 program must have been built with the debugging information (see GNAT -g
27300 switch). Here are the step-by-step instructions for debugging it:
27302 @enumerate 1
27303 @item Launch @code{GDB} on the main program.
27305 @smallexample
27306 $ gdb -nw ada_main
27307 @end smallexample
27309 @item Break on the main procedure and run the program.
27311 @smallexample
27312 (gdb) break ada_main
27313 (gdb) run
27314 @end smallexample
27316 @noindent
27317 This step is required to be able to set a breakpoint inside the DLL. As long
27318 as the program is not run, the DLL is not loaded. This has the
27319 consequence that the DLL debugging information is also not loaded, so it is not
27320 possible to set a breakpoint in the DLL.
27322 @item Set a breakpoint inside the DLL
27324 @smallexample
27325 (gdb) break ada_dll
27326 (gdb) run
27327 @end smallexample
27329 @end enumerate
27331 @noindent
27332 At this stage a breakpoint is set inside the DLL. From there on
27333 you can use the standard approach to debug the whole program
27334 (@pxref{Running and Debugging Ada Programs}).
27336 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27337 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27339 @menu
27340 * Debugging the DLL Directly::
27341 * Attaching to a Running Process::
27342 @end menu
27344 @noindent
27345 In this case things are slightly more complex because it is not possible to
27346 start the main program and then break at the beginning to load the DLL and the
27347 associated DLL debugging information. It is not possible to break at the
27348 beginning of the program because there is no @code{GDB} debugging information,
27349 and therefore there is no direct way of getting initial control. This
27350 section addresses this issue by describing some methods that can be used
27351 to break somewhere in the DLL to debug it.
27353 @noindent
27354 First suppose that the main procedure is named @code{main} (this is for
27355 example some C code built with Microsoft Visual C) and that there is a
27356 DLL named @code{test.dll} containing an Ada entry point named
27357 @code{ada_dll}.
27359 @noindent
27360 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27361 been built with debugging information (see GNAT -g option).
27363 @node Debugging the DLL Directly
27364 @subsubsection Debugging the DLL Directly
27366 @enumerate 1
27367 @item
27368 Launch the debugger on the DLL.
27370 @smallexample
27371 $ gdb -nw test.dll
27372 @end smallexample
27374 @item Set a breakpoint on a DLL subroutine.
27376 @smallexample
27377 (gdb) break ada_dll
27378 @end smallexample
27380 @item
27381 Specify the executable file to @code{GDB}.
27383 @smallexample
27384 (gdb) exec-file main.exe
27385 @end smallexample
27387 @item
27388 Run the program.
27390 @smallexample
27391 (gdb) run
27392 @end smallexample
27394 @noindent
27395 This will run the program until it reaches the breakpoint that has been
27396 set. From that point you can use the standard way to debug a program
27397 as described in (@pxref{Running and Debugging Ada Programs}).
27399 @end enumerate
27401 @noindent
27402 It is also possible to debug the DLL by attaching to a running process.
27404 @node Attaching to a Running Process
27405 @subsubsection Attaching to a Running Process
27406 @cindex DLL debugging, attach to process
27408 @noindent
27409 With @code{GDB} it is always possible to debug a running process by
27410 attaching to it. It is possible to debug a DLL this way. The limitation
27411 of this approach is that the DLL must run long enough to perform the
27412 attach operation. It may be useful for instance to insert a time wasting
27413 loop in the code of the DLL to meet this criterion.
27415 @enumerate 1
27417 @item Launch the main program @file{main.exe}.
27419 @smallexample
27420 $ main
27421 @end smallexample
27423 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27424 that the process PID for @file{main.exe} is 208.
27426 @item Launch gdb.
27428 @smallexample
27429 $ gdb -nw
27430 @end smallexample
27432 @item Attach to the running process to be debugged.
27434 @smallexample
27435 (gdb) attach 208
27436 @end smallexample
27438 @item Load the process debugging information.
27440 @smallexample
27441 (gdb) symbol-file main.exe
27442 @end smallexample
27444 @item Break somewhere in the DLL.
27446 @smallexample
27447 (gdb) break ada_dll
27448 @end smallexample
27450 @item Continue process execution.
27452 @smallexample
27453 (gdb) continue
27454 @end smallexample
27456 @end enumerate
27458 @noindent
27459 This last step will resume the process execution, and stop at
27460 the breakpoint we have set. From there you can use the standard
27461 approach to debug a program as described in
27462 (@pxref{Running and Debugging Ada Programs}).
27464 @node GNAT and COM/DCOM Objects
27465 @section GNAT and COM/DCOM Objects
27466 @findex COM
27467 @findex DCOM
27469 @noindent
27470 This section is temporarily left blank.
27472 @end ifset
27475 @c **********************************
27476 @c * GNU Free Documentation License *
27477 @c **********************************
27478 @include fdl.texi
27479 @c GNU Free Documentation License
27481 @node Index,,GNU Free Documentation License, Top
27482 @unnumbered Index
27484 @printindex cp
27486 @contents
27487 @c Put table of contents at end, otherwise it precedes the "title page" in
27488 @c the .txt version
27489 @c Edit the pdf file to move the contents to the beginning, after the title
27490 @c page
27492 @bye